Project

General

Profile

Bug #3527 » btech.py

proposed driver for test, will fix the "Radio Identification failed" with the BTECH UV-2501+220 and add Sainsonic GT-890 - Pavel Milanes, 04/15/2016 08:41 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
} 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

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

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

    
184
"""
185

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

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

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

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

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

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

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

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

    
252

    
253
##### ID strings #####################################################
254

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

    
262

    
263
# B-TECH UV-2501+220 pre-production units
264
UV2501_220pp_fp = "M3C281"
265
# extra block read for the 2501+220 pre-production units
266
# the same for all of this radios so far
267
UV2501_220pp_id = "      280528"
268
# B-TECH UV-2501+220
269
UV2501_220_fp = "M3G201"
270
# new variant, let's call it Generation 2
271
UV2501_220G2_fp = "BTG211"
272

    
273

    
274
# B-TECH UV-5001 pre-production units + 1st Gen radios
275
UV5001pp_fp = "V19204"
276
# B-TECH UV-5001 alpha units
277
UV5001alpha_fp = "V28204"
278
# B-TECH UV-5001 second generation (2G) radios
279
UV5001G2_fp = "BTG214"
280
# B-TECH UV-5001 second generation (2G2)
281
UV5001G22_fp = "V2G204"
282

    
283

    
284
# WACCOM Mini-8900
285
MINI8900_fp = "M28854"
286

    
287

    
288
# QYT KT-UV980 & JetStream JT2705M
289
KTUV980_fp = "H28854"
290

    
291

    
292
# QYT KT8900 & Juentai JT-6188
293
KT8900_fp = "M29154"
294
# this radio has an extra ID
295
KT8900_id = "      303688"
296

    
297

    
298
# Sainsonic GT890
299
GT890_fp = "M2G1F4"
300
# this need a second id
301
# and is the same of the QYT KT8900
302

    
303

    
304
#### MAGICS
305
# for the Waccom Mini-8900
306
MSTRING_MINI8900 = "\x55\xA5\xB5\x45\x55\x45\x4d\x02"
307
# for the B-TECH UV-2501+220 (including pre production ones)
308
MSTRING_220 = "\x55\x20\x15\x12\x12\x01\x4d\x02"
309
# for the QYT KT8900
310
MSTRING_KT8900 = "\x55\x20\x15\x09\x16\x45\x4D\x02"
311
# magic string for all other models
312
MSTRING = "\x55\x20\x15\x09\x20\x45\x4d\x02"
313

    
314

    
315
def _clean_buffer(radio):
316
    """Cleaning the read serial buffer, hard timeout to survive an infinite
317
    data stream"""
318

    
319
    # touching the serial timeout to optimize the flushing
320
    # restored at the end to the default value
321
    radio.pipe.setTimeout(0.1)
322
    dump = "1"
323
    datacount = 0
324

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

    
335
        # restore the default serial timeout
336
        radio.pipe.setTimeout(STIMEOUT)
337

    
338
    except Exception:
339
        raise errors.RadioError("Unknown error cleaning the serial buffer")
340

    
341

    
342
def _rawrecv(radio, amount):
343
    """Raw read from the radio device, less intensive way"""
344

    
345
    data = ""
346

    
347
    try:
348
        data = radio.pipe.read(amount)
349

    
350
        # DEBUG
351
        if debug is True:
352
            LOG.debug("<== (%d) bytes:\n\n%s" %
353
                      (len(data), util.hexprint(data)))
354

    
355
        # fail if no data is received
356
        if len(data) == 0:
357
            raise errors.RadioError("No data received from radio")
358

    
359
        # notice on the logs if short
360
        if len(data) < amount:
361
            LOG.warn("Short reading %d bytes from the %d requested." %
362
                     (len(data), amount))
363

    
364
    except:
365
        raise errors.RadioError("Error reading data from radio")
366

    
367
    return data
368

    
369

    
370
def _send(radio, data):
371
    """Send data to the radio device"""
372

    
373
    try:
374
        for byte in data:
375
            radio.pipe.write(byte)
376

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

    
384

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

    
392
    return frame
393

    
394

    
395
def _recv(radio, addr):
396
    """Get data from the radio all at once to lower syscalls load"""
397

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

    
401
    # get the whole block
402
    block = _rawrecv(radio, BLOCK_SIZE + 5)
403

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

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

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

    
419
    # return the data
420
    return block[5:]
421

    
422

    
423
def _start_clone_mode(radio, status):
424
    """Put the radio in clone mode and get the ident string, 3 tries"""
425

    
426
    # cleaning the serial buffer
427
    _clean_buffer(radio)
428

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

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

    
441
            # send the magic word
442
            _send(radio, radio._magic)
443

    
444
            # Now you get a x06 of ACK if all goes well
445
            ack = radio.pipe.read(1)
446

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

    
453
                return True
454

    
455
        return False
456

    
457
    except errors.RadioError:
458
        raise
459
    except Exception, e:
460
        raise errors.RadioError("Error sending Magic to radio:\n%s" % e)
461

    
462

    
463
def _do_ident(radio, status, upload=False):
464
    """Put the radio in PROGRAM mode & identify it"""
465
    #  set the serial discipline
466
    radio.pipe.setBaudrate(9600)
467
    radio.pipe.setParity("N")
468

    
469
    # open the radio into program mode
470
    if _start_clone_mode(radio, status) is False:
471
        raise errors.RadioError("Radio didn't entered in the clone mode")
472

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

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

    
480
    # check if ident is OK
481
    itis = False
482
    for fp in radio._fileid:
483
        if fp in ident:
484
            itis = True
485
            break
486

    
487
    if itis is False:
488
        LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
489
        raise errors.RadioError("Radio identification failed.")
490

    
491
    # some radios needs a extra read and check for a code on it, this ones
492
    # has the check value in the _id2 var, others simply False
493
    if radio._id2 is not False:
494
        # lower the timeout here as this radios are reseting due to timeout
495
        radio.pipe.setTimeout(0.05)
496

    
497
        # query & receive the extra ID
498
        _send(radio, _make_frame("S", 0x3DF0, 16))
499
        id2 = _rawrecv(radio, 21)
500

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

    
508
        # ok, the correct string must be in the received data
509
        if radio._id2 not in id2:
510
            LOG.debug("Full *BAD* extra ID on the %s is: \n%s" %
511
                      (radio.MODEL, util.hexprint(id2)))
512
            raise errors.RadioError("The extra ID is wrong, aborting.")
513

    
514
        # this radios need a extra request/answer here on the upload
515
        # the amount of data received depends of the radio type
516
        #
517
        # also the first block of TX must no have the ACK at the beginning
518
        # see _upload for this.
519
        if upload is True:
520
            # send an ACK
521
            _send(radio, ACK_CMD)
522

    
523
            # the amount of data depend on the radio, so far we have two radios
524
            # reading two bytes with an ACK at the end and just ONE with just
525
            # one byte (QYT KT8900)
526
            # the JT-6188 appears a clone of the last, but reads TWO bytes.
527
            #
528
            # we will read two bytes with a custom timeout to not penalize the
529
            # users for this.
530
            #
531
            # we just check for a response and last byte being a ACK, that is
532
            # the common stone for all radios (3 so far)
533
            ack = _rawrecv(radio, 2)
534

    
535
            # checking
536
            if len(ack) == 0 or ack[-1:] != ACK_CMD:
537
                raise errors.RadioError("Radio didn't ACK the upload")
538

    
539
            # restore the default serial timeout
540
            radio.pipe.setTimeout(STIMEOUT)
541

    
542
    # DEBUG
543
    LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL))
544

    
545
    return True
546

    
547

    
548
def _download(radio):
549
    """Get the memory map"""
550

    
551
    # UI progress
552
    status = chirp_common.Status()
553

    
554
    # put radio in program mode and identify it
555
    _do_ident(radio, status)
556

    
557
    # the models that doesn't have the extra ID have to make a dummy read here
558
    if radio._id2 is False:
559
        _send(radio, _make_frame("S", 0, BLOCK_SIZE))
560
        discard = _rawrecv(radio, BLOCK_SIZE + 5)
561

    
562
        if debug is True:
563
            LOG.info("Dummy first block read done, got this:\n\n %s",
564
                     util.hexprint(discard))
565

    
566
    # reset the progress bar in the UI
567
    status.max = MEM_SIZE / BLOCK_SIZE
568
    status.msg = "Cloning from radio..."
569
    status.cur = 0
570
    radio.status_fn(status)
571

    
572
    # cleaning the serial buffer
573
    _clean_buffer(radio)
574

    
575
    data = ""
576
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
577
        # sending the read request
578
        _send(radio, _make_frame("S", addr, BLOCK_SIZE))
579

    
580
        # read
581
        d = _recv(radio, addr)
582

    
583
        # aggregate the data
584
        data += d
585

    
586
        # UI Update
587
        status.cur = addr / BLOCK_SIZE
588
        status.msg = "Cloning from radio..."
589
        radio.status_fn(status)
590

    
591
    return data
592

    
593

    
594
def _upload(radio):
595
    """Upload procedure"""
596

    
597
    # The UPLOAD mem is restricted to lower than 0x3100,
598
    # so we will overide that here localy
599
    MEM_SIZE = 0x3100
600

    
601
    # UI progress
602
    status = chirp_common.Status()
603

    
604
    # put radio in program mode and identify it
605
    _do_ident(radio, status, True)
606

    
607
    # get the data to upload to radio
608
    data = radio.get_mmap()
609

    
610
    # Reset the UI progress
611
    status.max = MEM_SIZE / TX_BLOCK_SIZE
612
    status.cur = 0
613
    status.msg = "Cloning to radio..."
614
    radio.status_fn(status)
615

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

    
620
    # cleaning the serial buffer
621
    _clean_buffer(radio)
622

    
623
    # the fun start here
624
    for addr in range(0, MEM_SIZE, TX_BLOCK_SIZE):
625
        # getting the block of data to send
626
        d = data[addr:addr + TX_BLOCK_SIZE]
627

    
628
        # build the frame to send
629
        frame = _make_frame("X", addr, TX_BLOCK_SIZE, d)
630

    
631
        # first block must not send the ACK at the beginning for the
632
        # ones that has the extra id, since this have to do a extra step
633
        if addr == 0 and radio._id2 is not False:
634
            frame = frame[1:]
635

    
636
        # send the frame
637
        _send(radio, frame)
638

    
639
        # receiving the response
640
        ack = _rawrecv(radio, 1)
641

    
642
        # basic check
643
        if len(ack) != 1:
644
            raise errors.RadioError("No ACK when writing block 0x%04x" % addr)
645

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

    
649
         # UI Update
650
        status.cur = addr / TX_BLOCK_SIZE
651
        status.msg = "Cloning to radio..."
652
        radio.status_fn(status)
653

    
654

    
655
def model_match(cls, data):
656
    """Match the opened/downloaded image to the correct version"""
657
    rid = data[0x3f70:0x3f76]
658

    
659
    if rid in cls._fileid:
660
        return True
661

    
662
    return False
663

    
664

    
665
def _decode_ranges(low, high):
666
    """Unpack the data in the ranges zones in the memmap and return
667
    a tuple with the integer corresponding to the Mhz it means"""
668
    ilow = int(low[0]) * 100 + int(low[1]) * 10 + int(low[2])
669
    ihigh = int(high[0]) * 100 + int(high[1]) * 10 + int(high[2])
670
    ilow *= 1000000
671
    ihigh *= 1000000
672

    
673
    return (ilow, ihigh)
674

    
675

    
676
def _split(rf, f1, f2):
677
    """Returns False if the two freqs are in the same band (no split)
678
    or True otherwise"""
679

    
680
    # determine if the two freqs are in the same band
681
    for low, high in rf.valid_bands:
682
        if f1 >= low and f1 <= high and \
683
                f2 >= low and f2 <= high:
684
            # if the two freqs are on the same Band this is not a split
685
            return False
686

    
687
    # if you get here is because the freq pairs are split
688
    return False
689

    
690

    
691
class BTech(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio):
692
    """BTECH's UV-5001 and alike radios"""
693
    VENDOR = "BTECH"
694
    MODEL = ""
695
    IDENT = ""
696
    _vhf_range = (130000000, 180000000)
697
    _220_range = (210000000, 231000000)
698
    _uhf_range = (400000000, 521000000)
699
    _upper = 199
700
    _magic = MSTRING
701
    _fileid = None
702
    _id2 = False
703

    
704
    @classmethod
705
    def get_prompts(cls):
706
        rp = chirp_common.RadioPrompts()
707
        rp.experimental = \
708
            ('This driver is experimental.\n'
709
             '\n'
710
             'Please keep a copy of your memories with the original software '
711
             'if you treasure them, this driver is new and may contain'
712
             ' bugs.\n'
713
             '\n'
714
             )
715
        rp.pre_download = _(dedent("""\
716
            Follow these instructions to download your info:
717

    
718
            1 - Turn off your radio
719
            2 - Connect your interface cable
720
            3 - Turn on your radio
721
            4 - Do the download of your radio data
722

    
723
            """))
724
        rp.pre_upload = _(dedent("""\
725
            Follow these instructions to upload your info:
726

    
727
            1 - Turn off your radio
728
            2 - Connect your interface cable
729
            3 - Turn on your radio
730
            4 - Do the upload of your radio data
731

    
732
            """))
733
        return rp
734

    
735
    def get_features(self):
736
        """Get the radio's features"""
737

    
738
        # we will use the following var as global
739
        global POWER_LEVELS
740

    
741
        rf = chirp_common.RadioFeatures()
742
        rf.has_settings = True
743
        rf.has_bank = False
744
        rf.has_tuning_step = False
745
        rf.can_odd_split = True
746
        rf.has_name = True
747
        rf.has_offset = True
748
        rf.has_mode = True
749
        rf.has_dtcs = True
750
        rf.has_rx_dtcs = True
751
        rf.has_dtcs_polarity = True
752
        rf.has_ctone = True
753
        rf.has_cross = True
754
        rf.valid_modes = MODES
755
        rf.valid_characters = VALID_CHARS
756
        rf.valid_name_length = NAME_LENGTH
757
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
758
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
759
        rf.valid_cross_modes = [
760
            "Tone->Tone",
761
            "DTCS->",
762
            "->DTCS",
763
            "Tone->DTCS",
764
            "DTCS->Tone",
765
            "->Tone",
766
            "DTCS->DTCS"]
767
        rf.valid_skips = SKIP_VALUES
768
        rf.valid_dtcs_codes = DTCS
769
        rf.memory_bounds = (0, self._upper)
770

    
771
        # power levels
772
        if self.MODEL == "UV-5001":
773
            POWER_LEVELS = UV5001_POWER_LEVELS  # Higher power (50W)
774
        else:
775
            POWER_LEVELS = NORMAL_POWER_LEVELS  # Lower power (25W)
776

    
777
        rf.valid_power_levels = POWER_LEVELS
778

    
779
        # bands
780
        rf.valid_bands = [self._vhf_range, self._uhf_range]
781

    
782
        # 2501+220
783
        if self.MODEL == "UV-2501+220":
784
            rf.valid_bands.append(self._220_range)
785

    
786
        return rf
787

    
788
    def sync_in(self):
789
        """Download from radio"""
790
        data = _download(self)
791
        self._mmap = memmap.MemoryMap(data)
792
        self.process_mmap()
793

    
794
    def sync_out(self):
795
        """Upload to radio"""
796
        try:
797
            _upload(self)
798
        except errors.RadioError:
799
            raise
800
        except Exception, e:
801
            raise errors.RadioError("Error: %s" % e)
802

    
803
    def set_options(self):
804
        """This is to read the options from the image and set it in the
805
        environment, for now just the limits of the freqs in the VHF/UHF
806
        ranges"""
807

    
808
        # setting the correct ranges for each radio type
809
        if "+220" in self.MODEL:
810
            # the model 2501+220 has a segment in 220
811
            # and a different position in the memmap
812
            ranges = self._memobj.ranges220
813
        else:
814
            ranges = self._memobj.ranges
815

    
816
        # the normal dual bands
817
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
818
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
819

    
820
        # DEBUG
821
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
822
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
823

    
824
        # 220Mhz case
825
        if "+220" in self.MODEL:
826
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
827
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
828
            self._220_range = vhf2
829

    
830
        # set the class with the real data
831
        self._vhf_range = vhf
832
        self._uhf_range = uhf
833

    
834
    def process_mmap(self):
835
        """Process the mem map into the mem object"""
836

    
837
        # Get it
838
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
839

    
840
        # load specific parameters from the radio image
841
        self.set_options()
842

    
843
    def get_raw_memory(self, number):
844
        return repr(self._memobj.memory[number])
845

    
846
    def _decode_tone(self, val):
847
        """Parse the tone data to decode from mem, it returns:
848
        Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)"""
849
        pol = None
850

    
851
        if val in [0, 65535]:
852
            return '', None, None
853
        elif val > 0x0258:
854
            a = val / 10.0
855
            return 'Tone', a, pol
856
        else:
857
            if val > 0x69:
858
                index = val - 0x6A
859
                pol = "R"
860
            else:
861
                index = val - 1
862
                pol = "N"
863

    
864
            tone = DTCS[index]
865
            return 'DTCS', tone, pol
866

    
867
    def _encode_tone(self, memval, mode, val, pol):
868
        """Parse the tone data to encode from UI to mem"""
869
        if mode == '' or mode is None:
870
            memval.set_raw("\x00\x00")
871
        elif mode == 'Tone':
872
            memval.set_value(val * 10)
873
        elif mode == 'DTCS':
874
            # detect the index in the DTCS list
875
            try:
876
                index = DTCS.index(val)
877
                if pol == "N":
878
                    index += 1
879
                else:
880
                    index += 0x6A
881
                memval.set_value(index)
882
            except:
883
                msg = "Digital Tone '%d' is not supported" % value
884
                LOG.error(msg)
885
                raise errors.RadioError(msg)
886
        else:
887
            msg = "Internal error: invalid mode '%s'" % mode
888
            LOG.error(msg)
889
            raise errors.InvalidDataError(msg)
890

    
891
    def get_memory(self, number):
892
        """Get the mem representation from the radio image"""
893
        _mem = self._memobj.memory[number]
894
        _names = self._memobj.names[number]
895

    
896
        # Create a high-level memory object to return to the UI
897
        mem = chirp_common.Memory()
898

    
899
        # Memory number
900
        mem.number = number
901

    
902
        if _mem.get_raw()[0] == "\xFF":
903
            mem.empty = True
904
            return mem
905

    
906
        # Freq and offset
907
        mem.freq = int(_mem.rxfreq) * 10
908
        # tx freq can be blank
909
        if _mem.get_raw()[4] == "\xFF":
910
            # TX freq not set
911
            mem.offset = 0
912
            mem.duplex = "off"
913
        else:
914
            # TX freq set
915
            offset = (int(_mem.txfreq) * 10) - mem.freq
916
            if offset != 0:
917
                if _split(self.get_features(), mem.freq, int(_mem.txfreq) * 10):
918
                    mem.duplex = "split"
919
                    mem.offset = int(_mem.txfreq) * 10
920
                elif offset < 0:
921
                    mem.offset = abs(offset)
922
                    mem.duplex = "-"
923
                elif offset > 0:
924
                    mem.offset = offset
925
                    mem.duplex = "+"
926
            else:
927
                mem.offset = 0
928

    
929
        # name TAG of the channel
930
        mem.name = str(_names.name).rstrip("\xFF").replace("\xFF", " ")
931

    
932
        # power
933
        mem.power = POWER_LEVELS[int(_mem.power)]
934

    
935
        # wide/narrow
936
        mem.mode = MODES[int(_mem.wide)]
937

    
938
        # skip
939
        mem.skip = SKIP_VALUES[_mem.add]
940

    
941
        # tone data
942
        rxtone = txtone = None
943
        txtone = self._decode_tone(_mem.txtone)
944
        rxtone = self._decode_tone(_mem.rxtone)
945
        chirp_common.split_tone_decode(mem, txtone, rxtone)
946

    
947
        # Extra
948
        mem.extra = RadioSettingGroup("extra", "Extra")
949

    
950
        scramble = RadioSetting("scramble", "Scramble",
951
                                RadioSettingValueBoolean(bool(_mem.scramble)))
952
        mem.extra.append(scramble)
953

    
954
        bcl = RadioSetting("bcl", "Busy channel lockout",
955
                           RadioSettingValueBoolean(bool(_mem.bcl)))
956
        mem.extra.append(bcl)
957

    
958
        pttid = RadioSetting("pttid", "PTT ID",
959
                             RadioSettingValueList(PTTID_LIST,
960
                                                   PTTID_LIST[_mem.pttid]))
961
        mem.extra.append(pttid)
962

    
963
        # validating scode
964
        scode = _mem.scode if _mem.scode != 15 else 0
965
        pttidcode = RadioSetting("scode", "PTT ID signal code",
966
                                 RadioSettingValueList(
967
                                     PTTIDCODE_LIST,
968
                                     PTTIDCODE_LIST[scode]))
969
        mem.extra.append(pttidcode)
970

    
971
        optsig = RadioSetting("optsig", "Optional signaling",
972
                              RadioSettingValueList(
973
                                  OPTSIG_LIST,
974
                                  OPTSIG_LIST[_mem.optsig]))
975
        mem.extra.append(optsig)
976

    
977
        spmute = RadioSetting("spmute", "Speaker mute",
978
                              RadioSettingValueList(
979
                                  SPMUTE_LIST,
980
                                  SPMUTE_LIST[_mem.spmute]))
981
        mem.extra.append(spmute)
982

    
983
        return mem
984

    
985
    def set_memory(self, mem):
986
        """Set the memory data in the eeprom img from the UI"""
987
        # get the eprom representation of this channel
988
        _mem = self._memobj.memory[mem.number]
989
        _names = self._memobj.names[mem.number]
990

    
991
        # if empty memmory
992
        if mem.empty:
993
            # the channel itself
994
            _mem.set_raw("\xFF" * 16)
995
            # the name tag
996
            _names.set_raw("\xFF" * 16)
997
            return
998

    
999
        # frequency
1000
        _mem.rxfreq = mem.freq / 10
1001

    
1002
        # duplex
1003
        if mem.duplex == "+":
1004
            _mem.txfreq = (mem.freq + mem.offset) / 10
1005
        elif mem.duplex == "-":
1006
            _mem.txfreq = (mem.freq - mem.offset) / 10
1007
        elif mem.duplex == "off":
1008
            for i in _mem.txfreq:
1009
                i.set_raw("\xFF")
1010
        elif mem.duplex == "split":
1011
            _mem.txfreq = mem.offset / 10
1012
        else:
1013
            _mem.txfreq = mem.freq / 10
1014

    
1015
        # tone data
1016
        ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
1017
            chirp_common.split_tone_encode(mem)
1018
        self._encode_tone(_mem.txtone, txmode, txtone, txpol)
1019
        self._encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)
1020

    
1021
        # name TAG of the channel
1022
        if len(mem.name) < NAME_LENGTH:
1023
            # we must pad to NAME_LENGTH chars, " " = "\xFF"
1024
            mem.name = str(mem.name).ljust(NAME_LENGTH, " ")
1025
        _names.name = str(mem.name).replace(" ", "\xFF")
1026

    
1027
        # power, # default power level is high
1028
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
1029

    
1030
        # wide/narrow
1031
        _mem.wide = MODES.index(mem.mode)
1032

    
1033
        # scan add property
1034
        _mem.add = SKIP_VALUES.index(mem.skip)
1035

    
1036
        # reseting unknowns, this have to be set by hand
1037
        _mem.unknown0 = 0
1038
        _mem.unknown1 = 0
1039
        _mem.unknown2 = 0
1040
        _mem.unknown3 = 0
1041
        _mem.unknown4 = 0
1042
        _mem.unknown5 = 0
1043
        _mem.unknown6 = 0
1044

    
1045
        # extra settings
1046
        if len(mem.extra) > 0:
1047
            # there are setting, parse
1048
            for setting in mem.extra:
1049
                setattr(_mem, setting.get_name(), setting.value)
1050
        else:
1051
            # there is no extra settings, load defaults
1052
            _mem.spmute = 0
1053
            _mem.optsig = 0
1054
            _mem.scramble = 0
1055
            _mem.bcl = 0
1056
            _mem.pttid = 0
1057
            _mem.scode = 0
1058

    
1059
        return mem
1060

    
1061
    def get_settings(self):
1062
        """Translate the bit in the mem_struct into settings in the UI"""
1063
        _mem = self._memobj
1064
        basic = RadioSettingGroup("basic", "Basic Settings")
1065
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
1066
        other = RadioSettingGroup("other", "Other Settings")
1067
        work = RadioSettingGroup("work", "Work Mode Settings")
1068
        top = RadioSettings(basic, advanced, other, work)
1069

    
1070
        # Basic
1071
        tdr = RadioSetting("settings.tdr", "Transceiver dual receive",
1072
                           RadioSettingValueBoolean(_mem.settings.tdr))
1073
        basic.append(tdr)
1074

    
1075
        sql = RadioSetting("settings.sql", "Squelch level",
1076
                           RadioSettingValueInteger(0, 9, _mem.settings.sql))
1077
        basic.append(sql)
1078

    
1079
        tot = RadioSetting("settings.tot", "Time out timer",
1080
                           RadioSettingValueList(LIST_TOT, LIST_TOT[
1081
                               _mem.settings.tot]))
1082
        basic.append(tot)
1083

    
1084
        if self.MODEL in ("UV-2501", "UV-2501+220", "UV-5001"):
1085
            apo = RadioSetting("settings.apo", "Auto power off timer",
1086
                               RadioSettingValueList(LIST_APO, LIST_APO[
1087
                                   _mem.settings.apo]))
1088
            basic.append(apo)
1089
        else:
1090
            toa = RadioSetting("settings.apo", "Time out alert timer",
1091
                               RadioSettingValueList(LIST_TOA, LIST_TOA[
1092
                                   _mem.settings.apo]))
1093
            basic.append(toa)
1094

    
1095
        abr = RadioSetting("settings.abr", "Backlight timer",
1096
                           RadioSettingValueList(LIST_ABR, LIST_ABR[
1097
                               _mem.settings.abr]))
1098
        basic.append(abr)
1099

    
1100
        beep = RadioSetting("settings.beep", "Key beep",
1101
                            RadioSettingValueBoolean(_mem.settings.beep))
1102
        basic.append(beep)
1103

    
1104
        dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone",
1105
                              RadioSettingValueList(LIST_DTMFST, LIST_DTMFST[
1106
                                  _mem.settings.dtmfst]))
1107
        basic.append(dtmfst)
1108

    
1109
        prisc = RadioSetting("settings.prisc", "Priority scan",
1110
                             RadioSettingValueBoolean(_mem.settings.prisc))
1111
        basic.append(prisc)
1112

    
1113
        prich = RadioSetting("settings.prich", "Priority channel",
1114
                             RadioSettingValueInteger(0, 199,
1115
                                 _mem.settings.prich))
1116
        basic.append(prich)
1117

    
1118
        screv = RadioSetting("settings.screv", "Scan resume method",
1119
                             RadioSettingValueList(LIST_SCREV, LIST_SCREV[
1120
                                 _mem.settings.screv]))
1121
        basic.append(screv)
1122

    
1123
        pttlt = RadioSetting("settings.pttlt", "PTT transmit delay",
1124
                             RadioSettingValueInteger(0, 30,
1125
                                 _mem.settings.pttlt))
1126
        basic.append(pttlt)
1127

    
1128
        emctp = RadioSetting("settings.emctp", "Alarm mode",
1129
                             RadioSettingValueList(LIST_EMCTP, LIST_EMCTP[
1130
                                 _mem.settings.emctp]))
1131
        basic.append(emctp)
1132

    
1133
        emcch = RadioSetting("settings.emcch", "Alarm channel",
1134
                             RadioSettingValueInteger(0, 199,
1135
                                 _mem.settings.emcch))
1136
        basic.append(emcch)
1137

    
1138
        ringt = RadioSetting("settings.ringt", "Ring time",
1139
                             RadioSettingValueList(LIST_RINGT, LIST_RINGT[
1140
                                 _mem.settings.ringt]))
1141
        basic.append(ringt)
1142

    
1143
        camdf = RadioSetting("settings.camdf", "Display mode A",
1144
                             RadioSettingValueList(LIST_MDF, LIST_MDF[
1145
                                 _mem.settings.camdf]))
1146
        basic.append(camdf)
1147

    
1148
        cbmdf = RadioSetting("settings.cbmdf", "Display mode B",
1149
                             RadioSettingValueList(LIST_MDF, LIST_MDF[
1150
                                 _mem.settings.cbmdf]))
1151
        basic.append(cbmdf)
1152

    
1153
        if self.MODEL in ("UV-2501", "UV-2501+220", "UV-5001"):
1154
           sync = RadioSetting("settings.sync", "A/B channel sync",
1155
                               RadioSettingValueBoolean(_mem.settings.sync))
1156
           basic.append(sync)
1157
        else:
1158
           autolk = RadioSetting("settings.sync", "Auto keylock",
1159
                                 RadioSettingValueBoolean(_mem.settings.sync))
1160
           basic.append(autolk)
1161

    
1162
        ponmsg = RadioSetting("settings.ponmsg", "Power-on message",
1163
                              RadioSettingValueList(LIST_PONMSG, LIST_PONMSG[
1164
                                  _mem.settings.ponmsg]))
1165
        basic.append(ponmsg)
1166

    
1167
        wtled = RadioSetting("settings.wtled", "Standby backlight Color",
1168
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1169
                                 _mem.settings.wtled]))
1170
        basic.append(wtled)
1171

    
1172
        rxled = RadioSetting("settings.rxled", "RX backlight Color",
1173
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1174
                                 _mem.settings.rxled]))
1175
        basic.append(rxled)
1176

    
1177
        txled = RadioSetting("settings.txled", "TX backlight Color",
1178
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1179
                                 _mem.settings.txled]))
1180
        basic.append(txled)
1181

    
1182
        anil = RadioSetting("settings.anil", "ANI length",
1183
                            RadioSettingValueList(LIST_ANIL, LIST_ANIL[
1184
                                _mem.settings.anil]))
1185
        basic.append(anil)
1186

    
1187
        reps = RadioSetting("settings.reps", "Relay signal (tone burst)",
1188
                            RadioSettingValueList(LIST_REPS, LIST_REPS[
1189
                                _mem.settings.reps]))
1190
        basic.append(reps)
1191

    
1192
        repm = RadioSetting("settings.repm", "Relay condition",
1193
                            RadioSettingValueList(LIST_REPM, LIST_REPM[
1194
                                _mem.settings.repm]))
1195
        basic.append(repm)
1196

    
1197
        if self.MODEL in ("UV-2501", "UV-2501+220", "UV-5001"):
1198
            tdrab = RadioSetting("settings.tdrab", "TDR return time",
1199
                                 RadioSettingValueList(LIST_ABR, LIST_ABR[
1200
                                     _mem.settings.tdrab]))
1201
            basic.append(tdrab)
1202

    
1203
            ste = RadioSetting("settings.ste", "Squelch tail eliminate",
1204
                               RadioSettingValueBoolean(_mem.settings.ste))
1205
            basic.append(ste)
1206

    
1207
            rpste = RadioSetting("settings.rpste", "Repeater STE",
1208
                                 RadioSettingValueList(LIST_RINGT, LIST_RINGT[
1209
                                     _mem.settings.rpste]))
1210
            basic.append(rpste)
1211

    
1212
            rptdl = RadioSetting("settings.rptdl", "Repeater STE delay",
1213
                                 RadioSettingValueList(LIST_RPTDL, LIST_RPTDL[
1214
                                     _mem.settings.rptdl]))
1215
            basic.append(rptdl)
1216

    
1217
        # Advanced
1218
        def _filter(name):
1219
            filtered = ""
1220
            for char in str(name):
1221
                if char in VALID_CHARS:
1222
                    filtered += char
1223
                else:
1224
                    filtered += " "
1225
            return filtered
1226

    
1227
        _msg = self._memobj.poweron_msg
1228
        line1 = RadioSetting("poweron_msg.line1", "Power-on message line 1",
1229
                             RadioSettingValueString(0, 6, _filter(
1230
                                 _msg.line1)))
1231
        advanced.append(line1)
1232
        line2 = RadioSetting("poweron_msg.line2", "Power-on message line 2",
1233
                             RadioSettingValueString(0, 6, _filter(
1234
                                 _msg.line2)))
1235
        advanced.append(line2)
1236

    
1237
        if self.MODEL in ("UV-2501", "UV-5001"):
1238
            vfomren = RadioSetting("settings2.vfomren", "VFO/MR switching",
1239
                                   RadioSettingValueBoolean(
1240
                                       not _mem.settings2.vfomren))
1241
            advanced.append(vfomren)
1242

    
1243
            reseten = RadioSetting("settings2.reseten", "RESET",
1244
                                   RadioSettingValueBoolean(
1245
                                       _mem.settings2.reseten))
1246
            advanced.append(reseten)
1247

    
1248
            menuen = RadioSetting("settings2.menuen", "Menu",
1249
                                  RadioSettingValueBoolean(
1250
                                      _mem.settings2.menuen))
1251
            advanced.append(menuen)
1252

    
1253
        # Other
1254
        def convert_bytes_to_limit(bytes):
1255
            limit = ""
1256
            for byte in bytes:
1257
                if byte < 10:
1258
                    limit += chr(byte + 0x30)
1259
                else:
1260
                    break
1261
            return limit
1262

    
1263
        if "+220" in self.MODEL:
1264
            _ranges = self._memobj.ranges220
1265
            ranges = "ranges220"
1266
        else:
1267
            _ranges = self._memobj.ranges
1268
            ranges = "ranges"
1269

    
1270
        _limit = convert_bytes_to_limit(_ranges.vhf_low)
1271
        val = RadioSettingValueString(0, 3, _limit)
1272
        val.set_mutable(False)
1273
        vhf_low = RadioSetting("%s.vhf_low" % ranges, "VHF low", val)
1274
        other.append(vhf_low)
1275

    
1276
        _limit = convert_bytes_to_limit(_ranges.vhf_high)
1277
        val = RadioSettingValueString(0, 3, _limit)
1278
        val.set_mutable(False)
1279
        vhf_high = RadioSetting("%s.vhf_high" % ranges, "VHF high", val)
1280
        other.append(vhf_high)
1281

    
1282
        if "+220" in self.MODEL:
1283
            _limit = convert_bytes_to_limit(_ranges.vhf2_low)
1284
            val = RadioSettingValueString(0, 3, _limit)
1285
            val.set_mutable(False)
1286
            vhf2_low = RadioSetting("%s.vhf2_low" % ranges, "VHF2 low", val)
1287
            other.append(vhf2_low)
1288

    
1289
            _limit = convert_bytes_to_limit(_ranges.vhf2_high)
1290
            val = RadioSettingValueString(0, 3, _limit)
1291
            val.set_mutable(False)
1292
            vhf2_high = RadioSetting("%s.vhf2_high" % ranges, "VHF2 high", val)
1293
            other.append(vhf2_high)
1294

    
1295
        _limit = convert_bytes_to_limit(_ranges.uhf_low)
1296
        val = RadioSettingValueString(0, 3, _limit)
1297
        val.set_mutable(False)
1298
        uhf_low = RadioSetting("%s.uhf_low" % ranges, "UHF low", val)
1299
        other.append(uhf_low)
1300

    
1301
        _limit = convert_bytes_to_limit(_ranges.uhf_high)
1302
        val = RadioSettingValueString(0, 3, _limit)
1303
        val.set_mutable(False)
1304
        uhf_high = RadioSetting("%s.uhf_high" % ranges, "UHF high", val)
1305
        other.append(uhf_high)
1306

    
1307
        val = RadioSettingValueString(0, 6, _filter(_mem.fingerprint.fp))
1308
        val.set_mutable(False)
1309
        fp = RadioSetting("fingerprint.fp", "Fingerprint", val)
1310
        other.append(fp)
1311

    
1312
        # Work
1313
        dispab = RadioSetting("settings2.dispab", "Display",
1314
                              RadioSettingValueList(LIST_AB,LIST_AB[
1315
                                  _mem.settings2.dispab]))
1316
        work.append(dispab)
1317

    
1318
        vfomr = RadioSetting("settings2.vfomr", "VFO/MR mode",
1319
                             RadioSettingValueList(LIST_VFOMR,LIST_VFOMR[
1320
                                 _mem.settings2.vfomr]))
1321
        work.append(vfomr)
1322

    
1323
        keylock = RadioSetting("settings2.keylock", "Keypad lock",
1324
                           RadioSettingValueBoolean(_mem.settings2.keylock))
1325
        work.append(keylock)
1326

    
1327
        mrcha = RadioSetting("settings2.mrcha", "MR A channel",
1328
                             RadioSettingValueInteger(0, 199,
1329
                                 _mem.settings2.mrcha))
1330
        work.append(mrcha)
1331

    
1332
        mrchb = RadioSetting("settings2.mrchb", "MR B channel",
1333
                             RadioSettingValueInteger(0, 199,
1334
                                 _mem.settings2.mrchb))
1335
        work.append(mrchb)
1336

    
1337
        def convert_bytes_to_freq(bytes):
1338
            real_freq = 0
1339
            for byte in bytes:
1340
                real_freq = (real_freq * 10) + byte
1341
            return chirp_common.format_freq(real_freq * 10)
1342

    
1343
        def my_validate(value):
1344
            value = chirp_common.parse_freq(value)
1345
            print value
1346
            if 180000000 <= value and value < 210000000:
1347
                msg = ("Can't be between 180.00000-210.00000")
1348
                raise InvalidValueError(msg)
1349
            elif 231000000 <= value and value < 400000000:
1350
                msg = ("Can't be between 231.00000-400.00000")
1351
                raise InvalidValueError(msg)
1352
            elif 210000000 <= value and value < 231000000 \
1353
                and "+220" not in self.MODEL:
1354
                msg = ("Can't be between 180.00000-400.00000")
1355
                raise InvalidValueError(msg)
1356
            return chirp_common.format_freq(value)
1357

    
1358
        def apply_freq(setting, obj):
1359
            value = chirp_common.parse_freq(str(setting.value)) / 10
1360
            for i in range(7, -1, -1):
1361
                obj.freq[i] = value % 10
1362
                value /= 10
1363

    
1364
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1365
                                        _mem.vfo.a.freq))
1366
        val1a.set_validate_callback(my_validate)
1367
        vfoafreq = RadioSetting("vfo.a.freq", "VFO A frequency", val1a)
1368
        vfoafreq.set_apply_callback(apply_freq, _mem.vfo.a)
1369
        work.append(vfoafreq)
1370

    
1371
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1372
                                        _mem.vfo.b.freq))
1373
        val1b.set_validate_callback(my_validate)
1374
        vfobfreq = RadioSetting("vfo.b.freq", "VFO B frequency", val1b)
1375
        vfobfreq.set_apply_callback(apply_freq, _mem.vfo.b)
1376
        work.append(vfobfreq)
1377

    
1378
        vfoashiftd = RadioSetting("vfo.a.shiftd", "VFO A shift",
1379
                                  RadioSettingValueList(LIST_SHIFT, LIST_SHIFT[
1380
                                      _mem.vfo.a.shiftd]))
1381
        work.append(vfoashiftd)
1382

    
1383
        vfobshiftd = RadioSetting("vfo.b.shiftd", "VFO B shift",
1384
                                  RadioSettingValueList(LIST_SHIFT, LIST_SHIFT[
1385
                                      _mem.vfo.b.shiftd]))
1386
        work.append(vfobshiftd)
1387

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

    
1394
        def apply_offset(setting, obj):
1395
            value = chirp_common.parse_freq(str(setting.value)) / 10000
1396
            for i in range(3, -1, -1):
1397
                obj.offset[i] = value % 10
1398
                value /= 10
1399

    
1400
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1401
                                        _mem.vfo.a.offset))
1402
        vfoaoffset = RadioSetting("vfo.a.offset",
1403
                                  "VFO A offset (0.00-99.95)", val1a)
1404
        vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
1405
        work.append(vfoaoffset)
1406

    
1407
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1408
                                        _mem.vfo.b.offset))
1409
        vfoboffset = RadioSetting("vfo.b.offset",
1410
                                  "VFO B offset (0.00-99.95)", val1b)
1411
        vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
1412
        work.append(vfoboffset)
1413

    
1414
        vfoatxp = RadioSetting("vfo.a.power", "VFO A power",
1415
                                RadioSettingValueList(LIST_TXP,LIST_TXP[
1416
                                    _mem.vfo.a.power]))
1417
        work.append(vfoatxp)
1418

    
1419
        vfobtxp = RadioSetting("vfo.b.power", "VFO B power",
1420
                                RadioSettingValueList(LIST_TXP,LIST_TXP[
1421
                                    _mem.vfo.b.power]))
1422
        work.append(vfobtxp)
1423

    
1424
        vfoawide = RadioSetting("vfo.a.wide", "VFO A bandwidth",
1425
                                RadioSettingValueList(LIST_WIDE,LIST_WIDE[
1426
                                    _mem.vfo.a.wide]))
1427
        work.append(vfoawide)
1428

    
1429
        vfobwide = RadioSetting("vfo.b.wide", "VFO B bandwidth",
1430
                                RadioSettingValueList(LIST_WIDE,LIST_WIDE[
1431
                                    _mem.vfo.b.wide]))
1432
        work.append(vfobwide)
1433

    
1434
        vfoastep = RadioSetting("vfo.a.step", "VFO A step",
1435
                                RadioSettingValueList(LIST_STEP,LIST_STEP[
1436
                                    _mem.vfo.a.step]))
1437
        work.append(vfoastep)
1438

    
1439
        vfobstep = RadioSetting("vfo.b.step", "VFO B step",
1440
                                RadioSettingValueList(LIST_STEP,LIST_STEP[
1441
                                    _mem.vfo.b.step]))
1442
        work.append(vfobstep)
1443

    
1444
        vfoaoptsig = RadioSetting("vfo.a.optsig", "VFO A optional signal",
1445
                                  RadioSettingValueList(OPTSIG_LIST,
1446
                                      OPTSIG_LIST[_mem.vfo.a.optsig]))
1447
        work.append(vfoaoptsig)
1448

    
1449
        vfoboptsig = RadioSetting("vfo.b.optsig", "VFO B optional signal",
1450
                                  RadioSettingValueList(OPTSIG_LIST,
1451
                                      OPTSIG_LIST[_mem.vfo.b.optsig]))
1452
        work.append(vfoboptsig)
1453

    
1454
        vfoaspmute = RadioSetting("vfo.a.spmute", "VFO A speaker mute",
1455
                                  RadioSettingValueList(SPMUTE_LIST,
1456
                                      SPMUTE_LIST[_mem.vfo.a.spmute]))
1457
        work.append(vfoaspmute)
1458

    
1459
        vfobspmute = RadioSetting("vfo.b.spmute", "VFO B speaker mute",
1460
                                  RadioSettingValueList(SPMUTE_LIST,
1461
                                      SPMUTE_LIST[_mem.vfo.b.spmute]))
1462
        work.append(vfobspmute)
1463

    
1464
        vfoascr = RadioSetting("vfo.a.scramble", "VFO A scramble",
1465
                               RadioSettingValueBoolean(_mem.vfo.a.scramble))
1466
        work.append(vfoascr)
1467

    
1468
        vfobscr = RadioSetting("vfo.b.scramble", "VFO B scramble",
1469
                               RadioSettingValueBoolean(_mem.vfo.b.scramble))
1470
        work.append(vfobscr)
1471

    
1472
        vfoascode = RadioSetting("vfo.a.scode", "VFO A PTT-ID",
1473
                                 RadioSettingValueList(PTTIDCODE_LIST,
1474
                                     PTTIDCODE_LIST[_mem.vfo.a.scode]))
1475
        work.append(vfoascode)
1476

    
1477
        vfobscode = RadioSetting("vfo.b.scode", "VFO B PTT-ID",
1478
                                 RadioSettingValueList(PTTIDCODE_LIST,
1479
                                     PTTIDCODE_LIST[_mem.vfo.b.scode]))
1480
        work.append(vfobscode)
1481

    
1482
        pttid = RadioSetting("settings.pttid", "PTT ID",
1483
                             RadioSettingValueList(PTTID_LIST,
1484
                                 PTTID_LIST[_mem.settings.pttid]))
1485
        work.append(pttid)
1486

    
1487
        return top
1488

    
1489
    def set_settings(self, settings):
1490
        _settings = self._memobj.settings
1491
        for element in settings:
1492
            if not isinstance(element, RadioSetting):
1493
                if element.get_name() == "fm_preset":
1494
                    self._set_fm_preset(element)
1495
                else:
1496
                    self.set_settings(element)
1497
                    continue
1498
            else:
1499
                try:
1500
                    name = element.get_name()
1501
                    if "." in name:
1502
                        bits = name.split(".")
1503
                        obj = self._memobj
1504
                        for bit in bits[:-1]:
1505
                            if "/" in bit:
1506
                                bit, index = bit.split("/", 1)
1507
                                index = int(index)
1508
                                obj = getattr(obj, bit)[index]
1509
                            else:
1510
                                obj = getattr(obj, bit)
1511
                        setting = bits[-1]
1512
                    else:
1513
                        obj = _settings
1514
                        setting = element.get_name()
1515

    
1516
                    if element.has_apply_callback():
1517
                        LOG.debug("Using apply callback")
1518
                        element.run_apply_callback()
1519
                    elif setting == "vfomren":
1520
                        setattr(obj, setting, not int(element.value))
1521
                    elif element.value.get_mutable():
1522
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1523
                        setattr(obj, setting, element.value)
1524
                except Exception, e:
1525
                    LOG.debug(element.get_name())
1526
                    raise
1527

    
1528
    @classmethod
1529
    def match_model(cls, filedata, filename):
1530
        match_size = False
1531
        match_model = False
1532

    
1533
        # testing the file data size
1534
        if len(filedata) == MEM_SIZE:
1535
            match_size = True
1536

    
1537
        # testing the firmware model fingerprint
1538
        match_model = model_match(cls, filedata)
1539

    
1540
        if match_size and match_model:
1541
            return True
1542
        else:
1543
            return False
1544

    
1545

    
1546
@directory.register
1547
class UV2501(BTech):
1548
    """Baofeng Tech UV2501"""
1549
    MODEL = "UV-2501"
1550
    _fileid = [UV2501G2_fp, UV2501pp2_fp, UV2501pp_fp]
1551

    
1552

    
1553
@directory.register
1554
class UV2501_220(BTech):
1555
    """Baofeng Tech UV2501+220"""
1556
    MODEL = "UV-2501+220"
1557
    _magic = MSTRING_220
1558
    _fileid = [UV2501_220G2_fp, UV2501_220_fp, UV2501_220pp_fp]
1559
    _id2 = UV2501_220pp_id
1560

    
1561

    
1562
@directory.register
1563
class UV5001(BTech):
1564
    """Baofeng Tech UV5001"""
1565
    MODEL = "UV-5001"
1566
    _fileid = [UV5001G22_fp, UV5001G2_fp, UV5001alpha_fp, UV5001pp_fp]
1567

    
1568

    
1569
@directory.register
1570
class MINI8900(BTech):
1571
    """WACCOM MINI-8900"""
1572
    VENDOR = "WACCOM"
1573
    MODEL = "MINI-8900"
1574
    _magic = MSTRING_MINI8900
1575
    _fileid = [MINI8900_fp, ]
1576

    
1577

    
1578
@directory.register
1579
class KTUV980(BTech):
1580
    """QYT KT-UV980"""
1581
    VENDOR = "QYT"
1582
    MODEL = "KT-UV980"
1583
    _vhf_range = (136000000, 175000000)
1584
    _uhf_range = (400000000, 481000000)
1585
    _magic = MSTRING_MINI8900
1586
    _fileid = [KTUV980_fp, ]
1587

    
1588

    
1589
@directory.register
1590
class KT9800(BTech):
1591
    """QYT KT8900"""
1592
    VENDOR = "QYT"
1593
    MODEL = "KT8900"
1594
    _vhf_range = (136000000, 175000000)
1595
    _uhf_range = (400000000, 481000000)
1596
    _magic = MSTRING_KT8900
1597
    _fileid = [KT8900_fp, ]
1598
    _id2 = KT8900_id
1599

    
1600

    
1601
@directory.register
1602
class GT890(BTech):
1603
    """Sainsonic GT890"""
1604
    VENDOR = "Sainsonic"
1605
    MODEL = "GT-890"
1606
    # ranges are the same as btech's defaults
1607
    _magic = MSTRING_KT8900
1608
    _fileid = [GT890_fp, ]
1609
    _id2 = KT8900_id
(8-8/9)