Project

General

Profile

Bug #3539 » btech.py

dev version with support for 3 new variants of the KT-8900 and one of the GT-890 - Pavel Milanes, 05/09/2016 11:33 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
# New generation KT8900
295
KT8900_fp2 = "M2C234"
296
# this radio has an extra ID
297
KT8900_id = "      303688"
298

    
299

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

    
305

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

    
316

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

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

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

    
337
        # restore the default serial timeout
338
        radio.pipe.setTimeout(STIMEOUT)
339

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

    
343

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

    
347
    data = ""
348

    
349
    try:
350
        data = radio.pipe.read(amount)
351

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

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

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

    
366
    except:
367
        raise errors.RadioError("Error reading data from radio")
368

    
369
    return data
370

    
371

    
372
def _send(radio, data):
373
    """Send data to the radio device"""
374

    
375
    try:
376
        for byte in data:
377
            radio.pipe.write(byte)
378

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

    
386

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

    
394
    return frame
395

    
396

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

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

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

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

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

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

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

    
424

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

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

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

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

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

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

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

    
455
                return True
456

    
457
        return False
458

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

    
464

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

    
471
    # open the radio into program mode
472
    if _start_clone_mode(radio, status) is False:
473
        if radio.MODEL == "KT8900":
474
            error = "Radio didn't entered in clone mode; there is a generation"
475
            error += " of this radios that are a clone of the WACCOM Mini-8900"
476
            error += " please try that also."
477
            raise errors.RadioError(error)
478
        else:
479
            raise errors.RadioError("Radio didn't entered in the clone mode")
480

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

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

    
488
    # check if ident is OK
489
    itis = False
490
    for fp in radio._fileid:
491
        if fp in ident:
492
            itis = True
493
            break
494

    
495
    if itis is False:
496
        LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
497
        raise errors.RadioError("Radio identification failed.")
498

    
499
    # some radios needs a extra read and check for a code on it, this ones
500
    # has the check value in the _id2 var, others simply False
501
    if radio._id2 is not False:
502
        # lower the timeout here as this radios are reseting due to timeout
503
        radio.pipe.setTimeout(0.05)
504

    
505
        # query & receive the extra ID
506
        _send(radio, _make_frame("S", 0x3DF0, 16))
507
        id2 = _rawrecv(radio, 21)
508

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

    
516
        # ok, the correct string must be in the received data
517
        if radio._id2 not in id2:
518
            LOG.debug("Full *BAD* extra ID on the %s is: \n%s" %
519
                      (radio.MODEL, util.hexprint(id2)))
520
            raise errors.RadioError("The extra ID is wrong, aborting.")
521

    
522
        # this radios need a extra request/answer here on the upload
523
        # the amount of data received depends of the radio type
524
        #
525
        # also the first block of TX must no have the ACK at the beginning
526
        # see _upload for this.
527
        if upload is True:
528
            # send an ACK
529
            _send(radio, ACK_CMD)
530

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

    
543
            # checking
544
            if len(ack) == 0 or ack[-1:] != ACK_CMD:
545
                raise errors.RadioError("Radio didn't ACK the upload")
546

    
547
            # restore the default serial timeout
548
            radio.pipe.setTimeout(STIMEOUT)
549

    
550
    # DEBUG
551
    LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL))
552

    
553
    return True
554

    
555

    
556
def _download(radio):
557
    """Get the memory map"""
558

    
559
    # UI progress
560
    status = chirp_common.Status()
561

    
562
    # put radio in program mode and identify it
563
    _do_ident(radio, status)
564

    
565
    # the models that doesn't have the extra ID have to make a dummy read here
566
    if radio._id2 is False:
567
        _send(radio, _make_frame("S", 0, BLOCK_SIZE))
568
        discard = _rawrecv(radio, BLOCK_SIZE + 5)
569

    
570
        if debug is True:
571
            LOG.info("Dummy first block read done, got this:\n\n %s",
572
                     util.hexprint(discard))
573

    
574
    # reset the progress bar in the UI
575
    status.max = MEM_SIZE / BLOCK_SIZE
576
    status.msg = "Cloning from radio..."
577
    status.cur = 0
578
    radio.status_fn(status)
579

    
580
    # cleaning the serial buffer
581
    _clean_buffer(radio)
582

    
583
    data = ""
584
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
585
        # sending the read request
586
        _send(radio, _make_frame("S", addr, BLOCK_SIZE))
587

    
588
        # read
589
        d = _recv(radio, addr)
590

    
591
        # aggregate the data
592
        data += d
593

    
594
        # UI Update
595
        status.cur = addr / BLOCK_SIZE
596
        status.msg = "Cloning from radio..."
597
        radio.status_fn(status)
598

    
599
    return data
600

    
601

    
602
def _upload(radio):
603
    """Upload procedure"""
604

    
605
    # The UPLOAD mem is restricted to lower than 0x3100,
606
    # so we will overide that here localy
607
    MEM_SIZE = 0x3100
608

    
609
    # UI progress
610
    status = chirp_common.Status()
611

    
612
    # put radio in program mode and identify it
613
    _do_ident(radio, status, True)
614

    
615
    # get the data to upload to radio
616
    data = radio.get_mmap()
617

    
618
    # Reset the UI progress
619
    status.max = MEM_SIZE / TX_BLOCK_SIZE
620
    status.cur = 0
621
    status.msg = "Cloning to radio..."
622
    radio.status_fn(status)
623

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

    
628
    # cleaning the serial buffer
629
    _clean_buffer(radio)
630

    
631
    # the fun start here
632
    for addr in range(0, MEM_SIZE, TX_BLOCK_SIZE):
633
        # getting the block of data to send
634
        d = data[addr:addr + TX_BLOCK_SIZE]
635

    
636
        # build the frame to send
637
        frame = _make_frame("X", addr, TX_BLOCK_SIZE, d)
638

    
639
        # first block must not send the ACK at the beginning for the
640
        # ones that has the extra id, since this have to do a extra step
641
        if addr == 0 and radio._id2 is not False:
642
            frame = frame[1:]
643

    
644
        # send the frame
645
        _send(radio, frame)
646

    
647
        # receiving the response
648
        ack = _rawrecv(radio, 1)
649

    
650
        # basic check
651
        if len(ack) != 1:
652
            raise errors.RadioError("No ACK when writing block 0x%04x" % addr)
653

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

    
657
         # UI Update
658
        status.cur = addr / TX_BLOCK_SIZE
659
        status.msg = "Cloning to radio..."
660
        radio.status_fn(status)
661

    
662

    
663
def model_match(cls, data):
664
    """Match the opened/downloaded image to the correct version"""
665
    rid = data[0x3f70:0x3f76]
666

    
667
    if rid in cls._fileid:
668
        return True
669

    
670
    return False
671

    
672

    
673
def _decode_ranges(low, high):
674
    """Unpack the data in the ranges zones in the memmap and return
675
    a tuple with the integer corresponding to the Mhz it means"""
676
    ilow = int(low[0]) * 100 + int(low[1]) * 10 + int(low[2])
677
    ihigh = int(high[0]) * 100 + int(high[1]) * 10 + int(high[2])
678
    ilow *= 1000000
679
    ihigh *= 1000000
680

    
681
    return (ilow, ihigh)
682

    
683

    
684
def _split(rf, f1, f2):
685
    """Returns False if the two freqs are in the same band (no split)
686
    or True otherwise"""
687

    
688
    # determine if the two freqs are in the same band
689
    for low, high in rf.valid_bands:
690
        if f1 >= low and f1 <= high and \
691
                f2 >= low and f2 <= high:
692
            # if the two freqs are on the same Band this is not a split
693
            return False
694

    
695
    # if you get here is because the freq pairs are split
696
    return False
697

    
698

    
699
class BTech(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio):
700
    """BTECH's UV-5001 and alike radios"""
701
    VENDOR = "BTECH"
702
    MODEL = ""
703
    IDENT = ""
704
    _vhf_range = (130000000, 180000000)
705
    _220_range = (210000000, 231000000)
706
    _uhf_range = (400000000, 521000000)
707
    _upper = 199
708
    _magic = MSTRING
709
    _fileid = None
710
    _id2 = False
711

    
712
    @classmethod
713
    def get_prompts(cls):
714
        rp = chirp_common.RadioPrompts()
715
        rp.experimental = \
716
            ('This driver is experimental.\n'
717
             '\n'
718
             'Please keep a copy of your memories with the original software '
719
             'if you treasure them, this driver is new and may contain'
720
             ' bugs.\n'
721
             '\n'
722
             )
723
        rp.pre_download = _(dedent("""\
724
            Follow these instructions to download your info:
725

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

    
731
            """))
732
        rp.pre_upload = _(dedent("""\
733
            Follow these instructions to upload your info:
734

    
735
            1 - Turn off your radio
736
            2 - Connect your interface cable
737
            3 - Turn on your radio
738
            4 - Do the upload of your radio data
739

    
740
            """))
741
        return rp
742

    
743
    def get_features(self):
744
        """Get the radio's features"""
745

    
746
        # we will use the following var as global
747
        global POWER_LEVELS
748

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

    
779
        # power levels
780
        if self.MODEL == "UV-5001":
781
            POWER_LEVELS = UV5001_POWER_LEVELS  # Higher power (50W)
782
        else:
783
            POWER_LEVELS = NORMAL_POWER_LEVELS  # Lower power (25W)
784

    
785
        rf.valid_power_levels = POWER_LEVELS
786

    
787
        # bands
788
        rf.valid_bands = [self._vhf_range, self._uhf_range]
789

    
790
        # 2501+220
791
        if self.MODEL == "UV-2501+220":
792
            rf.valid_bands.append(self._220_range)
793

    
794
        return rf
795

    
796
    def sync_in(self):
797
        """Download from radio"""
798
        data = _download(self)
799
        self._mmap = memmap.MemoryMap(data)
800
        self.process_mmap()
801

    
802
    def sync_out(self):
803
        """Upload to radio"""
804
        try:
805
            _upload(self)
806
        except errors.RadioError:
807
            raise
808
        except Exception, e:
809
            raise errors.RadioError("Error: %s" % e)
810

    
811
    def set_options(self):
812
        """This is to read the options from the image and set it in the
813
        environment, for now just the limits of the freqs in the VHF/UHF
814
        ranges"""
815

    
816
        # setting the correct ranges for each radio type
817
        if "+220" in self.MODEL:
818
            # the model 2501+220 has a segment in 220
819
            # and a different position in the memmap
820
            ranges = self._memobj.ranges220
821
        else:
822
            ranges = self._memobj.ranges
823

    
824
        # the normal dual bands
825
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
826
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
827

    
828
        # DEBUG
829
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
830
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
831

    
832
        # 220Mhz case
833
        if "+220" in self.MODEL:
834
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
835
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
836
            self._220_range = vhf2
837

    
838
        # set the class with the real data
839
        self._vhf_range = vhf
840
        self._uhf_range = uhf
841

    
842
    def process_mmap(self):
843
        """Process the mem map into the mem object"""
844

    
845
        # Get it
846
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
847

    
848
        # load specific parameters from the radio image
849
        self.set_options()
850

    
851
    def get_raw_memory(self, number):
852
        return repr(self._memobj.memory[number])
853

    
854
    def _decode_tone(self, val):
855
        """Parse the tone data to decode from mem, it returns:
856
        Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)"""
857
        pol = None
858

    
859
        if val in [0, 65535]:
860
            return '', None, None
861
        elif val > 0x0258:
862
            a = val / 10.0
863
            return 'Tone', a, pol
864
        else:
865
            if val > 0x69:
866
                index = val - 0x6A
867
                pol = "R"
868
            else:
869
                index = val - 1
870
                pol = "N"
871

    
872
            tone = DTCS[index]
873
            return 'DTCS', tone, pol
874

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

    
899
    def get_memory(self, number):
900
        """Get the mem representation from the radio image"""
901
        _mem = self._memobj.memory[number]
902
        _names = self._memobj.names[number]
903

    
904
        # Create a high-level memory object to return to the UI
905
        mem = chirp_common.Memory()
906

    
907
        # Memory number
908
        mem.number = number
909

    
910
        if _mem.get_raw()[0] == "\xFF":
911
            mem.empty = True
912
            return mem
913

    
914
        # Freq and offset
915
        mem.freq = int(_mem.rxfreq) * 10
916
        # tx freq can be blank
917
        if _mem.get_raw()[4] == "\xFF":
918
            # TX freq not set
919
            mem.offset = 0
920
            mem.duplex = "off"
921
        else:
922
            # TX freq set
923
            offset = (int(_mem.txfreq) * 10) - mem.freq
924
            if offset != 0:
925
                if _split(self.get_features(), mem.freq, int(_mem.txfreq) * 10):
926
                    mem.duplex = "split"
927
                    mem.offset = int(_mem.txfreq) * 10
928
                elif offset < 0:
929
                    mem.offset = abs(offset)
930
                    mem.duplex = "-"
931
                elif offset > 0:
932
                    mem.offset = offset
933
                    mem.duplex = "+"
934
            else:
935
                mem.offset = 0
936

    
937
        # name TAG of the channel
938
        mem.name = str(_names.name).rstrip("\xFF").replace("\xFF", " ")
939

    
940
        # power
941
        mem.power = POWER_LEVELS[int(_mem.power)]
942

    
943
        # wide/narrow
944
        mem.mode = MODES[int(_mem.wide)]
945

    
946
        # skip
947
        mem.skip = SKIP_VALUES[_mem.add]
948

    
949
        # tone data
950
        rxtone = txtone = None
951
        txtone = self._decode_tone(_mem.txtone)
952
        rxtone = self._decode_tone(_mem.rxtone)
953
        chirp_common.split_tone_decode(mem, txtone, rxtone)
954

    
955
        # Extra
956
        mem.extra = RadioSettingGroup("extra", "Extra")
957

    
958
        scramble = RadioSetting("scramble", "Scramble",
959
                                RadioSettingValueBoolean(bool(_mem.scramble)))
960
        mem.extra.append(scramble)
961

    
962
        bcl = RadioSetting("bcl", "Busy channel lockout",
963
                           RadioSettingValueBoolean(bool(_mem.bcl)))
964
        mem.extra.append(bcl)
965

    
966
        pttid = RadioSetting("pttid", "PTT ID",
967
                             RadioSettingValueList(PTTID_LIST,
968
                                                   PTTID_LIST[_mem.pttid]))
969
        mem.extra.append(pttid)
970

    
971
        # validating scode
972
        scode = _mem.scode if _mem.scode != 15 else 0
973
        pttidcode = RadioSetting("scode", "PTT ID signal code",
974
                                 RadioSettingValueList(
975
                                     PTTIDCODE_LIST,
976
                                     PTTIDCODE_LIST[scode]))
977
        mem.extra.append(pttidcode)
978

    
979
        optsig = RadioSetting("optsig", "Optional signaling",
980
                              RadioSettingValueList(
981
                                  OPTSIG_LIST,
982
                                  OPTSIG_LIST[_mem.optsig]))
983
        mem.extra.append(optsig)
984

    
985
        spmute = RadioSetting("spmute", "Speaker mute",
986
                              RadioSettingValueList(
987
                                  SPMUTE_LIST,
988
                                  SPMUTE_LIST[_mem.spmute]))
989
        mem.extra.append(spmute)
990

    
991
        return mem
992

    
993
    def set_memory(self, mem):
994
        """Set the memory data in the eeprom img from the UI"""
995
        # get the eprom representation of this channel
996
        _mem = self._memobj.memory[mem.number]
997
        _names = self._memobj.names[mem.number]
998

    
999
        # if empty memmory
1000
        if mem.empty:
1001
            # the channel itself
1002
            _mem.set_raw("\xFF" * 16)
1003
            # the name tag
1004
            _names.set_raw("\xFF" * 16)
1005
            return
1006

    
1007
        # frequency
1008
        _mem.rxfreq = mem.freq / 10
1009

    
1010
        # duplex
1011
        if mem.duplex == "+":
1012
            _mem.txfreq = (mem.freq + mem.offset) / 10
1013
        elif mem.duplex == "-":
1014
            _mem.txfreq = (mem.freq - mem.offset) / 10
1015
        elif mem.duplex == "off":
1016
            for i in _mem.txfreq:
1017
                i.set_raw("\xFF")
1018
        elif mem.duplex == "split":
1019
            _mem.txfreq = mem.offset / 10
1020
        else:
1021
            _mem.txfreq = mem.freq / 10
1022

    
1023
        # tone data
1024
        ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
1025
            chirp_common.split_tone_encode(mem)
1026
        self._encode_tone(_mem.txtone, txmode, txtone, txpol)
1027
        self._encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)
1028

    
1029
        # name TAG of the channel
1030
        if len(mem.name) < NAME_LENGTH:
1031
            # we must pad to NAME_LENGTH chars, " " = "\xFF"
1032
            mem.name = str(mem.name).ljust(NAME_LENGTH, " ")
1033
        _names.name = str(mem.name).replace(" ", "\xFF")
1034

    
1035
        # power, # default power level is high
1036
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
1037

    
1038
        # wide/narrow
1039
        _mem.wide = MODES.index(mem.mode)
1040

    
1041
        # scan add property
1042
        _mem.add = SKIP_VALUES.index(mem.skip)
1043

    
1044
        # reseting unknowns, this have to be set by hand
1045
        _mem.unknown0 = 0
1046
        _mem.unknown1 = 0
1047
        _mem.unknown2 = 0
1048
        _mem.unknown3 = 0
1049
        _mem.unknown4 = 0
1050
        _mem.unknown5 = 0
1051
        _mem.unknown6 = 0
1052

    
1053
        # extra settings
1054
        if len(mem.extra) > 0:
1055
            # there are setting, parse
1056
            for setting in mem.extra:
1057
                setattr(_mem, setting.get_name(), setting.value)
1058
        else:
1059
            # there is no extra settings, load defaults
1060
            _mem.spmute = 0
1061
            _mem.optsig = 0
1062
            _mem.scramble = 0
1063
            _mem.bcl = 0
1064
            _mem.pttid = 0
1065
            _mem.scode = 0
1066

    
1067
        return mem
1068

    
1069
    def get_settings(self):
1070
        """Translate the bit in the mem_struct into settings in the UI"""
1071
        _mem = self._memobj
1072
        basic = RadioSettingGroup("basic", "Basic Settings")
1073
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
1074
        other = RadioSettingGroup("other", "Other Settings")
1075
        work = RadioSettingGroup("work", "Work Mode Settings")
1076
        top = RadioSettings(basic, advanced, other, work)
1077

    
1078
        # Basic
1079
        tdr = RadioSetting("settings.tdr", "Transceiver dual receive",
1080
                           RadioSettingValueBoolean(_mem.settings.tdr))
1081
        basic.append(tdr)
1082

    
1083
        sql = RadioSetting("settings.sql", "Squelch level",
1084
                           RadioSettingValueInteger(0, 9, _mem.settings.sql))
1085
        basic.append(sql)
1086

    
1087
        tot = RadioSetting("settings.tot", "Time out timer",
1088
                           RadioSettingValueList(LIST_TOT, LIST_TOT[
1089
                               _mem.settings.tot]))
1090
        basic.append(tot)
1091

    
1092
        if self.MODEL in ("UV-2501", "UV-2501+220", "UV-5001"):
1093
            apo = RadioSetting("settings.apo", "Auto power off timer",
1094
                               RadioSettingValueList(LIST_APO, LIST_APO[
1095
                                   _mem.settings.apo]))
1096
            basic.append(apo)
1097
        else:
1098
            toa = RadioSetting("settings.apo", "Time out alert timer",
1099
                               RadioSettingValueList(LIST_TOA, LIST_TOA[
1100
                                   _mem.settings.apo]))
1101
            basic.append(toa)
1102

    
1103
        abr = RadioSetting("settings.abr", "Backlight timer",
1104
                           RadioSettingValueList(LIST_ABR, LIST_ABR[
1105
                               _mem.settings.abr]))
1106
        basic.append(abr)
1107

    
1108
        beep = RadioSetting("settings.beep", "Key beep",
1109
                            RadioSettingValueBoolean(_mem.settings.beep))
1110
        basic.append(beep)
1111

    
1112
        dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone",
1113
                              RadioSettingValueList(LIST_DTMFST, LIST_DTMFST[
1114
                                  _mem.settings.dtmfst]))
1115
        basic.append(dtmfst)
1116

    
1117
        prisc = RadioSetting("settings.prisc", "Priority scan",
1118
                             RadioSettingValueBoolean(_mem.settings.prisc))
1119
        basic.append(prisc)
1120

    
1121
        prich = RadioSetting("settings.prich", "Priority channel",
1122
                             RadioSettingValueInteger(0, 199,
1123
                                 _mem.settings.prich))
1124
        basic.append(prich)
1125

    
1126
        screv = RadioSetting("settings.screv", "Scan resume method",
1127
                             RadioSettingValueList(LIST_SCREV, LIST_SCREV[
1128
                                 _mem.settings.screv]))
1129
        basic.append(screv)
1130

    
1131
        pttlt = RadioSetting("settings.pttlt", "PTT transmit delay",
1132
                             RadioSettingValueInteger(0, 30,
1133
                                 _mem.settings.pttlt))
1134
        basic.append(pttlt)
1135

    
1136
        emctp = RadioSetting("settings.emctp", "Alarm mode",
1137
                             RadioSettingValueList(LIST_EMCTP, LIST_EMCTP[
1138
                                 _mem.settings.emctp]))
1139
        basic.append(emctp)
1140

    
1141
        emcch = RadioSetting("settings.emcch", "Alarm channel",
1142
                             RadioSettingValueInteger(0, 199,
1143
                                 _mem.settings.emcch))
1144
        basic.append(emcch)
1145

    
1146
        ringt = RadioSetting("settings.ringt", "Ring time",
1147
                             RadioSettingValueList(LIST_RINGT, LIST_RINGT[
1148
                                 _mem.settings.ringt]))
1149
        basic.append(ringt)
1150

    
1151
        camdf = RadioSetting("settings.camdf", "Display mode A",
1152
                             RadioSettingValueList(LIST_MDF, LIST_MDF[
1153
                                 _mem.settings.camdf]))
1154
        basic.append(camdf)
1155

    
1156
        cbmdf = RadioSetting("settings.cbmdf", "Display mode B",
1157
                             RadioSettingValueList(LIST_MDF, LIST_MDF[
1158
                                 _mem.settings.cbmdf]))
1159
        basic.append(cbmdf)
1160

    
1161
        if self.MODEL in ("UV-2501", "UV-2501+220", "UV-5001"):
1162
           sync = RadioSetting("settings.sync", "A/B channel sync",
1163
                               RadioSettingValueBoolean(_mem.settings.sync))
1164
           basic.append(sync)
1165
        else:
1166
           autolk = RadioSetting("settings.sync", "Auto keylock",
1167
                                 RadioSettingValueBoolean(_mem.settings.sync))
1168
           basic.append(autolk)
1169

    
1170
        ponmsg = RadioSetting("settings.ponmsg", "Power-on message",
1171
                              RadioSettingValueList(LIST_PONMSG, LIST_PONMSG[
1172
                                  _mem.settings.ponmsg]))
1173
        basic.append(ponmsg)
1174

    
1175
        wtled = RadioSetting("settings.wtled", "Standby backlight Color",
1176
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1177
                                 _mem.settings.wtled]))
1178
        basic.append(wtled)
1179

    
1180
        rxled = RadioSetting("settings.rxled", "RX backlight Color",
1181
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1182
                                 _mem.settings.rxled]))
1183
        basic.append(rxled)
1184

    
1185
        txled = RadioSetting("settings.txled", "TX backlight Color",
1186
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1187
                                 _mem.settings.txled]))
1188
        basic.append(txled)
1189

    
1190
        anil = RadioSetting("settings.anil", "ANI length",
1191
                            RadioSettingValueList(LIST_ANIL, LIST_ANIL[
1192
                                _mem.settings.anil]))
1193
        basic.append(anil)
1194

    
1195
        reps = RadioSetting("settings.reps", "Relay signal (tone burst)",
1196
                            RadioSettingValueList(LIST_REPS, LIST_REPS[
1197
                                _mem.settings.reps]))
1198
        basic.append(reps)
1199

    
1200
        repm = RadioSetting("settings.repm", "Relay condition",
1201
                            RadioSettingValueList(LIST_REPM, LIST_REPM[
1202
                                _mem.settings.repm]))
1203
        basic.append(repm)
1204

    
1205
        if self.MODEL in ("UV-2501", "UV-2501+220", "UV-5001"):
1206
            tdrab = RadioSetting("settings.tdrab", "TDR return time",
1207
                                 RadioSettingValueList(LIST_ABR, LIST_ABR[
1208
                                     _mem.settings.tdrab]))
1209
            basic.append(tdrab)
1210

    
1211
            ste = RadioSetting("settings.ste", "Squelch tail eliminate",
1212
                               RadioSettingValueBoolean(_mem.settings.ste))
1213
            basic.append(ste)
1214

    
1215
            rpste = RadioSetting("settings.rpste", "Repeater STE",
1216
                                 RadioSettingValueList(LIST_RINGT, LIST_RINGT[
1217
                                     _mem.settings.rpste]))
1218
            basic.append(rpste)
1219

    
1220
            rptdl = RadioSetting("settings.rptdl", "Repeater STE delay",
1221
                                 RadioSettingValueList(LIST_RPTDL, LIST_RPTDL[
1222
                                     _mem.settings.rptdl]))
1223
            basic.append(rptdl)
1224

    
1225
        # Advanced
1226
        def _filter(name):
1227
            filtered = ""
1228
            for char in str(name):
1229
                if char in VALID_CHARS:
1230
                    filtered += char
1231
                else:
1232
                    filtered += " "
1233
            return filtered
1234

    
1235
        _msg = self._memobj.poweron_msg
1236
        line1 = RadioSetting("poweron_msg.line1", "Power-on message line 1",
1237
                             RadioSettingValueString(0, 6, _filter(
1238
                                 _msg.line1)))
1239
        advanced.append(line1)
1240
        line2 = RadioSetting("poweron_msg.line2", "Power-on message line 2",
1241
                             RadioSettingValueString(0, 6, _filter(
1242
                                 _msg.line2)))
1243
        advanced.append(line2)
1244

    
1245
        if self.MODEL in ("UV-2501", "UV-5001"):
1246
            vfomren = RadioSetting("settings2.vfomren", "VFO/MR switching",
1247
                                   RadioSettingValueBoolean(
1248
                                       not _mem.settings2.vfomren))
1249
            advanced.append(vfomren)
1250

    
1251
            reseten = RadioSetting("settings2.reseten", "RESET",
1252
                                   RadioSettingValueBoolean(
1253
                                       _mem.settings2.reseten))
1254
            advanced.append(reseten)
1255

    
1256
            menuen = RadioSetting("settings2.menuen", "Menu",
1257
                                  RadioSettingValueBoolean(
1258
                                      _mem.settings2.menuen))
1259
            advanced.append(menuen)
1260

    
1261
        # Other
1262
        def convert_bytes_to_limit(bytes):
1263
            limit = ""
1264
            for byte in bytes:
1265
                if byte < 10:
1266
                    limit += chr(byte + 0x30)
1267
                else:
1268
                    break
1269
            return limit
1270

    
1271
        if "+220" in self.MODEL:
1272
            _ranges = self._memobj.ranges220
1273
            ranges = "ranges220"
1274
        else:
1275
            _ranges = self._memobj.ranges
1276
            ranges = "ranges"
1277

    
1278
        _limit = convert_bytes_to_limit(_ranges.vhf_low)
1279
        val = RadioSettingValueString(0, 3, _limit)
1280
        val.set_mutable(False)
1281
        vhf_low = RadioSetting("%s.vhf_low" % ranges, "VHF low", val)
1282
        other.append(vhf_low)
1283

    
1284
        _limit = convert_bytes_to_limit(_ranges.vhf_high)
1285
        val = RadioSettingValueString(0, 3, _limit)
1286
        val.set_mutable(False)
1287
        vhf_high = RadioSetting("%s.vhf_high" % ranges, "VHF high", val)
1288
        other.append(vhf_high)
1289

    
1290
        if "+220" in self.MODEL:
1291
            _limit = convert_bytes_to_limit(_ranges.vhf2_low)
1292
            val = RadioSettingValueString(0, 3, _limit)
1293
            val.set_mutable(False)
1294
            vhf2_low = RadioSetting("%s.vhf2_low" % ranges, "VHF2 low", val)
1295
            other.append(vhf2_low)
1296

    
1297
            _limit = convert_bytes_to_limit(_ranges.vhf2_high)
1298
            val = RadioSettingValueString(0, 3, _limit)
1299
            val.set_mutable(False)
1300
            vhf2_high = RadioSetting("%s.vhf2_high" % ranges, "VHF2 high", val)
1301
            other.append(vhf2_high)
1302

    
1303
        _limit = convert_bytes_to_limit(_ranges.uhf_low)
1304
        val = RadioSettingValueString(0, 3, _limit)
1305
        val.set_mutable(False)
1306
        uhf_low = RadioSetting("%s.uhf_low" % ranges, "UHF low", val)
1307
        other.append(uhf_low)
1308

    
1309
        _limit = convert_bytes_to_limit(_ranges.uhf_high)
1310
        val = RadioSettingValueString(0, 3, _limit)
1311
        val.set_mutable(False)
1312
        uhf_high = RadioSetting("%s.uhf_high" % ranges, "UHF high", val)
1313
        other.append(uhf_high)
1314

    
1315
        val = RadioSettingValueString(0, 6, _filter(_mem.fingerprint.fp))
1316
        val.set_mutable(False)
1317
        fp = RadioSetting("fingerprint.fp", "Fingerprint", val)
1318
        other.append(fp)
1319

    
1320
        # Work
1321
        dispab = RadioSetting("settings2.dispab", "Display",
1322
                              RadioSettingValueList(LIST_AB,LIST_AB[
1323
                                  _mem.settings2.dispab]))
1324
        work.append(dispab)
1325

    
1326
        vfomr = RadioSetting("settings2.vfomr", "VFO/MR mode",
1327
                             RadioSettingValueList(LIST_VFOMR,LIST_VFOMR[
1328
                                 _mem.settings2.vfomr]))
1329
        work.append(vfomr)
1330

    
1331
        keylock = RadioSetting("settings2.keylock", "Keypad lock",
1332
                           RadioSettingValueBoolean(_mem.settings2.keylock))
1333
        work.append(keylock)
1334

    
1335
        mrcha = RadioSetting("settings2.mrcha", "MR A channel",
1336
                             RadioSettingValueInteger(0, 199,
1337
                                 _mem.settings2.mrcha))
1338
        work.append(mrcha)
1339

    
1340
        mrchb = RadioSetting("settings2.mrchb", "MR B channel",
1341
                             RadioSettingValueInteger(0, 199,
1342
                                 _mem.settings2.mrchb))
1343
        work.append(mrchb)
1344

    
1345
        def convert_bytes_to_freq(bytes):
1346
            real_freq = 0
1347
            for byte in bytes:
1348
                real_freq = (real_freq * 10) + byte
1349
            return chirp_common.format_freq(real_freq * 10)
1350

    
1351
        def my_validate(value):
1352
            value = chirp_common.parse_freq(value)
1353
            if 180000000 <= value and value < 210000000:
1354
                msg = ("Can't be between 180.00000-210.00000")
1355
                raise InvalidValueError(msg)
1356
            elif 231000000 <= value and value < 400000000:
1357
                msg = ("Can't be between 231.00000-400.00000")
1358
                raise InvalidValueError(msg)
1359
            elif 210000000 <= value and value < 231000000 \
1360
                and "+220" not in self.MODEL:
1361
                msg = ("Can't be between 180.00000-400.00000")
1362
                raise InvalidValueError(msg)
1363
            return chirp_common.format_freq(value)
1364

    
1365
        def apply_freq(setting, obj):
1366
            value = chirp_common.parse_freq(str(setting.value)) / 10
1367
            for i in range(7, -1, -1):
1368
                obj.freq[i] = value % 10
1369
                value /= 10
1370

    
1371
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1372
                                        _mem.vfo.a.freq))
1373
        val1a.set_validate_callback(my_validate)
1374
        vfoafreq = RadioSetting("vfo.a.freq", "VFO A frequency", val1a)
1375
        vfoafreq.set_apply_callback(apply_freq, _mem.vfo.a)
1376
        work.append(vfoafreq)
1377

    
1378
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1379
                                        _mem.vfo.b.freq))
1380
        val1b.set_validate_callback(my_validate)
1381
        vfobfreq = RadioSetting("vfo.b.freq", "VFO B frequency", val1b)
1382
        vfobfreq.set_apply_callback(apply_freq, _mem.vfo.b)
1383
        work.append(vfobfreq)
1384

    
1385
        vfoashiftd = RadioSetting("vfo.a.shiftd", "VFO A shift",
1386
                                  RadioSettingValueList(LIST_SHIFT, LIST_SHIFT[
1387
                                      _mem.vfo.a.shiftd]))
1388
        work.append(vfoashiftd)
1389

    
1390
        vfobshiftd = RadioSetting("vfo.b.shiftd", "VFO B shift",
1391
                                  RadioSettingValueList(LIST_SHIFT, LIST_SHIFT[
1392
                                      _mem.vfo.b.shiftd]))
1393
        work.append(vfobshiftd)
1394

    
1395
        def convert_bytes_to_offset(bytes):
1396
            real_offset = 0
1397
            for byte in bytes:
1398
                real_offset = (real_offset * 10) + byte
1399
            return chirp_common.format_freq(real_offset * 10000)
1400

    
1401
        def apply_offset(setting, obj):
1402
            value = chirp_common.parse_freq(str(setting.value)) / 10000
1403
            for i in range(3, -1, -1):
1404
                obj.offset[i] = value % 10
1405
                value /= 10
1406

    
1407
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1408
                                        _mem.vfo.a.offset))
1409
        vfoaoffset = RadioSetting("vfo.a.offset",
1410
                                  "VFO A offset (0.00-99.95)", val1a)
1411
        vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
1412
        work.append(vfoaoffset)
1413

    
1414
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1415
                                        _mem.vfo.b.offset))
1416
        vfoboffset = RadioSetting("vfo.b.offset",
1417
                                  "VFO B offset (0.00-99.95)", val1b)
1418
        vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
1419
        work.append(vfoboffset)
1420

    
1421
        vfoatxp = RadioSetting("vfo.a.power", "VFO A power",
1422
                                RadioSettingValueList(LIST_TXP,LIST_TXP[
1423
                                    _mem.vfo.a.power]))
1424
        work.append(vfoatxp)
1425

    
1426
        vfobtxp = RadioSetting("vfo.b.power", "VFO B power",
1427
                                RadioSettingValueList(LIST_TXP,LIST_TXP[
1428
                                    _mem.vfo.b.power]))
1429
        work.append(vfobtxp)
1430

    
1431
        vfoawide = RadioSetting("vfo.a.wide", "VFO A bandwidth",
1432
                                RadioSettingValueList(LIST_WIDE,LIST_WIDE[
1433
                                    _mem.vfo.a.wide]))
1434
        work.append(vfoawide)
1435

    
1436
        vfobwide = RadioSetting("vfo.b.wide", "VFO B bandwidth",
1437
                                RadioSettingValueList(LIST_WIDE,LIST_WIDE[
1438
                                    _mem.vfo.b.wide]))
1439
        work.append(vfobwide)
1440

    
1441
        vfoastep = RadioSetting("vfo.a.step", "VFO A step",
1442
                                RadioSettingValueList(LIST_STEP,LIST_STEP[
1443
                                    _mem.vfo.a.step]))
1444
        work.append(vfoastep)
1445

    
1446
        vfobstep = RadioSetting("vfo.b.step", "VFO B step",
1447
                                RadioSettingValueList(LIST_STEP,LIST_STEP[
1448
                                    _mem.vfo.b.step]))
1449
        work.append(vfobstep)
1450

    
1451
        vfoaoptsig = RadioSetting("vfo.a.optsig", "VFO A optional signal",
1452
                                  RadioSettingValueList(OPTSIG_LIST,
1453
                                      OPTSIG_LIST[_mem.vfo.a.optsig]))
1454
        work.append(vfoaoptsig)
1455

    
1456
        vfoboptsig = RadioSetting("vfo.b.optsig", "VFO B optional signal",
1457
                                  RadioSettingValueList(OPTSIG_LIST,
1458
                                      OPTSIG_LIST[_mem.vfo.b.optsig]))
1459
        work.append(vfoboptsig)
1460

    
1461
        vfoaspmute = RadioSetting("vfo.a.spmute", "VFO A speaker mute",
1462
                                  RadioSettingValueList(SPMUTE_LIST,
1463
                                      SPMUTE_LIST[_mem.vfo.a.spmute]))
1464
        work.append(vfoaspmute)
1465

    
1466
        vfobspmute = RadioSetting("vfo.b.spmute", "VFO B speaker mute",
1467
                                  RadioSettingValueList(SPMUTE_LIST,
1468
                                      SPMUTE_LIST[_mem.vfo.b.spmute]))
1469
        work.append(vfobspmute)
1470

    
1471
        vfoascr = RadioSetting("vfo.a.scramble", "VFO A scramble",
1472
                               RadioSettingValueBoolean(_mem.vfo.a.scramble))
1473
        work.append(vfoascr)
1474

    
1475
        vfobscr = RadioSetting("vfo.b.scramble", "VFO B scramble",
1476
                               RadioSettingValueBoolean(_mem.vfo.b.scramble))
1477
        work.append(vfobscr)
1478

    
1479
        vfoascode = RadioSetting("vfo.a.scode", "VFO A PTT-ID",
1480
                                 RadioSettingValueList(PTTIDCODE_LIST,
1481
                                     PTTIDCODE_LIST[_mem.vfo.a.scode]))
1482
        work.append(vfoascode)
1483

    
1484
        vfobscode = RadioSetting("vfo.b.scode", "VFO B PTT-ID",
1485
                                 RadioSettingValueList(PTTIDCODE_LIST,
1486
                                     PTTIDCODE_LIST[_mem.vfo.b.scode]))
1487
        work.append(vfobscode)
1488

    
1489
        pttid = RadioSetting("settings.pttid", "PTT ID",
1490
                             RadioSettingValueList(PTTID_LIST,
1491
                                 PTTID_LIST[_mem.settings.pttid]))
1492
        work.append(pttid)
1493

    
1494
        return top
1495

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

    
1523
                    if element.has_apply_callback():
1524
                        LOG.debug("Using apply callback")
1525
                        element.run_apply_callback()
1526
                    elif setting == "vfomren":
1527
                        setattr(obj, setting, not int(element.value))
1528
                    elif element.value.get_mutable():
1529
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1530
                        setattr(obj, setting, element.value)
1531
                except Exception, e:
1532
                    LOG.debug(element.get_name())
1533
                    raise
1534

    
1535
    @classmethod
1536
    def match_model(cls, filedata, filename):
1537
        match_size = False
1538
        match_model = False
1539

    
1540
        # testing the file data size
1541
        if len(filedata) == MEM_SIZE:
1542
            match_size = True
1543

    
1544
        # testing the firmware model fingerprint
1545
        match_model = model_match(cls, filedata)
1546

    
1547
        if match_size and match_model:
1548
            return True
1549
        else:
1550
            return False
1551

    
1552

    
1553
@directory.register
1554
class UV2501(BTech):
1555
    """Baofeng Tech UV2501"""
1556
    MODEL = "UV-2501"
1557
    _fileid = [UV2501G2_fp, UV2501pp2_fp, UV2501pp_fp]
1558

    
1559

    
1560
@directory.register
1561
class UV2501_220(BTech):
1562
    """Baofeng Tech UV2501+220"""
1563
    MODEL = "UV-2501+220"
1564
    _magic = MSTRING_220
1565
    _fileid = [UV2501_220G2_fp, UV2501_220_fp, UV2501_220pp_fp]
1566
    _id2 = UV2501_220pp_id
1567

    
1568

    
1569
@directory.register
1570
class UV5001(BTech):
1571
    """Baofeng Tech UV5001"""
1572
    MODEL = "UV-5001"
1573
    _fileid = [UV5001G22_fp, UV5001G2_fp, UV5001alpha_fp, UV5001pp_fp]
1574

    
1575

    
1576
@directory.register
1577
class MINI8900(BTech):
1578
    """WACCOM MINI-8900"""
1579
    VENDOR = "WACCOM"
1580
    MODEL = "MINI-8900"
1581
    _magic = MSTRING_MINI8900
1582
    _fileid = [MINI8900_fp, ]
1583

    
1584

    
1585
@directory.register
1586
class KTUV980(BTech):
1587
    """QYT KT-UV980"""
1588
    VENDOR = "QYT"
1589
    MODEL = "KT-UV980"
1590
    _vhf_range = (136000000, 175000000)
1591
    _uhf_range = (400000000, 481000000)
1592
    _magic = MSTRING_MINI8900
1593
    _fileid = [KTUV980_fp, ]
1594

    
1595

    
1596
@directory.register
1597
class KT9800(BTech):
1598
    """QYT KT8900"""
1599
    VENDOR = "QYT"
1600
    MODEL = "KT8900"
1601
    _vhf_range = (136000000, 175000000)
1602
    _uhf_range = (400000000, 481000000)
1603
    _magic = MSTRING_KT8900
1604
    _fileid = [KT8900_fp, KT8900_fp2, GT890_fp]
1605
    _id2 = KT8900_id
1606

    
1607

    
1608
@directory.register
1609
class GT890(BTech):
1610
    """Sainsonic GT890"""
1611
    VENDOR = "Sainsonic"
1612
    MODEL = "GT-890"
1613
    # ranges are the same as btech's defaults
1614
    _magic = MSTRING_KT8900
1615
    _fileid = [GT890_fp, KT8900_fp]
1616
    _id2 = KT8900_id
(2-2/4)