Project

General

Profile

Bug #4101 » btech.py

test driver for M2G314 MCU-Version - Jim Unroe, 10/03/2016 06:33 PM

 
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 time import sleep
25
from chirp import chirp_common, directory, memmap
26
from chirp import bitwise, errors, util
27
from chirp.settings import RadioSettingGroup, RadioSetting, \
28
    RadioSettingValueBoolean, RadioSettingValueList, \
29
    RadioSettingValueString, RadioSettingValueInteger, \
30
    RadioSettingValueFloat, RadioSettings, InvalidValueError
31
from textwrap import dedent
32

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

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

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

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

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

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

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

    
158
#seekto 0x3000;
159
struct {
160
  u8 freq[8];
161
  char broadcast_station_name[6];
162
  u8 unknown[2];
163
} fm_radio_preset[16];
164

    
165
#seekto 0x3C90;
166
struct {
167
  u8 vhf_low[3];
168
  u8 vhf_high[3];
169
  u8 uhf_low[3];
170
  u8 uhf_high[3];
171
} ranges;
172

    
173
// the UV-2501+220 & KT8900R has different zones for storing ranges
174

    
175
#seekto 0x3CD0;
176
struct {
177
  u8 vhf_low[3];
178
  u8 vhf_high[3];
179
  u8 unknown1[4];
180
  u8 unknown2[6];
181
  u8 vhf2_low[3];
182
  u8 vhf2_high[3];
183
  u8 unknown3[4];
184
  u8 unknown4[6];
185
  u8 uhf_low[3];
186
  u8 uhf_high[3];
187
} ranges220;
188

    
189
#seekto 0x3F70;
190
struct {
191
  char fp[6];
192
} fingerprint;
193

    
194
"""
195

    
196
# A note about the memmory in these radios
197
#
198
# The real memory of these radios extends to 0x4000
199
# On read the factory software only uses up to 0x3200
200
# On write it just uploads the contents up to 0x3100
201
#
202
# The mem beyond 0x3200 holds the ID data
203

    
204
MEM_SIZE = 0x4000
205
BLOCK_SIZE = 0x40
206
TX_BLOCK_SIZE = 0x10
207
ACK_CMD = "\x06"
208
MODES = ["FM", "NFM"]
209
SKIP_VALUES = ["S", ""]
210
TONES = chirp_common.TONES
211
DTCS = sorted(chirp_common.DTCS_CODES + [645])
212
NAME_LENGTH = 6
213
PTTID_LIST = ["OFF", "BOT", "EOT", "BOTH"]
214
PTTIDCODE_LIST = ["%s" % x for x in range(1, 16)]
215
OPTSIG_LIST = ["OFF", "DTMF", "2TONE", "5TONE"]
216
SPMUTE_LIST = ["Tone/DTCS", "Tone/DTCS and Optsig", "Tone/DTCS or Optsig"]
217

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

    
241
# This is a general serial timeout for all serial read functions.
242
# Practice has show that about 0.7 sec will be enough to cover all radios.
243
STIMEOUT = 0.7
244

    
245
# this var controls the verbosity in the debug and by default it's low (False)
246
# make it True and you will to get a very verbose debug.log
247
debug = False
248

    
249
# Power Levels
250
NORMAL_POWER_LEVELS = [chirp_common.PowerLevel("High", watts=25),
251
                       chirp_common.PowerLevel("Low", watts=10)]
252
UV5001_POWER_LEVELS = [chirp_common.PowerLevel("High", watts=50),
253
                       chirp_common.PowerLevel("Low", watts=10)]
254

    
255
# this must be defined globaly
256
POWER_LEVELS = None
257

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

    
262

    
263
##### ID strings #####################################################
264

    
265
# BTECH UV2501 pre-production units
266
UV2501pp_fp = "M2C294"
267
# BTECH UV2501 pre-production units 2 + and 1st Gen radios
268
UV2501pp2_fp = "M29204"
269
# B-TECH UV-2501 second generation (2G) radios
270
UV2501G2_fp = "BTG214"
271
# B-TECH UV-2501 third generation (3G) radios
272
UV2501G3_fp = "BTG324"
273

    
274
# B-TECH UV-2501+220 pre-production units
275
UV2501_220pp_fp = "M3C281"
276
# extra block read for the 2501+220 pre-production units
277
# the same for all of this radios so far
278
UV2501_220pp_id = "      280528"
279
# B-TECH UV-2501+220
280
UV2501_220_fp = "M3G201"
281
# new variant, let's call it Generation 2
282
UV2501_220G2_fp = "BTG211"
283
# B-TECH UV-2501+220 third generation (3G)
284
UV2501_220G3_fp = "BTG311"
285

    
286
# B-TECH UV-5001 pre-production units + 1st Gen radios
287
UV5001pp_fp = "V19204"
288
# B-TECH UV-5001 alpha units
289
UV5001alpha_fp = "V28204"
290
# B-TECH UV-5001 second generation (2G) radios
291
UV5001G2_fp = "BTG214"
292
# B-TECH UV-5001 second generation (2G2)
293
UV5001G22_fp = "V2G204"
294
# B-TECH UV-5001 third generation (3G)
295
UV5001G3_fp = "BTG304"
296

    
297
# special var to know when we found a BTECH Gen 3
298
BTECH3 = [UV2501G3_fp, UV2501_220G3_fp, UV5001G3_fp]
299

    
300

    
301
# WACCOM Mini-8900
302
MINI8900_fp = "M28854"
303

    
304

    
305
# QYT KT-UV980
306
KTUV980_fp = "H28854"
307

    
308
# QYT KT8900
309
KT8900_fp = "M29154"
310
# New generations KT8900
311
KT8900_fp1 = "M2C234"
312
KT8900_fp2 = "M2G1F4"
313
KT8900_fp3 = "M2G2F4"
314
KT8900_fp4 = "M2G304"
315
KT8900_fp5 = "M2G314"
316
# this radio has an extra ID
317
KT8900_id = "      303688"
318

    
319
# KT8900R
320
KT8900R_fp = "M3G1F4"
321
# Second Generation
322
KT8900R_fp1 = "M3G214"
323
# another model
324
KT8900R_fp2 = "M3C234"
325
# another model G4?
326
KT8900R_fp3 = "M39164"
327
# another model
328
KT8900R_fp4 = "M3G314"
329
# this radio has an extra ID
330
KT8900R_id = "280528"
331

    
332

    
333
# LUITON LT-588UV
334
LT588UV_fp = "V2G1F4"
335

    
336

    
337
#### MAGICS
338
# for the Waccom Mini-8900
339
MSTRING_MINI8900 = "\x55\xA5\xB5\x45\x55\x45\x4d\x02"
340
# for the B-TECH UV-2501+220 (including pre production ones)
341
MSTRING_220 = "\x55\x20\x15\x12\x12\x01\x4d\x02"
342
# for the QYT KT8900 & R
343
MSTRING_KT8900 = "\x55\x20\x15\x09\x16\x45\x4D\x02"
344
MSTRING_KT8900R = "\x55\x20\x15\x09\x25\x01\x4D\x02"
345
# magic string for all other models
346
MSTRING = "\x55\x20\x15\x09\x20\x45\x4d\x02"
347

    
348

    
349
def _clean_buffer(radio):
350
    """Cleaning the read serial buffer, hard timeout to survive an infinite
351
    data stream"""
352

    
353
    # touching the serial timeout to optimize the flushing
354
    # restored at the end to the default value
355
    radio.pipe.timeout = 0.1
356
    dump = "1"
357
    datacount = 0
358

    
359
    try:
360
        while len(dump) > 0:
361
            dump = radio.pipe.read(100)
362
            datacount += len(dump)
363
            # hard limit to survive a infinite serial data stream
364
            # 5 times bigger than a normal rx block (69 bytes)
365
            if datacount > 345:
366
                seriale = "Please check your serial port selection."
367
                raise errors.RadioError(seriale)
368

    
369
        # restore the default serial timeout
370
        radio.pipe.timeout = STIMEOUT
371

    
372
    except Exception:
373
        raise errors.RadioError("Unknown error cleaning the serial buffer")
374

    
375

    
376
def _rawrecv(radio, amount):
377
    """Raw read from the radio device, less intensive way"""
378

    
379
    data = ""
380

    
381
    try:
382
        data = radio.pipe.read(amount)
383

    
384
        # DEBUG
385
        if debug is True:
386
            LOG.debug("<== (%d) bytes:\n\n%s" %
387
                      (len(data), util.hexprint(data)))
388

    
389
        # fail if no data is received
390
        if len(data) == 0:
391
            raise errors.RadioError("No data received from radio")
392

    
393
        # notice on the logs if short
394
        if len(data) < amount:
395
            LOG.warn("Short reading %d bytes from the %d requested." %
396
                     (len(data), amount))
397

    
398
    except:
399
        raise errors.RadioError("Error reading data from radio")
400

    
401
    return data
402

    
403

    
404
def _send(radio, data):
405
    """Send data to the radio device"""
406

    
407
    try:
408
        for byte in data:
409
            radio.pipe.write(byte)
410
            # Some OS (mainly Linux ones) are too fast on the serial and
411
            # get the MCU inside the radio stuck in the early stages, this
412
            # hits some models more than others.
413
            #
414
            # To cope with that we introduce a delay on the writes.
415
            # Many option have been tested (delaying only after error occures, after short reads, only for linux, ...)
416
            # Finally, a static delay was chosen as simplest of all solutions (Michael Wagner, OE4AMW)
417
            # (for details, see issue 3993)
418
            sleep(0.002)
419

    
420
        # DEBUG
421
        if debug is True:
422
            LOG.debug("==> (%d) bytes:\n\n%s" %
423
                      (len(data), util.hexprint(data)))
424
    except:
425
        raise errors.RadioError("Error sending data to radio")
426

    
427

    
428
def _make_frame(cmd, addr, length, data=""):
429
    """Pack the info in the headder format"""
430
    frame = "\x06" + struct.pack(">BHB", ord(cmd), addr, length)
431
    # add the data if set
432
    if len(data) != 0:
433
        frame += data
434

    
435
    return frame
436

    
437

    
438
def _recv(radio, addr):
439
    """Get data from the radio all at once to lower syscalls load"""
440

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

    
444
    # get the whole block
445
    block = _rawrecv(radio, BLOCK_SIZE + 5)
446

    
447
    # basic check
448
    if len(block) < (BLOCK_SIZE + 5):
449
        raise errors.RadioError("Short read of the block 0x%04x" % addr)
450

    
451
    # checking for the ack
452
    if block[0] != ACK_CMD:
453
        raise errors.RadioError("Bad ack from radio in block 0x%04x" % addr)
454

    
455
    # header validation
456
    c, a, l = struct.unpack(">BHB", block[1:5])
457
    if a != addr or l != BLOCK_SIZE or c != ord("X"):
458
        LOG.debug("Invalid header for block 0x%04x" % addr)
459
        LOG.debug("CMD: %s  ADDR: %04x  SIZE: %02x" % (c, a, l))
460
        raise errors.RadioError("Invalid header for block 0x%04x:" % addr)
461

    
462
    # return the data
463
    return block[5:]
464

    
465

    
466
def _start_clone_mode(radio, status):
467
    """Put the radio in clone mode and get the ident string, 3 tries"""
468

    
469
    # cleaning the serial buffer
470
    _clean_buffer(radio)
471

    
472
    # prep the data to show in the UI
473
    status.cur = 0
474
    status.msg = "Identifying the radio..."
475
    status.max = 3
476
    radio.status_fn(status)
477

    
478
    try:
479
        for a in range(0, status.max):
480
            # Update the UI
481
            status.cur = a + 1
482
            radio.status_fn(status)
483

    
484
            # send the magic word
485
            _send(radio, radio._magic)
486

    
487
            # Now you get a x06 of ACK if all goes well
488
            ack = radio.pipe.read(1)
489

    
490
            if ack == "\x06":
491
                # DEBUG
492
                LOG.info("Magic ACK received")
493
                status.cur = status.max
494
                radio.status_fn(status)
495

    
496
                return True
497

    
498
        return False
499

    
500
    except errors.RadioError:
501
        raise
502
    except Exception, e:
503
        raise errors.RadioError("Error sending Magic to radio:\n%s" % e)
504

    
505

    
506
def _do_ident(radio, status, upload=False):
507
    """Put the radio in PROGRAM mode & identify it"""
508
    #  set the serial discipline
509
    radio.pipe.baudrate = 9600
510
    radio.pipe.parity = "N"
511

    
512
    # open the radio into program mode
513
    if _start_clone_mode(radio, status) is False:
514
        msg = "Radio did not enter clone mode"
515
        # warning about old versions of QYT KT8900
516
        if radio.MODEL == "KT8900":
517
            msg += ". You may want to try it as a WACCOM MINI-8900, there is a"
518
            msg += " known variant of this radios that is a clone of it."
519
        raise errors.RadioError(msg)
520

    
521
    # Ok, get the ident string
522
    ident = _rawrecv(radio, 49)
523

    
524
    # basic check for the ident
525
    if len(ident) != 49:
526
        raise errors.RadioError("Radio send a short ident block.")
527

    
528
    # check if ident is OK
529
    itis = False
530
    for fp in radio._fileid:
531
        if fp in ident:
532
            # got it!
533
            itis = True
534
            # checking if we are dealing with a Gen 3 BTECH
535
            if radio.VENDOR == "BTECH" and fp in BTECH3:
536
                radio.btech3 = True
537

    
538
            break
539

    
540
    if itis is False:
541
        LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
542
        raise errors.RadioError("Radio identification failed.")
543

    
544
    # some radios needs a extra read and check for a code on it, this ones
545
    # has the check value in the _id2 var, others simply False
546
    if radio._id2 is not False:
547
        # lower the timeout here as this radios are reseting due to timeout
548
        radio.pipe.timeout = 0.05
549

    
550
        # query & receive the extra ID
551
        _send(radio, _make_frame("S", 0x3DF0, 16))
552
        id2 = _rawrecv(radio, 21)
553

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

    
561
        # ok, the correct string must be in the received data
562
        if radio._id2 not in id2:
563
            LOG.debug("Full *BAD* extra ID on the %s is: \n%s" %
564
                      (radio.MODEL, util.hexprint(id2)))
565
            raise errors.RadioError("The extra ID is wrong, aborting.")
566

    
567
        # this radios need a extra request/answer here on the upload
568
        # the amount of data received depends of the radio type
569
        #
570
        # also the first block of TX must no have the ACK at the beginning
571
        # see _upload for this.
572
        if upload is True:
573
            # send an ACK
574
            _send(radio, ACK_CMD)
575

    
576
            # the amount of data depend on the radio, so far we have two radios
577
            # reading two bytes with an ACK at the end and just ONE with just
578
            # one byte (QYT KT8900)
579
            # the JT-6188 appears a clone of the last, but reads TWO bytes.
580
            #
581
            # we will read two bytes with a custom timeout to not penalize the
582
            # users for this.
583
            #
584
            # we just check for a response and last byte being a ACK, that is
585
            # the common stone for all radios (3 so far)
586
            ack = _rawrecv(radio, 2)
587

    
588
            # checking
589
            if len(ack) == 0 or ack[-1:] != ACK_CMD:
590
                raise errors.RadioError("Radio didn't ACK the upload")
591

    
592
            # restore the default serial timeout
593
            radio.pipe.timeout = STIMEOUT
594

    
595
    # DEBUG
596
    LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL))
597

    
598
    return True
599

    
600

    
601
def _download(radio):
602
    """Get the memory map"""
603

    
604
    # UI progress
605
    status = chirp_common.Status()
606

    
607
    # put radio in program mode and identify it
608
    _do_ident(radio, status)
609

    
610
    # the models that doesn't have the extra ID have to make a dummy read here
611
    if radio._id2 is False:
612
        _send(radio, _make_frame("S", 0, BLOCK_SIZE))
613
        discard = _rawrecv(radio, BLOCK_SIZE + 5)
614

    
615
        if debug is True:
616
            LOG.info("Dummy first block read done, got this:\n\n %s",
617
                     util.hexprint(discard))
618

    
619
    # reset the progress bar in the UI
620
    status.max = MEM_SIZE / BLOCK_SIZE
621
    status.msg = "Cloning from radio..."
622
    status.cur = 0
623
    radio.status_fn(status)
624

    
625
    # cleaning the serial buffer
626
    _clean_buffer(radio)
627

    
628
    data = ""
629
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
630
        # sending the read request
631
        _send(radio, _make_frame("S", addr, BLOCK_SIZE))
632

    
633
        # read
634
        d = _recv(radio, addr)
635

    
636
        # aggregate the data
637
        data += d
638

    
639
        # UI Update
640
        status.cur = addr / BLOCK_SIZE
641
        status.msg = "Cloning from radio..."
642
        radio.status_fn(status)
643

    
644
    return data
645

    
646

    
647
def _upload(radio):
648
    """Upload procedure"""
649

    
650
    # The UPLOAD mem is restricted to lower than 0x3100,
651
    # so we will overide that here localy
652
    MEM_SIZE = 0x3100
653

    
654
    # UI progress
655
    status = chirp_common.Status()
656

    
657
    # put radio in program mode and identify it
658
    _do_ident(radio, status, True)
659

    
660
    # get the data to upload to radio
661
    data = radio.get_mmap()
662

    
663
    # Reset the UI progress
664
    status.max = MEM_SIZE / TX_BLOCK_SIZE
665
    status.cur = 0
666
    status.msg = "Cloning to radio..."
667
    radio.status_fn(status)
668

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

    
673
    # cleaning the serial buffer
674
    _clean_buffer(radio)
675

    
676
    # the fun start here
677
    for addr in range(0, MEM_SIZE, TX_BLOCK_SIZE):
678
        # getting the block of data to send
679
        d = data[addr:addr + TX_BLOCK_SIZE]
680

    
681
        # build the frame to send
682
        frame = _make_frame("X", addr, TX_BLOCK_SIZE, d)
683

    
684
        # first block must not send the ACK at the beginning for the
685
        # ones that has the extra id, since this have to do a extra step
686
        if addr == 0 and radio._id2 is not False:
687
            frame = frame[1:]
688

    
689
        # send the frame
690
        _send(radio, frame)
691

    
692
        # receiving the response
693
        ack = _rawrecv(radio, 1)
694

    
695
        # basic check
696
        if len(ack) != 1:
697
            raise errors.RadioError("No ACK when writing block 0x%04x" % addr)
698

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

    
702
         # UI Update
703
        status.cur = addr / TX_BLOCK_SIZE
704
        status.msg = "Cloning to radio..."
705
        radio.status_fn(status)
706

    
707

    
708
def model_match(cls, data):
709
    """Match the opened/downloaded image to the correct version"""
710
    rid = data[0x3f70:0x3f76]
711

    
712
    if rid in cls._fileid:
713
        return True
714

    
715
    return False
716

    
717

    
718
def _decode_ranges(low, high):
719
    """Unpack the data in the ranges zones in the memmap and return
720
    a tuple with the integer corresponding to the Mhz it means"""
721
    ilow = int(low[0]) * 100 + int(low[1]) * 10 + int(low[2])
722
    ihigh = int(high[0]) * 100 + int(high[1]) * 10 + int(high[2])
723
    ilow *= 1000000
724
    ihigh *= 1000000
725

    
726
    return (ilow, ihigh)
727

    
728

    
729
def _split(rf, f1, f2):
730
    """Returns False if the two freqs are in the same band (no split)
731
    or True otherwise"""
732

    
733
    # determine if the two freqs are in the same band
734
    for low, high in rf.valid_bands:
735
        if f1 >= low and f1 <= high and \
736
                f2 >= low and f2 <= high:
737
            # if the two freqs are on the same Band this is not a split
738
            return False
739

    
740
    # if you get here is because the freq pairs are split
741
    return False
742

    
743

    
744
class BTech(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio):
745
    """BTECH's UV-5001 and alike radios"""
746
    VENDOR = "BTECH"
747
    MODEL = ""
748
    IDENT = ""
749
    _vhf_range = (130000000, 180000000)
750
    _220_range = (210000000, 231000000)
751
    _uhf_range = (400000000, 521000000)
752
    _upper = 199
753
    _magic = MSTRING
754
    _fileid = None
755
    _id2 = False
756
    btech3 = False
757

    
758
    @classmethod
759
    def get_prompts(cls):
760
        rp = chirp_common.RadioPrompts()
761
        rp.experimental = \
762
            ('This driver is experimental.\n'
763
             '\n'
764
             'Please keep a copy of your memories with the original software '
765
             'if you treasure them, this driver is new and may contain'
766
             ' bugs.\n'
767
             '\n'
768
             )
769
        rp.pre_download = _(dedent("""\
770
            Follow these instructions to download your info:
771

    
772
            1 - Turn off your radio
773
            2 - Connect your interface cable
774
            3 - Turn on your radio
775
            4 - Do the download of your radio data
776

    
777
            """))
778
        rp.pre_upload = _(dedent("""\
779
            Follow these instructions to upload your info:
780

    
781
            1 - Turn off your radio
782
            2 - Connect your interface cable
783
            3 - Turn on your radio
784
            4 - Do the upload of your radio data
785

    
786
            """))
787
        return rp
788

    
789
    def get_features(self):
790
        """Get the radio's features"""
791

    
792
        # we will use the following var as global
793
        global POWER_LEVELS
794

    
795
        rf = chirp_common.RadioFeatures()
796
        rf.has_settings = True
797
        rf.has_bank = False
798
        rf.has_tuning_step = False
799
        rf.can_odd_split = True
800
        rf.has_name = True
801
        rf.has_offset = True
802
        rf.has_mode = True
803
        rf.has_dtcs = True
804
        rf.has_rx_dtcs = True
805
        rf.has_dtcs_polarity = True
806
        rf.has_ctone = True
807
        rf.has_cross = True
808
        rf.valid_modes = MODES
809
        rf.valid_characters = VALID_CHARS
810
        rf.valid_name_length = NAME_LENGTH
811
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
812
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
813
        rf.valid_cross_modes = [
814
            "Tone->Tone",
815
            "DTCS->",
816
            "->DTCS",
817
            "Tone->DTCS",
818
            "DTCS->Tone",
819
            "->Tone",
820
            "DTCS->DTCS"]
821
        rf.valid_skips = SKIP_VALUES
822
        rf.valid_dtcs_codes = DTCS
823
        rf.memory_bounds = (0, self._upper)
824

    
825
        # power levels
826
        if self.MODEL == "UV-5001":
827
            POWER_LEVELS = UV5001_POWER_LEVELS  # Higher power (50W)
828
        else:
829
            POWER_LEVELS = NORMAL_POWER_LEVELS  # Lower power (25W)
830

    
831
        rf.valid_power_levels = POWER_LEVELS
832

    
833
        # bands
834
        rf.valid_bands = [self._vhf_range, self._uhf_range]
835

    
836
        # 2501+220 & KT8900R
837
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
838
            rf.valid_bands.append(self._220_range)
839

    
840
        return rf
841

    
842
    def sync_in(self):
843
        """Download from radio"""
844
        data = _download(self)
845
        self._mmap = memmap.MemoryMap(data)
846
        self.process_mmap()
847

    
848
    def sync_out(self):
849
        """Upload to radio"""
850
        try:
851
            _upload(self)
852
        except errors.RadioError:
853
            raise
854
        except Exception, e:
855
            raise errors.RadioError("Error: %s" % e)
856

    
857
    def set_options(self):
858
        """This is to read the options from the image and set it in the
859
        environment, for now just the limits of the freqs in the VHF/UHF
860
        ranges"""
861

    
862
        # setting the correct ranges for each radio type
863
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
864
            # the model 2501+220 has a segment in 220
865
            # and a different position in the memmap
866
            # also the QYT KT8900R
867
            ranges = self._memobj.ranges220
868
        else:
869
            ranges = self._memobj.ranges
870

    
871
        # the normal dual bands
872
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
873
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
874

    
875
        # DEBUG
876
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
877
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
878

    
879
        # 220Mhz radios case
880
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
881
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
882
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
883
            self._220_range = vhf2
884

    
885
        # set the class with the real data
886
        self._vhf_range = vhf
887
        self._uhf_range = uhf
888

    
889
    def process_mmap(self):
890
        """Process the mem map into the mem object"""
891

    
892
        # Get it
893
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
894

    
895
        # load specific parameters from the radio image
896
        self.set_options()
897

    
898
    def get_raw_memory(self, number):
899
        return repr(self._memobj.memory[number])
900

    
901
    def _decode_tone(self, val):
902
        """Parse the tone data to decode from mem, it returns:
903
        Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)"""
904
        pol = None
905

    
906
        if val in [0, 65535]:
907
            return '', None, None
908
        elif val > 0x0258:
909
            a = val / 10.0
910
            return 'Tone', a, pol
911
        else:
912
            if val > 0x69:
913
                index = val - 0x6A
914
                pol = "R"
915
            else:
916
                index = val - 1
917
                pol = "N"
918

    
919
            tone = DTCS[index]
920
            return 'DTCS', tone, pol
921

    
922
    def _encode_tone(self, memval, mode, val, pol):
923
        """Parse the tone data to encode from UI to mem"""
924
        if mode == '' or mode is None:
925
            memval.set_raw("\x00\x00")
926
        elif mode == 'Tone':
927
            memval.set_value(val * 10)
928
        elif mode == 'DTCS':
929
            # detect the index in the DTCS list
930
            try:
931
                index = DTCS.index(val)
932
                if pol == "N":
933
                    index += 1
934
                else:
935
                    index += 0x6A
936
                memval.set_value(index)
937
            except:
938
                msg = "Digital Tone '%d' is not supported" % value
939
                LOG.error(msg)
940
                raise errors.RadioError(msg)
941
        else:
942
            msg = "Internal error: invalid mode '%s'" % mode
943
            LOG.error(msg)
944
            raise errors.InvalidDataError(msg)
945

    
946
    def get_memory(self, number):
947
        """Get the mem representation from the radio image"""
948
        _mem = self._memobj.memory[number]
949
        _names = self._memobj.names[number]
950

    
951
        # Create a high-level memory object to return to the UI
952
        mem = chirp_common.Memory()
953

    
954
        # Memory number
955
        mem.number = number
956

    
957
        if _mem.get_raw()[0] == "\xFF":
958
            mem.empty = True
959
            return mem
960

    
961
        # Freq and offset
962
        mem.freq = int(_mem.rxfreq) * 10
963
        # tx freq can be blank
964
        if _mem.get_raw()[4] == "\xFF":
965
            # TX freq not set
966
            mem.offset = 0
967
            mem.duplex = "off"
968
        else:
969
            # TX freq set
970
            offset = (int(_mem.txfreq) * 10) - mem.freq
971
            if offset != 0:
972
                if _split(self.get_features(), mem.freq, int(_mem.txfreq) * 10):
973
                    mem.duplex = "split"
974
                    mem.offset = int(_mem.txfreq) * 10
975
                elif offset < 0:
976
                    mem.offset = abs(offset)
977
                    mem.duplex = "-"
978
                elif offset > 0:
979
                    mem.offset = offset
980
                    mem.duplex = "+"
981
            else:
982
                mem.offset = 0
983

    
984
        # name TAG of the channel
985
        mem.name = str(_names.name).rstrip("\xFF").replace("\xFF", " ")
986

    
987
        # power
988
        mem.power = POWER_LEVELS[int(_mem.power)]
989

    
990
        # wide/narrow
991
        mem.mode = MODES[int(_mem.wide)]
992

    
993
        # skip
994
        mem.skip = SKIP_VALUES[_mem.add]
995

    
996
        # tone data
997
        rxtone = txtone = None
998
        txtone = self._decode_tone(_mem.txtone)
999
        rxtone = self._decode_tone(_mem.rxtone)
1000
        chirp_common.split_tone_decode(mem, txtone, rxtone)
1001

    
1002
        # Extra
1003
        mem.extra = RadioSettingGroup("extra", "Extra")
1004

    
1005
        scramble = RadioSetting("scramble", "Scramble",
1006
                                RadioSettingValueBoolean(bool(_mem.scramble)))
1007
        mem.extra.append(scramble)
1008

    
1009
        bcl = RadioSetting("bcl", "Busy channel lockout",
1010
                           RadioSettingValueBoolean(bool(_mem.bcl)))
1011
        mem.extra.append(bcl)
1012

    
1013
        pttid = RadioSetting("pttid", "PTT ID",
1014
                             RadioSettingValueList(PTTID_LIST,
1015
                                                   PTTID_LIST[_mem.pttid]))
1016
        mem.extra.append(pttid)
1017

    
1018
        # validating scode
1019
        scode = _mem.scode if _mem.scode != 15 else 0
1020
        pttidcode = RadioSetting("scode", "PTT ID signal code",
1021
                                 RadioSettingValueList(
1022
                                     PTTIDCODE_LIST,
1023
                                     PTTIDCODE_LIST[scode]))
1024
        mem.extra.append(pttidcode)
1025

    
1026
        optsig = RadioSetting("optsig", "Optional signaling",
1027
                              RadioSettingValueList(
1028
                                  OPTSIG_LIST,
1029
                                  OPTSIG_LIST[_mem.optsig]))
1030
        mem.extra.append(optsig)
1031

    
1032
        spmute = RadioSetting("spmute", "Speaker mute",
1033
                              RadioSettingValueList(
1034
                                  SPMUTE_LIST,
1035
                                  SPMUTE_LIST[_mem.spmute]))
1036
        mem.extra.append(spmute)
1037

    
1038
        return mem
1039

    
1040
    def set_memory(self, mem):
1041
        """Set the memory data in the eeprom img from the UI"""
1042
        # get the eprom representation of this channel
1043
        _mem = self._memobj.memory[mem.number]
1044
        _names = self._memobj.names[mem.number]
1045

    
1046
        # if empty memmory
1047
        if mem.empty:
1048
            # the channel itself
1049
            _mem.set_raw("\xFF" * 16)
1050
            # the name tag
1051
            _names.set_raw("\xFF" * 16)
1052
            return
1053

    
1054
        # frequency
1055
        _mem.rxfreq = mem.freq / 10
1056

    
1057
        # duplex
1058
        if mem.duplex == "+":
1059
            _mem.txfreq = (mem.freq + mem.offset) / 10
1060
        elif mem.duplex == "-":
1061
            _mem.txfreq = (mem.freq - mem.offset) / 10
1062
        elif mem.duplex == "off":
1063
            for i in _mem.txfreq:
1064
                i.set_raw("\xFF")
1065
        elif mem.duplex == "split":
1066
            _mem.txfreq = mem.offset / 10
1067
        else:
1068
            _mem.txfreq = mem.freq / 10
1069

    
1070
        # tone data
1071
        ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
1072
            chirp_common.split_tone_encode(mem)
1073
        self._encode_tone(_mem.txtone, txmode, txtone, txpol)
1074
        self._encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)
1075

    
1076
        # name TAG of the channel
1077
        if len(mem.name) < NAME_LENGTH:
1078
            # we must pad to NAME_LENGTH chars, " " = "\xFF"
1079
            mem.name = str(mem.name).ljust(NAME_LENGTH, " ")
1080
        _names.name = str(mem.name).replace(" ", "\xFF")
1081

    
1082
        # power, # default power level is high
1083
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
1084

    
1085
        # wide/narrow
1086
        _mem.wide = MODES.index(mem.mode)
1087

    
1088
        # scan add property
1089
        _mem.add = SKIP_VALUES.index(mem.skip)
1090

    
1091
        # reseting unknowns, this have to be set by hand
1092
        _mem.unknown0 = 0
1093
        _mem.unknown1 = 0
1094
        _mem.unknown2 = 0
1095
        _mem.unknown3 = 0
1096
        _mem.unknown4 = 0
1097
        _mem.unknown5 = 0
1098
        _mem.unknown6 = 0
1099

    
1100
        # extra settings
1101
        if len(mem.extra) > 0:
1102
            # there are setting, parse
1103
            for setting in mem.extra:
1104
                setattr(_mem, setting.get_name(), setting.value)
1105
        else:
1106
            # there is no extra settings, load defaults
1107
            _mem.spmute = 0
1108
            _mem.optsig = 0
1109
            _mem.scramble = 0
1110
            _mem.bcl = 0
1111
            _mem.pttid = 0
1112
            _mem.scode = 0
1113

    
1114
        return mem
1115

    
1116
    def get_settings(self):
1117
        """Translate the bit in the mem_struct into settings in the UI"""
1118
        _mem = self._memobj
1119
        basic = RadioSettingGroup("basic", "Basic Settings")
1120
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
1121
        other = RadioSettingGroup("other", "Other Settings")
1122
        work = RadioSettingGroup("work", "Work Mode Settings")
1123
        fm_presets = RadioSettingGroup("fm_presets", "FM Presets")
1124
        top = RadioSettings(basic, advanced, other, work, fm_presets)
1125

    
1126
        # Basic
1127
        tdr = RadioSetting("settings.tdr", "Transceiver dual receive",
1128
                           RadioSettingValueBoolean(_mem.settings.tdr))
1129
        basic.append(tdr)
1130

    
1131
        sql = RadioSetting("settings.sql", "Squelch level",
1132
                           RadioSettingValueInteger(0, 9, _mem.settings.sql))
1133
        basic.append(sql)
1134

    
1135
        tot = RadioSetting("settings.tot", "Time out timer",
1136
                           RadioSettingValueList(LIST_TOT, LIST_TOT[
1137
                               _mem.settings.tot]))
1138
        basic.append(tot)
1139

    
1140
        if self.MODEL in ("UV-2501", "UV-2501+220", "UV-5001"):
1141
            apo = RadioSetting("settings.apo", "Auto power off timer",
1142
                               RadioSettingValueList(LIST_APO, LIST_APO[
1143
                                   _mem.settings.apo]))
1144
            basic.append(apo)
1145
        else:
1146
            toa = RadioSetting("settings.apo", "Time out alert timer",
1147
                               RadioSettingValueList(LIST_TOA, LIST_TOA[
1148
                                   _mem.settings.apo]))
1149
            basic.append(toa)
1150

    
1151
        abr = RadioSetting("settings.abr", "Backlight timer",
1152
                           RadioSettingValueList(LIST_ABR, LIST_ABR[
1153
                               _mem.settings.abr]))
1154
        basic.append(abr)
1155

    
1156
        beep = RadioSetting("settings.beep", "Key beep",
1157
                            RadioSettingValueBoolean(_mem.settings.beep))
1158
        basic.append(beep)
1159

    
1160
        dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone",
1161
                              RadioSettingValueList(LIST_DTMFST, LIST_DTMFST[
1162
                                  _mem.settings.dtmfst]))
1163
        basic.append(dtmfst)
1164

    
1165
        prisc = RadioSetting("settings.prisc", "Priority scan",
1166
                             RadioSettingValueBoolean(_mem.settings.prisc))
1167
        basic.append(prisc)
1168

    
1169
        prich = RadioSetting("settings.prich", "Priority channel",
1170
                             RadioSettingValueInteger(0, 199,
1171
                                 _mem.settings.prich))
1172
        basic.append(prich)
1173

    
1174
        screv = RadioSetting("settings.screv", "Scan resume method",
1175
                             RadioSettingValueList(LIST_SCREV, LIST_SCREV[
1176
                                 _mem.settings.screv]))
1177
        basic.append(screv)
1178

    
1179
        pttlt = RadioSetting("settings.pttlt", "PTT transmit delay",
1180
                             RadioSettingValueInteger(0, 30,
1181
                                 _mem.settings.pttlt))
1182
        basic.append(pttlt)
1183

    
1184
        emctp = RadioSetting("settings.emctp", "Alarm mode",
1185
                             RadioSettingValueList(LIST_EMCTP, LIST_EMCTP[
1186
                                 _mem.settings.emctp]))
1187
        basic.append(emctp)
1188

    
1189
        emcch = RadioSetting("settings.emcch", "Alarm channel",
1190
                             RadioSettingValueInteger(0, 199,
1191
                                 _mem.settings.emcch))
1192
        basic.append(emcch)
1193

    
1194
        ringt = RadioSetting("settings.ringt", "Ring time",
1195
                             RadioSettingValueList(LIST_RINGT, LIST_RINGT[
1196
                                 _mem.settings.ringt]))
1197
        basic.append(ringt)
1198

    
1199
        camdf = RadioSetting("settings.camdf", "Display mode A",
1200
                             RadioSettingValueList(LIST_MDF, LIST_MDF[
1201
                                 _mem.settings.camdf]))
1202
        basic.append(camdf)
1203

    
1204
        cbmdf = RadioSetting("settings.cbmdf", "Display mode B",
1205
                             RadioSettingValueList(LIST_MDF, LIST_MDF[
1206
                                 _mem.settings.cbmdf]))
1207
        basic.append(cbmdf)
1208

    
1209
        if self.MODEL in ("UV-2501", "UV-2501+220", "UV-5001"):
1210
           sync = RadioSetting("settings.sync", "A/B channel sync",
1211
                               RadioSettingValueBoolean(_mem.settings.sync))
1212
           basic.append(sync)
1213
        else:
1214
           autolk = RadioSetting("settings.sync", "Auto keylock",
1215
                                 RadioSettingValueBoolean(_mem.settings.sync))
1216
           basic.append(autolk)
1217

    
1218
        ponmsg = RadioSetting("settings.ponmsg", "Power-on message",
1219
                              RadioSettingValueList(LIST_PONMSG, LIST_PONMSG[
1220
                                  _mem.settings.ponmsg]))
1221
        basic.append(ponmsg)
1222

    
1223
        wtled = RadioSetting("settings.wtled", "Standby backlight Color",
1224
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1225
                                 _mem.settings.wtled]))
1226
        basic.append(wtled)
1227

    
1228
        rxled = RadioSetting("settings.rxled", "RX backlight Color",
1229
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1230
                                 _mem.settings.rxled]))
1231
        basic.append(rxled)
1232

    
1233
        txled = RadioSetting("settings.txled", "TX backlight Color",
1234
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1235
                                 _mem.settings.txled]))
1236
        basic.append(txled)
1237

    
1238
        anil = RadioSetting("settings.anil", "ANI length",
1239
                            RadioSettingValueList(LIST_ANIL, LIST_ANIL[
1240
                                _mem.settings.anil]))
1241
        basic.append(anil)
1242

    
1243
        reps = RadioSetting("settings.reps", "Relay signal (tone burst)",
1244
                            RadioSettingValueList(LIST_REPS, LIST_REPS[
1245
                                _mem.settings.reps]))
1246
        basic.append(reps)
1247

    
1248
        repm = RadioSetting("settings.repm", "Relay condition",
1249
                            RadioSettingValueList(LIST_REPM, LIST_REPM[
1250
                                _mem.settings.repm]))
1251
        basic.append(repm)
1252

    
1253
        if self.MODEL in ("UV-2501", "UV-2501+220", "UV-5001"):
1254
            tdrab = RadioSetting("settings.tdrab", "TDR return time",
1255
                                 RadioSettingValueList(LIST_ABR, LIST_ABR[
1256
                                     _mem.settings.tdrab]))
1257
            basic.append(tdrab)
1258

    
1259
            ste = RadioSetting("settings.ste", "Squelch tail eliminate",
1260
                               RadioSettingValueBoolean(_mem.settings.ste))
1261
            basic.append(ste)
1262

    
1263
            rpste = RadioSetting("settings.rpste", "Repeater STE",
1264
                                 RadioSettingValueList(LIST_RINGT, LIST_RINGT[
1265
                                     _mem.settings.rpste]))
1266
            basic.append(rpste)
1267

    
1268
            rptdl = RadioSetting("settings.rptdl", "Repeater STE delay",
1269
                                 RadioSettingValueList(LIST_RPTDL, LIST_RPTDL[
1270
                                     _mem.settings.rptdl]))
1271
            basic.append(rptdl)
1272

    
1273
        if str(_mem.fingerprint.fp) in BTECH3:
1274

    
1275
            mgain = RadioSetting("settings.mgain", "Mic gain",
1276
                                 RadioSettingValueInteger(0, 120,
1277
                                     _mem.settings.mgain))
1278
            basic.append(mgain)
1279

    
1280
            dtmfg = RadioSetting("settings.dtmfg", "DTMF gain",
1281
                                 RadioSettingValueInteger(0, 60,
1282
                                     _mem.settings.dtmfg))
1283
            basic.append(dtmfg)
1284

    
1285
        # Advanced
1286
        def _filter(name):
1287
            filtered = ""
1288
            for char in str(name):
1289
                if char in VALID_CHARS:
1290
                    filtered += char
1291
                else:
1292
                    filtered += " "
1293
            return filtered
1294

    
1295
        _msg = self._memobj.poweron_msg
1296
        line1 = RadioSetting("poweron_msg.line1", "Power-on message line 1",
1297
                             RadioSettingValueString(0, 6, _filter(
1298
                                 _msg.line1)))
1299
        advanced.append(line1)
1300
        line2 = RadioSetting("poweron_msg.line2", "Power-on message line 2",
1301
                             RadioSettingValueString(0, 6, _filter(
1302
                                 _msg.line2)))
1303
        advanced.append(line2)
1304

    
1305
        if self.MODEL in ("UV-2501", "UV-5001"):
1306
            vfomren = RadioSetting("settings2.vfomren", "VFO/MR switching",
1307
                                   RadioSettingValueBoolean(
1308
                                       _mem.settings2.vfomren))
1309
            advanced.append(vfomren)
1310

    
1311
            reseten = RadioSetting("settings2.reseten", "RESET",
1312
                                   RadioSettingValueBoolean(
1313
                                       _mem.settings2.reseten))
1314
            advanced.append(reseten)
1315

    
1316
            menuen = RadioSetting("settings2.menuen", "Menu",
1317
                                  RadioSettingValueBoolean(
1318
                                      _mem.settings2.menuen))
1319
            advanced.append(menuen)
1320

    
1321
        # Other
1322
        def convert_bytes_to_limit(bytes):
1323
            limit = ""
1324
            for byte in bytes:
1325
                if byte < 10:
1326
                    limit += chr(byte + 0x30)
1327
                else:
1328
                    break
1329
            return limit
1330

    
1331
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1332
            _ranges = self._memobj.ranges220
1333
            ranges = "ranges220"
1334
        else:
1335
            _ranges = self._memobj.ranges
1336
            ranges = "ranges"
1337

    
1338
        _limit = convert_bytes_to_limit(_ranges.vhf_low)
1339
        val = RadioSettingValueString(0, 3, _limit)
1340
        val.set_mutable(False)
1341
        vhf_low = RadioSetting("%s.vhf_low" % ranges, "VHF low", val)
1342
        other.append(vhf_low)
1343

    
1344
        _limit = convert_bytes_to_limit(_ranges.vhf_high)
1345
        val = RadioSettingValueString(0, 3, _limit)
1346
        val.set_mutable(False)
1347
        vhf_high = RadioSetting("%s.vhf_high" % ranges, "VHF high", val)
1348
        other.append(vhf_high)
1349

    
1350
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1351
            _limit = convert_bytes_to_limit(_ranges.vhf2_low)
1352
            val = RadioSettingValueString(0, 3, _limit)
1353
            val.set_mutable(False)
1354
            vhf2_low = RadioSetting("%s.vhf2_low" % ranges, "VHF2 low", val)
1355
            other.append(vhf2_low)
1356

    
1357
            _limit = convert_bytes_to_limit(_ranges.vhf2_high)
1358
            val = RadioSettingValueString(0, 3, _limit)
1359
            val.set_mutable(False)
1360
            vhf2_high = RadioSetting("%s.vhf2_high" % ranges, "VHF2 high", val)
1361
            other.append(vhf2_high)
1362

    
1363
        _limit = convert_bytes_to_limit(_ranges.uhf_low)
1364
        val = RadioSettingValueString(0, 3, _limit)
1365
        val.set_mutable(False)
1366
        uhf_low = RadioSetting("%s.uhf_low" % ranges, "UHF low", val)
1367
        other.append(uhf_low)
1368

    
1369
        _limit = convert_bytes_to_limit(_ranges.uhf_high)
1370
        val = RadioSettingValueString(0, 3, _limit)
1371
        val.set_mutable(False)
1372
        uhf_high = RadioSetting("%s.uhf_high" % ranges, "UHF high", val)
1373
        other.append(uhf_high)
1374

    
1375
        val = RadioSettingValueString(0, 6, _filter(_mem.fingerprint.fp))
1376
        val.set_mutable(False)
1377
        fp = RadioSetting("fingerprint.fp", "Fingerprint", val)
1378
        other.append(fp)
1379

    
1380
        # Work
1381
        dispab = RadioSetting("settings2.dispab", "Display",
1382
                              RadioSettingValueList(LIST_AB,LIST_AB[
1383
                                  _mem.settings2.dispab]))
1384
        work.append(dispab)
1385

    
1386
        vfomr = RadioSetting("settings2.vfomr", "VFO/MR mode",
1387
                             RadioSettingValueList(LIST_VFOMR,LIST_VFOMR[
1388
                                 _mem.settings2.vfomr]))
1389
        work.append(vfomr)
1390

    
1391
        keylock = RadioSetting("settings2.keylock", "Keypad lock",
1392
                           RadioSettingValueBoolean(_mem.settings2.keylock))
1393
        work.append(keylock)
1394

    
1395
        mrcha = RadioSetting("settings2.mrcha", "MR A channel",
1396
                             RadioSettingValueInteger(0, 199,
1397
                                 _mem.settings2.mrcha))
1398
        work.append(mrcha)
1399

    
1400
        mrchb = RadioSetting("settings2.mrchb", "MR B channel",
1401
                             RadioSettingValueInteger(0, 199,
1402
                                 _mem.settings2.mrchb))
1403
        work.append(mrchb)
1404

    
1405
        def convert_bytes_to_freq(bytes):
1406
            real_freq = 0
1407
            for byte in bytes:
1408
                real_freq = (real_freq * 10) + byte
1409
            return chirp_common.format_freq(real_freq * 10)
1410

    
1411
        def my_validate(value):
1412
            value = chirp_common.parse_freq(value)
1413
            if "+220" in self.MODEL:
1414
                if 180000000 <= value and value < 210000000:
1415
                    msg = ("Can't be between 180.00000-210.00000")
1416
                    raise InvalidValueError(msg)
1417
                elif 231000000 <= value and value < 400000000:
1418
                    msg = ("Can't be between 231.00000-400.00000")
1419
                    raise InvalidValueError(msg)
1420
            elif "8900R" in self.MODEL:
1421
                if 180000000 <= value and value < 240000000:
1422
                    msg = ("Can't be between 180.00000-240.00000")
1423
                    raise InvalidValueError(msg)
1424
                elif 271000000 <= value and value < 400000000:
1425
                    msg = ("Can't be between 271.00000-400.00000")
1426
                    raise InvalidValueError(msg)
1427
            elif 180000000 <= value and value < 400000000:
1428
                msg = ("Can't be between 180.00000-400.00000")
1429
                raise InvalidValueError(msg)
1430
            return chirp_common.format_freq(value)
1431

    
1432
        def apply_freq(setting, obj):
1433
            value = chirp_common.parse_freq(str(setting.value)) / 10
1434
            for i in range(7, -1, -1):
1435
                obj.freq[i] = value % 10
1436
                value /= 10
1437

    
1438
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1439
                                        _mem.vfo.a.freq))
1440
        val1a.set_validate_callback(my_validate)
1441
        vfoafreq = RadioSetting("vfo.a.freq", "VFO A frequency", val1a)
1442
        vfoafreq.set_apply_callback(apply_freq, _mem.vfo.a)
1443
        work.append(vfoafreq)
1444

    
1445
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1446
                                        _mem.vfo.b.freq))
1447
        val1b.set_validate_callback(my_validate)
1448
        vfobfreq = RadioSetting("vfo.b.freq", "VFO B frequency", val1b)
1449
        vfobfreq.set_apply_callback(apply_freq, _mem.vfo.b)
1450
        work.append(vfobfreq)
1451

    
1452
        vfoashiftd = RadioSetting("vfo.a.shiftd", "VFO A shift",
1453
                                  RadioSettingValueList(LIST_SHIFT, LIST_SHIFT[
1454
                                      _mem.vfo.a.shiftd]))
1455
        work.append(vfoashiftd)
1456

    
1457
        vfobshiftd = RadioSetting("vfo.b.shiftd", "VFO B shift",
1458
                                  RadioSettingValueList(LIST_SHIFT, LIST_SHIFT[
1459
                                      _mem.vfo.b.shiftd]))
1460
        work.append(vfobshiftd)
1461

    
1462
        def convert_bytes_to_offset(bytes):
1463
            real_offset = 0
1464
            for byte in bytes:
1465
                real_offset = (real_offset * 10) + byte
1466
            return chirp_common.format_freq(real_offset * 10000)
1467

    
1468
        def apply_offset(setting, obj):
1469
            value = chirp_common.parse_freq(str(setting.value)) / 10000
1470
            for i in range(3, -1, -1):
1471
                obj.offset[i] = value % 10
1472
                value /= 10
1473

    
1474
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1475
                                        _mem.vfo.a.offset))
1476
        vfoaoffset = RadioSetting("vfo.a.offset",
1477
                                  "VFO A offset (0.00-99.95)", val1a)
1478
        vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
1479
        work.append(vfoaoffset)
1480

    
1481
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1482
                                        _mem.vfo.b.offset))
1483
        vfoboffset = RadioSetting("vfo.b.offset",
1484
                                  "VFO B offset (0.00-99.95)", val1b)
1485
        vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
1486
        work.append(vfoboffset)
1487

    
1488
        vfoatxp = RadioSetting("vfo.a.power", "VFO A power",
1489
                                RadioSettingValueList(LIST_TXP,LIST_TXP[
1490
                                    _mem.vfo.a.power]))
1491
        work.append(vfoatxp)
1492

    
1493
        vfobtxp = RadioSetting("vfo.b.power", "VFO B power",
1494
                                RadioSettingValueList(LIST_TXP,LIST_TXP[
1495
                                    _mem.vfo.b.power]))
1496
        work.append(vfobtxp)
1497

    
1498
        vfoawide = RadioSetting("vfo.a.wide", "VFO A bandwidth",
1499
                                RadioSettingValueList(LIST_WIDE,LIST_WIDE[
1500
                                    _mem.vfo.a.wide]))
1501
        work.append(vfoawide)
1502

    
1503
        vfobwide = RadioSetting("vfo.b.wide", "VFO B bandwidth",
1504
                                RadioSettingValueList(LIST_WIDE,LIST_WIDE[
1505
                                    _mem.vfo.b.wide]))
1506
        work.append(vfobwide)
1507

    
1508
        vfoastep = RadioSetting("vfo.a.step", "VFO A step",
1509
                                RadioSettingValueList(LIST_STEP,LIST_STEP[
1510
                                    _mem.vfo.a.step]))
1511
        work.append(vfoastep)
1512

    
1513
        vfobstep = RadioSetting("vfo.b.step", "VFO B step",
1514
                                RadioSettingValueList(LIST_STEP,LIST_STEP[
1515
                                    _mem.vfo.b.step]))
1516
        work.append(vfobstep)
1517

    
1518
        vfoaoptsig = RadioSetting("vfo.a.optsig", "VFO A optional signal",
1519
                                  RadioSettingValueList(OPTSIG_LIST,
1520
                                      OPTSIG_LIST[_mem.vfo.a.optsig]))
1521
        work.append(vfoaoptsig)
1522

    
1523
        vfoboptsig = RadioSetting("vfo.b.optsig", "VFO B optional signal",
1524
                                  RadioSettingValueList(OPTSIG_LIST,
1525
                                      OPTSIG_LIST[_mem.vfo.b.optsig]))
1526
        work.append(vfoboptsig)
1527

    
1528
        vfoaspmute = RadioSetting("vfo.a.spmute", "VFO A speaker mute",
1529
                                  RadioSettingValueList(SPMUTE_LIST,
1530
                                      SPMUTE_LIST[_mem.vfo.a.spmute]))
1531
        work.append(vfoaspmute)
1532

    
1533
        vfobspmute = RadioSetting("vfo.b.spmute", "VFO B speaker mute",
1534
                                  RadioSettingValueList(SPMUTE_LIST,
1535
                                      SPMUTE_LIST[_mem.vfo.b.spmute]))
1536
        work.append(vfobspmute)
1537

    
1538
        vfoascr = RadioSetting("vfo.a.scramble", "VFO A scramble",
1539
                               RadioSettingValueBoolean(_mem.vfo.a.scramble))
1540
        work.append(vfoascr)
1541

    
1542
        vfobscr = RadioSetting("vfo.b.scramble", "VFO B scramble",
1543
                               RadioSettingValueBoolean(_mem.vfo.b.scramble))
1544
        work.append(vfobscr)
1545

    
1546
        vfoascode = RadioSetting("vfo.a.scode", "VFO A PTT-ID",
1547
                                 RadioSettingValueList(PTTIDCODE_LIST,
1548
                                     PTTIDCODE_LIST[_mem.vfo.a.scode]))
1549
        work.append(vfoascode)
1550

    
1551
        vfobscode = RadioSetting("vfo.b.scode", "VFO B PTT-ID",
1552
                                 RadioSettingValueList(PTTIDCODE_LIST,
1553
                                     PTTIDCODE_LIST[_mem.vfo.b.scode]))
1554
        work.append(vfobscode)
1555

    
1556
        pttid = RadioSetting("settings.pttid", "PTT ID",
1557
                             RadioSettingValueList(PTTID_LIST,
1558
                                 PTTID_LIST[_mem.settings.pttid]))
1559
        work.append(pttid)
1560

    
1561
        #FM presets
1562
        def fm_validate(value):
1563
            if value == 0:
1564
                return chirp_common.format_freq(value)
1565
            if not (87.5 <= value and value <= 108.0):  # 87.5-108MHz
1566
                msg = ("FM-Preset-Frequency: Must be between 87.5 and 108 MHz")
1567
                raise InvalidValueError(msg)
1568
            return value
1569

    
1570
        def apply_fm_preset_name(setting, obj):
1571
            valstring = str (setting.value)
1572
            for i in range(0,6):
1573
                if valstring[i] in VALID_CHARS:
1574
                    obj[i] = valstring[i]
1575
                else:
1576
                    obj[i] = '0xff'
1577

    
1578
        def apply_fm_freq(setting, obj):
1579
            value = chirp_common.parse_freq(str(setting.value)) / 10
1580
            for i in range(7, -1, -1):
1581
                obj.freq[i] = value % 10
1582
                value /= 10
1583
        
1584
        _presets = self._memobj.fm_radio_preset
1585
        i = 1
1586
        for preset in _presets:
1587
            line = RadioSetting("fm_presets_"+ str(i), "Station name " + str(i),
1588
                                RadioSettingValueString(0, 6, _filter(
1589
                                    preset.broadcast_station_name)))
1590
            line.set_apply_callback(apply_fm_preset_name, 
1591
                                    preset.broadcast_station_name)
1592
            
1593
            val = RadioSettingValueFloat(0, 108, convert_bytes_to_freq(preset.freq))
1594
            fmfreq = RadioSetting("fm_presets_"+ str(i) + "_freq", "Frequency "+ str(i), val)
1595
            val.set_validate_callback(fm_validate)
1596
            fmfreq.set_apply_callback(apply_fm_freq, preset)
1597
            fm_presets.append(line)
1598
            fm_presets.append(fmfreq)
1599
            
1600
            i = i + 1
1601
            
1602
        return top
1603

    
1604
    def set_settings(self, settings):
1605
        _settings = self._memobj.settings
1606
        for element in settings:
1607
            if not isinstance(element, RadioSetting):
1608
                if element.get_name() == "fm_preset":
1609
                    self._set_fm_preset(element)
1610
                else:
1611
                    self.set_settings(element)
1612
                    continue
1613
            else:
1614
                try:
1615
                    name = element.get_name()
1616
                    if "." in name:
1617
                        bits = name.split(".")
1618
                        obj = self._memobj
1619
                        for bit in bits[:-1]:
1620
                            if "/" in bit:
1621
                                bit, index = bit.split("/", 1)
1622
                                index = int(index)
1623
                                obj = getattr(obj, bit)[index]
1624
                            else:
1625
                                obj = getattr(obj, bit)
1626
                        setting = bits[-1]
1627
                    else:
1628
                        obj = _settings
1629
                        setting = element.get_name()
1630

    
1631
                    if element.has_apply_callback():
1632
                        LOG.debug("Using apply callback")
1633
                        element.run_apply_callback()
1634
                    elif element.value.get_mutable():
1635
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1636
                        setattr(obj, setting, element.value)
1637
                except Exception, e:
1638
                    LOG.debug(element.get_name())
1639
                    raise
1640

    
1641
    @classmethod
1642
    def match_model(cls, filedata, filename):
1643
        match_size = False
1644
        match_model = False
1645

    
1646
        # testing the file data size
1647
        if len(filedata) == MEM_SIZE:
1648
            match_size = True
1649

    
1650
        # testing the firmware model fingerprint
1651
        match_model = model_match(cls, filedata)
1652

    
1653
        if match_size and match_model:
1654
            return True
1655
        else:
1656
            return False
1657

    
1658

    
1659
# Declaring Aliases (Clones of the real radios)
1660
class JT2705M(chirp_common.Alias):
1661
    VENDOR = "Jetstream"
1662
    MODEL = "JT2705M"
1663

    
1664

    
1665
class JT6188Mini(chirp_common.Alias):
1666
    VENDOR = "Juentai"
1667
    MODEL = "JT-6188 Mini"
1668

    
1669

    
1670
class JT6188Plus(chirp_common.Alias):
1671
    VENDOR = "Juentai"
1672
    MODEL = "JT-6188 Plus"
1673

    
1674

    
1675
class SSGT890(chirp_common.Alias):
1676
    VENDOR = "Sainsonic"
1677
    MODEL = "GT-890"
1678

    
1679

    
1680
class ZastoneMP300(chirp_common.Alias):
1681
    VENDOR = "Zastone"
1682
    MODEL = "MP-300"
1683

    
1684

    
1685
# real radios
1686
@directory.register
1687
class UV2501(BTech):
1688
    """Baofeng Tech UV2501"""
1689
    MODEL = "UV-2501"
1690
    _fileid = [UV2501G3_fp,
1691
               UV2501G2_fp,
1692
               UV2501pp2_fp,
1693
               UV2501pp_fp]
1694

    
1695

    
1696
@directory.register
1697
class UV2501_220(BTech):
1698
    """Baofeng Tech UV2501+220"""
1699
    MODEL = "UV-2501+220"
1700
    _magic = MSTRING_220
1701
    _id2 = UV2501_220pp_id
1702
    _fileid = [UV2501_220G3_fp,
1703
               UV2501_220G2_fp,
1704
               UV2501_220_fp,
1705
               UV2501_220pp_fp]
1706

    
1707

    
1708
@directory.register
1709
class UV5001(BTech):
1710
    """Baofeng Tech UV5001"""
1711
    MODEL = "UV-5001"
1712
    _fileid = [UV5001G3_fp,
1713
               UV5001G22_fp,
1714
               UV5001G2_fp,
1715
               UV5001alpha_fp,
1716
               UV5001pp_fp]
1717

    
1718

    
1719
@directory.register
1720
class MINI8900(BTech):
1721
    """WACCOM MINI-8900"""
1722
    VENDOR = "WACCOM"
1723
    MODEL = "MINI-8900"
1724
    _magic = MSTRING_MINI8900
1725
    _fileid = [MINI8900_fp, ]
1726
    # Clones
1727
    ALIASES = [JT6188Plus, ]
1728

    
1729

    
1730
@directory.register
1731
class KTUV980(BTech):
1732
    """QYT KT-UV980"""
1733
    VENDOR = "QYT"
1734
    MODEL = "KT-UV980"
1735
    _vhf_range = (136000000, 175000000)
1736
    _uhf_range = (400000000, 481000000)
1737
    _magic = MSTRING_MINI8900
1738
    _fileid = [KTUV980_fp, ]
1739
    # Clones
1740
    ALIASES = [JT2705M, ]
1741

    
1742
# Please note that there is a version of this radios that is a clone of the
1743
# Waccom Mini8900, maybe an early version?
1744
@directory.register
1745
class KT9800(BTech):
1746
    """QYT KT8900"""
1747
    VENDOR = "QYT"
1748
    MODEL = "KT8900"
1749
    _vhf_range = (136000000, 175000000)
1750
    _uhf_range = (400000000, 481000000)
1751
    _magic = MSTRING_KT8900
1752
    _fileid = [KT8900_fp,
1753
               KT8900_fp1,
1754
               KT8900_fp2,
1755
               KT8900_fp3,
1756
               KT8900_fp4,
1757
               KT8900_fp5]
1758
    _id2 = KT8900_id
1759
    # Clones
1760
    ALIASES = [JT6188Mini, SSGT890, ZastoneMP300]
1761

    
1762

    
1763
@directory.register
1764
class KT9800R(BTech):
1765
    """QYT KT8900R"""
1766
    VENDOR = "QYT"
1767
    MODEL = "KT8900R"
1768
    _vhf_range = (136000000, 175000000)
1769
    _220_range = (240000000, 271000000)
1770
    _uhf_range = (400000000, 481000000)
1771
    _magic = MSTRING_KT8900R
1772
    _fileid = [KT8900R_fp,
1773
               KT8900R_fp1,
1774
               KT8900R_fp2,
1775
               KT8900R_fp3,
1776
               KT8900R_fp4]
1777
    _id2 = KT8900R_id
1778

    
1779

    
1780
@directory.register
1781
class LT588UV(BTech):
1782
    """LUITON LT-588UV"""
1783
    VENDOR = "LUITON"
1784
    MODEL = "LT-588UV"
1785
    _vhf_range = (136000000, 175000000)
1786
    _uhf_range = (400000000, 481000000)
1787
    _magic = MSTRING_KT8900
1788
    _fileid = [LT588UV_fp, ]
(4-4/4)