Project

General

Profile

Bug #3993 » btech(1).py

Michael Wagner, 09/12/2016 10:32 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 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
    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 0x3C90;
159
struct {
160
  u8 vhf_low[3];
161
  u8 vhf_high[3];
162
  u8 uhf_low[3];
163
  u8 uhf_high[3];
164
} ranges;
165

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

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

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

    
187
"""
188

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

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

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

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

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

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

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

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

    
255

    
256
##### ID strings #####################################################
257

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

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

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

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

    
293

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

    
297

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

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

    
311
# KT8900R
312
KT8900R_fp = "M3G1F4"
313
# Second Generation
314
KT8900R_fp1 = "M3G214"
315
# another model
316
KT8900R_fp2 = "M3C234"
317
# another model G4?
318
KT8900R_fp3 = "M39164"
319
# this radio has an extra ID
320
KT8900R_id = "280528"
321

    
322

    
323
# LUITON LT-588UV
324
LT588UV_fp = "V2G1F4"
325

    
326

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

    
338

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

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

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

    
359
        # restore the default serial timeout
360
        radio.pipe.timeout = STIMEOUT
361

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

    
365

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

    
369
    data = ""
370

    
371
    try:
372
        data = radio.pipe.read(amount)
373

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

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

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

    
388
    except:
389
        raise errors.RadioError("Error reading data from radio")
390

    
391
    return data
392

    
393

    
394
def _send(radio, data):
395
    """Send data to the radio device"""
396

    
397
    try:
398
        for byte in data:
399
            radio.pipe.write(byte)
400
            # linux is to fast in the serial, causing the radio send a \x05
401
            # byte and stop responding, we need to slow it down a bit.
402
            # Thanks to Michael Wagner for this fix.
403
            # we have not noticed any problem in MAC (YET)
404
            if sys.platform.startswith ('linux'):
405
                # 10 msec is proved to be safe.
406
                sleep(0.005)
407

    
408
        # DEBUG
409
        if debug is True:
410
            LOG.debug("==> (%d) bytes:\n\n%s" %
411
                      (len(data), util.hexprint(data)))
412
    except:
413
        raise errors.RadioError("Error sending data to radio")
414

    
415

    
416
def _make_frame(cmd, addr, length, data=""):
417
    """Pack the info in the headder format"""
418
    frame = "\x06" + struct.pack(">BHB", ord(cmd), addr, length)
419
    # add the data if set
420
    if len(data) != 0:
421
        frame += data
422

    
423
    return frame
424

    
425

    
426
def _recv(radio, addr):
427
    """Get data from the radio all at once to lower syscalls load"""
428

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

    
432
    # get the whole block
433
    block = _rawrecv(radio, BLOCK_SIZE + 5)
434

    
435
    # basic check
436
    if len(block) < (BLOCK_SIZE + 5):
437
        raise errors.RadioError("Short read of the block 0x%04x" % addr)
438

    
439
    # checking for the ack
440
    if block[0] != ACK_CMD:
441
        raise errors.RadioError("Bad ack from radio in block 0x%04x" % addr)
442

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

    
450
    # return the data
451
    return block[5:]
452

    
453

    
454
def _start_clone_mode(radio, status):
455
    """Put the radio in clone mode and get the ident string, 3 tries"""
456

    
457
    # cleaning the serial buffer
458
    _clean_buffer(radio)
459

    
460
    # prep the data to show in the UI
461
    status.cur = 0
462
    status.msg = "Identifying the radio..."
463
    status.max = 3
464
    radio.status_fn(status)
465

    
466
    try:
467
        for a in range(0, status.max):
468
            # Update the UI
469
            status.cur = a + 1
470
            radio.status_fn(status)
471

    
472
            # send the magic word
473
            _send(radio, radio._magic)
474

    
475
            # Now you get a x06 of ACK if all goes well
476
            ack = radio.pipe.read(1)
477

    
478
            if ack == "\x06":
479
                # DEBUG
480
                LOG.info("Magic ACK received")
481
                status.cur = status.max
482
                radio.status_fn(status)
483

    
484
                return True
485

    
486
        return False
487

    
488
    except errors.RadioError:
489
        raise
490
    except Exception, e:
491
        raise errors.RadioError("Error sending Magic to radio:\n%s" % e)
492

    
493

    
494
def _do_ident(radio, status, upload=False):
495
    """Put the radio in PROGRAM mode & identify it"""
496
    #  set the serial discipline
497
    radio.pipe.baudrate = 9600
498
    radio.pipe.parity = "N"
499

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

    
509
    # Ok, get the ident string
510
    ident = _rawrecv(radio, 49)
511

    
512
    # basic check for the ident
513
    if len(ident) != 49:
514
        raise errors.RadioError("Radio send a short ident block.")
515

    
516
    # check if ident is OK
517
    itis = False
518
    for fp in radio._fileid:
519
        if fp in ident:
520
            # got it!
521
            itis = True
522
            # checking if we are dealing with a Gen 3 BTECH
523
            if radio.VENDOR == "BTECH" and fp in BTECH3:
524
                radio.btech3 = True
525

    
526
            break
527

    
528
    if itis is False:
529
        LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
530
        raise errors.RadioError("Radio identification failed.")
531

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

    
538
        # query & receive the extra ID
539
        _send(radio, _make_frame("S", 0x3DF0, 16))
540
        id2 = _rawrecv(radio, 21)
541

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

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

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

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

    
576
            # checking
577
            if len(ack) == 0 or ack[-1:] != ACK_CMD:
578
                raise errors.RadioError("Radio didn't ACK the upload")
579

    
580
            # restore the default serial timeout
581
            radio.pipe.timeout = STIMEOUT
582

    
583
    # DEBUG
584
    LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL))
585

    
586
    return True
587

    
588

    
589
def _download(radio):
590
    """Get the memory map"""
591

    
592
    # UI progress
593
    status = chirp_common.Status()
594

    
595
    # put radio in program mode and identify it
596
    _do_ident(radio, status)
597

    
598
    # the models that doesn't have the extra ID have to make a dummy read here
599
    if radio._id2 is False:
600
        _send(radio, _make_frame("S", 0, BLOCK_SIZE))
601
        discard = _rawrecv(radio, BLOCK_SIZE + 5)
602

    
603
        if debug is True:
604
            LOG.info("Dummy first block read done, got this:\n\n %s",
605
                     util.hexprint(discard))
606

    
607
    # reset the progress bar in the UI
608
    status.max = MEM_SIZE / BLOCK_SIZE
609
    status.msg = "Cloning from radio..."
610
    status.cur = 0
611
    radio.status_fn(status)
612

    
613
    # cleaning the serial buffer
614
    _clean_buffer(radio)
615

    
616
    data = ""
617
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
618
        # sending the read request
619
        _send(radio, _make_frame("S", addr, BLOCK_SIZE))
620

    
621
        # read
622
        d = _recv(radio, addr)
623

    
624
        # aggregate the data
625
        data += d
626

    
627
        # UI Update
628
        status.cur = addr / BLOCK_SIZE
629
        status.msg = "Cloning from radio..."
630
        radio.status_fn(status)
631

    
632
    return data
633

    
634

    
635
def _upload(radio):
636
    """Upload procedure"""
637

    
638
    # The UPLOAD mem is restricted to lower than 0x3100,
639
    # so we will overide that here localy
640
    MEM_SIZE = 0x3100
641

    
642
    # UI progress
643
    status = chirp_common.Status()
644

    
645
    # put radio in program mode and identify it
646
    _do_ident(radio, status, True)
647

    
648
    # get the data to upload to radio
649
    data = radio.get_mmap()
650

    
651
    # Reset the UI progress
652
    status.max = MEM_SIZE / TX_BLOCK_SIZE
653
    status.cur = 0
654
    status.msg = "Cloning to radio..."
655
    radio.status_fn(status)
656

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

    
661
    # cleaning the serial buffer
662
    _clean_buffer(radio)
663

    
664
    # the fun start here
665
    for addr in range(0, MEM_SIZE, TX_BLOCK_SIZE):
666
        # getting the block of data to send
667
        d = data[addr:addr + TX_BLOCK_SIZE]
668

    
669
        # build the frame to send
670
        frame = _make_frame("X", addr, TX_BLOCK_SIZE, d)
671

    
672
        # first block must not send the ACK at the beginning for the
673
        # ones that has the extra id, since this have to do a extra step
674
        if addr == 0 and radio._id2 is not False:
675
            frame = frame[1:]
676

    
677
        # send the frame
678
        _send(radio, frame)
679

    
680
        # receiving the response
681
        ack = _rawrecv(radio, 1)
682

    
683
        # basic check
684
        if len(ack) != 1:
685
            raise errors.RadioError("No ACK when writing block 0x%04x" % addr)
686

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

    
690
         # UI Update
691
        status.cur = addr / TX_BLOCK_SIZE
692
        status.msg = "Cloning to radio..."
693
        radio.status_fn(status)
694

    
695

    
696
def model_match(cls, data):
697
    """Match the opened/downloaded image to the correct version"""
698
    rid = data[0x3f70:0x3f76]
699

    
700
    if rid in cls._fileid:
701
        return True
702

    
703
    return False
704

    
705

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

    
714
    return (ilow, ihigh)
715

    
716

    
717
def _split(rf, f1, f2):
718
    """Returns False if the two freqs are in the same band (no split)
719
    or True otherwise"""
720

    
721
    # determine if the two freqs are in the same band
722
    for low, high in rf.valid_bands:
723
        if f1 >= low and f1 <= high and \
724
                f2 >= low and f2 <= high:
725
            # if the two freqs are on the same Band this is not a split
726
            return False
727

    
728
    # if you get here is because the freq pairs are split
729
    return False
730

    
731

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

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

    
760
            1 - Turn off your radio
761
            2 - Connect your interface cable
762
            3 - Turn on your radio
763
            4 - Do the download of your radio data
764

    
765
            """))
766
        rp.pre_upload = _(dedent("""\
767
            Follow these instructions to upload your info:
768

    
769
            1 - Turn off your radio
770
            2 - Connect your interface cable
771
            3 - Turn on your radio
772
            4 - Do the upload of your radio data
773

    
774
            """))
775
        return rp
776

    
777
    def get_features(self):
778
        """Get the radio's features"""
779

    
780
        # we will use the following var as global
781
        global POWER_LEVELS
782

    
783
        rf = chirp_common.RadioFeatures()
784
        rf.has_settings = True
785
        rf.has_bank = False
786
        rf.has_tuning_step = False
787
        rf.can_odd_split = True
788
        rf.has_name = True
789
        rf.has_offset = True
790
        rf.has_mode = True
791
        rf.has_dtcs = True
792
        rf.has_rx_dtcs = True
793
        rf.has_dtcs_polarity = True
794
        rf.has_ctone = True
795
        rf.has_cross = True
796
        rf.valid_modes = MODES
797
        rf.valid_characters = VALID_CHARS
798
        rf.valid_name_length = NAME_LENGTH
799
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
800
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
801
        rf.valid_cross_modes = [
802
            "Tone->Tone",
803
            "DTCS->",
804
            "->DTCS",
805
            "Tone->DTCS",
806
            "DTCS->Tone",
807
            "->Tone",
808
            "DTCS->DTCS"]
809
        rf.valid_skips = SKIP_VALUES
810
        rf.valid_dtcs_codes = DTCS
811
        rf.memory_bounds = (0, self._upper)
812

    
813
        # power levels
814
        if self.MODEL == "UV-5001":
815
            POWER_LEVELS = UV5001_POWER_LEVELS  # Higher power (50W)
816
        else:
817
            POWER_LEVELS = NORMAL_POWER_LEVELS  # Lower power (25W)
818

    
819
        rf.valid_power_levels = POWER_LEVELS
820

    
821
        # bands
822
        rf.valid_bands = [self._vhf_range, self._uhf_range]
823

    
824
        # 2501+220 & KT8900R
825
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
826
            rf.valid_bands.append(self._220_range)
827

    
828
        return rf
829

    
830
    def sync_in(self):
831
        """Download from radio"""
832
        data = _download(self)
833
        self._mmap = memmap.MemoryMap(data)
834
        self.process_mmap()
835

    
836
    def sync_out(self):
837
        """Upload to radio"""
838
        try:
839
            _upload(self)
840
        except errors.RadioError:
841
            raise
842
        except Exception, e:
843
            raise errors.RadioError("Error: %s" % e)
844

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

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

    
859
        # the normal dual bands
860
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
861
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
862

    
863
        # DEBUG
864
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
865
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
866

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

    
873
        # set the class with the real data
874
        self._vhf_range = vhf
875
        self._uhf_range = uhf
876

    
877
    def process_mmap(self):
878
        """Process the mem map into the mem object"""
879

    
880
        # Get it
881
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
882

    
883
        # load specific parameters from the radio image
884
        self.set_options()
885

    
886
    def get_raw_memory(self, number):
887
        return repr(self._memobj.memory[number])
888

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

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

    
907
            tone = DTCS[index]
908
            return 'DTCS', tone, pol
909

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

    
934
    def get_memory(self, number):
935
        """Get the mem representation from the radio image"""
936
        _mem = self._memobj.memory[number]
937
        _names = self._memobj.names[number]
938

    
939
        # Create a high-level memory object to return to the UI
940
        mem = chirp_common.Memory()
941

    
942
        # Memory number
943
        mem.number = number
944

    
945
        if _mem.get_raw()[0] == "\xFF":
946
            mem.empty = True
947
            return mem
948

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

    
972
        # name TAG of the channel
973
        mem.name = str(_names.name).rstrip("\xFF").replace("\xFF", " ")
974

    
975
        # power
976
        mem.power = POWER_LEVELS[int(_mem.power)]
977

    
978
        # wide/narrow
979
        mem.mode = MODES[int(_mem.wide)]
980

    
981
        # skip
982
        mem.skip = SKIP_VALUES[_mem.add]
983

    
984
        # tone data
985
        rxtone = txtone = None
986
        txtone = self._decode_tone(_mem.txtone)
987
        rxtone = self._decode_tone(_mem.rxtone)
988
        chirp_common.split_tone_decode(mem, txtone, rxtone)
989

    
990
        # Extra
991
        mem.extra = RadioSettingGroup("extra", "Extra")
992

    
993
        scramble = RadioSetting("scramble", "Scramble",
994
                                RadioSettingValueBoolean(bool(_mem.scramble)))
995
        mem.extra.append(scramble)
996

    
997
        bcl = RadioSetting("bcl", "Busy channel lockout",
998
                           RadioSettingValueBoolean(bool(_mem.bcl)))
999
        mem.extra.append(bcl)
1000

    
1001
        pttid = RadioSetting("pttid", "PTT ID",
1002
                             RadioSettingValueList(PTTID_LIST,
1003
                                                   PTTID_LIST[_mem.pttid]))
1004
        mem.extra.append(pttid)
1005

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

    
1014
        optsig = RadioSetting("optsig", "Optional signaling",
1015
                              RadioSettingValueList(
1016
                                  OPTSIG_LIST,
1017
                                  OPTSIG_LIST[_mem.optsig]))
1018
        mem.extra.append(optsig)
1019

    
1020
        spmute = RadioSetting("spmute", "Speaker mute",
1021
                              RadioSettingValueList(
1022
                                  SPMUTE_LIST,
1023
                                  SPMUTE_LIST[_mem.spmute]))
1024
        mem.extra.append(spmute)
1025

    
1026
        return mem
1027

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

    
1034
        # if empty memmory
1035
        if mem.empty:
1036
            # the channel itself
1037
            _mem.set_raw("\xFF" * 16)
1038
            # the name tag
1039
            _names.set_raw("\xFF" * 16)
1040
            return
1041

    
1042
        # frequency
1043
        _mem.rxfreq = mem.freq / 10
1044

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

    
1058
        # tone data
1059
        ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
1060
            chirp_common.split_tone_encode(mem)
1061
        self._encode_tone(_mem.txtone, txmode, txtone, txpol)
1062
        self._encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)
1063

    
1064
        # name TAG of the channel
1065
        if len(mem.name) < NAME_LENGTH:
1066
            # we must pad to NAME_LENGTH chars, " " = "\xFF"
1067
            mem.name = str(mem.name).ljust(NAME_LENGTH, " ")
1068
        _names.name = str(mem.name).replace(" ", "\xFF")
1069

    
1070
        # power, # default power level is high
1071
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
1072

    
1073
        # wide/narrow
1074
        _mem.wide = MODES.index(mem.mode)
1075

    
1076
        # scan add property
1077
        _mem.add = SKIP_VALUES.index(mem.skip)
1078

    
1079
        # reseting unknowns, this have to be set by hand
1080
        _mem.unknown0 = 0
1081
        _mem.unknown1 = 0
1082
        _mem.unknown2 = 0
1083
        _mem.unknown3 = 0
1084
        _mem.unknown4 = 0
1085
        _mem.unknown5 = 0
1086
        _mem.unknown6 = 0
1087

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

    
1102
        return mem
1103

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

    
1113
        # Basic
1114
        tdr = RadioSetting("settings.tdr", "Transceiver dual receive",
1115
                           RadioSettingValueBoolean(_mem.settings.tdr))
1116
        basic.append(tdr)
1117

    
1118
        sql = RadioSetting("settings.sql", "Squelch level",
1119
                           RadioSettingValueInteger(0, 9, _mem.settings.sql))
1120
        basic.append(sql)
1121

    
1122
        tot = RadioSetting("settings.tot", "Time out timer",
1123
                           RadioSettingValueList(LIST_TOT, LIST_TOT[
1124
                               _mem.settings.tot]))
1125
        basic.append(tot)
1126

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

    
1138
        abr = RadioSetting("settings.abr", "Backlight timer",
1139
                           RadioSettingValueList(LIST_ABR, LIST_ABR[
1140
                               _mem.settings.abr]))
1141
        basic.append(abr)
1142

    
1143
        beep = RadioSetting("settings.beep", "Key beep",
1144
                            RadioSettingValueBoolean(_mem.settings.beep))
1145
        basic.append(beep)
1146

    
1147
        dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone",
1148
                              RadioSettingValueList(LIST_DTMFST, LIST_DTMFST[
1149
                                  _mem.settings.dtmfst]))
1150
        basic.append(dtmfst)
1151

    
1152
        prisc = RadioSetting("settings.prisc", "Priority scan",
1153
                             RadioSettingValueBoolean(_mem.settings.prisc))
1154
        basic.append(prisc)
1155

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

    
1161
        screv = RadioSetting("settings.screv", "Scan resume method",
1162
                             RadioSettingValueList(LIST_SCREV, LIST_SCREV[
1163
                                 _mem.settings.screv]))
1164
        basic.append(screv)
1165

    
1166
        pttlt = RadioSetting("settings.pttlt", "PTT transmit delay",
1167
                             RadioSettingValueInteger(0, 30,
1168
                                 _mem.settings.pttlt))
1169
        basic.append(pttlt)
1170

    
1171
        emctp = RadioSetting("settings.emctp", "Alarm mode",
1172
                             RadioSettingValueList(LIST_EMCTP, LIST_EMCTP[
1173
                                 _mem.settings.emctp]))
1174
        basic.append(emctp)
1175

    
1176
        emcch = RadioSetting("settings.emcch", "Alarm channel",
1177
                             RadioSettingValueInteger(0, 199,
1178
                                 _mem.settings.emcch))
1179
        basic.append(emcch)
1180

    
1181
        ringt = RadioSetting("settings.ringt", "Ring time",
1182
                             RadioSettingValueList(LIST_RINGT, LIST_RINGT[
1183
                                 _mem.settings.ringt]))
1184
        basic.append(ringt)
1185

    
1186
        camdf = RadioSetting("settings.camdf", "Display mode A",
1187
                             RadioSettingValueList(LIST_MDF, LIST_MDF[
1188
                                 _mem.settings.camdf]))
1189
        basic.append(camdf)
1190

    
1191
        cbmdf = RadioSetting("settings.cbmdf", "Display mode B",
1192
                             RadioSettingValueList(LIST_MDF, LIST_MDF[
1193
                                 _mem.settings.cbmdf]))
1194
        basic.append(cbmdf)
1195

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

    
1205
        ponmsg = RadioSetting("settings.ponmsg", "Power-on message",
1206
                              RadioSettingValueList(LIST_PONMSG, LIST_PONMSG[
1207
                                  _mem.settings.ponmsg]))
1208
        basic.append(ponmsg)
1209

    
1210
        wtled = RadioSetting("settings.wtled", "Standby backlight Color",
1211
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1212
                                 _mem.settings.wtled]))
1213
        basic.append(wtled)
1214

    
1215
        rxled = RadioSetting("settings.rxled", "RX backlight Color",
1216
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1217
                                 _mem.settings.rxled]))
1218
        basic.append(rxled)
1219

    
1220
        txled = RadioSetting("settings.txled", "TX backlight Color",
1221
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1222
                                 _mem.settings.txled]))
1223
        basic.append(txled)
1224

    
1225
        anil = RadioSetting("settings.anil", "ANI length",
1226
                            RadioSettingValueList(LIST_ANIL, LIST_ANIL[
1227
                                _mem.settings.anil]))
1228
        basic.append(anil)
1229

    
1230
        reps = RadioSetting("settings.reps", "Relay signal (tone burst)",
1231
                            RadioSettingValueList(LIST_REPS, LIST_REPS[
1232
                                _mem.settings.reps]))
1233
        basic.append(reps)
1234

    
1235
        repm = RadioSetting("settings.repm", "Relay condition",
1236
                            RadioSettingValueList(LIST_REPM, LIST_REPM[
1237
                                _mem.settings.repm]))
1238
        basic.append(repm)
1239

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

    
1246
            ste = RadioSetting("settings.ste", "Squelch tail eliminate",
1247
                               RadioSettingValueBoolean(_mem.settings.ste))
1248
            basic.append(ste)
1249

    
1250
            rpste = RadioSetting("settings.rpste", "Repeater STE",
1251
                                 RadioSettingValueList(LIST_RINGT, LIST_RINGT[
1252
                                     _mem.settings.rpste]))
1253
            basic.append(rpste)
1254

    
1255
            rptdl = RadioSetting("settings.rptdl", "Repeater STE delay",
1256
                                 RadioSettingValueList(LIST_RPTDL, LIST_RPTDL[
1257
                                     _mem.settings.rptdl]))
1258
            basic.append(rptdl)
1259

    
1260
        if str(_mem.fingerprint.fp) in BTECH3:
1261

    
1262
            mgain = RadioSetting("settings.mgain", "Mic gain",
1263
                                 RadioSettingValueInteger(0, 120,
1264
                                     _mem.settings.mgain))
1265
            basic.append(mgain)
1266

    
1267
            dtmfg = RadioSetting("settings.dtmfg", "DTMF gain",
1268
                                 RadioSettingValueInteger(0, 60,
1269
                                     _mem.settings.dtmfg))
1270
            basic.append(dtmfg)
1271

    
1272
        # Advanced
1273
        def _filter(name):
1274
            filtered = ""
1275
            for char in str(name):
1276
                if char in VALID_CHARS:
1277
                    filtered += char
1278
                else:
1279
                    filtered += " "
1280
            return filtered
1281

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

    
1292
        if self.MODEL in ("UV-2501", "UV-5001"):
1293
            vfomren = RadioSetting("settings2.vfomren", "VFO/MR switching",
1294
                                   RadioSettingValueBoolean(
1295
                                       not _mem.settings2.vfomren))
1296
            advanced.append(vfomren)
1297

    
1298
            reseten = RadioSetting("settings2.reseten", "RESET",
1299
                                   RadioSettingValueBoolean(
1300
                                       _mem.settings2.reseten))
1301
            advanced.append(reseten)
1302

    
1303
            menuen = RadioSetting("settings2.menuen", "Menu",
1304
                                  RadioSettingValueBoolean(
1305
                                      _mem.settings2.menuen))
1306
            advanced.append(menuen)
1307

    
1308
        # Other
1309
        def convert_bytes_to_limit(bytes):
1310
            limit = ""
1311
            for byte in bytes:
1312
                if byte < 10:
1313
                    limit += chr(byte + 0x30)
1314
                else:
1315
                    break
1316
            return limit
1317

    
1318
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1319
            _ranges = self._memobj.ranges220
1320
            ranges = "ranges220"
1321
        else:
1322
            _ranges = self._memobj.ranges
1323
            ranges = "ranges"
1324

    
1325
        _limit = convert_bytes_to_limit(_ranges.vhf_low)
1326
        val = RadioSettingValueString(0, 3, _limit)
1327
        val.set_mutable(False)
1328
        vhf_low = RadioSetting("%s.vhf_low" % ranges, "VHF low", val)
1329
        other.append(vhf_low)
1330

    
1331
        _limit = convert_bytes_to_limit(_ranges.vhf_high)
1332
        val = RadioSettingValueString(0, 3, _limit)
1333
        val.set_mutable(False)
1334
        vhf_high = RadioSetting("%s.vhf_high" % ranges, "VHF high", val)
1335
        other.append(vhf_high)
1336

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

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

    
1350
        _limit = convert_bytes_to_limit(_ranges.uhf_low)
1351
        val = RadioSettingValueString(0, 3, _limit)
1352
        val.set_mutable(False)
1353
        uhf_low = RadioSetting("%s.uhf_low" % ranges, "UHF low", val)
1354
        other.append(uhf_low)
1355

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

    
1362
        val = RadioSettingValueString(0, 6, _filter(_mem.fingerprint.fp))
1363
        val.set_mutable(False)
1364
        fp = RadioSetting("fingerprint.fp", "Fingerprint", val)
1365
        other.append(fp)
1366

    
1367
        # Work
1368
        dispab = RadioSetting("settings2.dispab", "Display",
1369
                              RadioSettingValueList(LIST_AB,LIST_AB[
1370
                                  _mem.settings2.dispab]))
1371
        work.append(dispab)
1372

    
1373
        vfomr = RadioSetting("settings2.vfomr", "VFO/MR mode",
1374
                             RadioSettingValueList(LIST_VFOMR,LIST_VFOMR[
1375
                                 _mem.settings2.vfomr]))
1376
        work.append(vfomr)
1377

    
1378
        keylock = RadioSetting("settings2.keylock", "Keypad lock",
1379
                           RadioSettingValueBoolean(_mem.settings2.keylock))
1380
        work.append(keylock)
1381

    
1382
        mrcha = RadioSetting("settings2.mrcha", "MR A channel",
1383
                             RadioSettingValueInteger(0, 199,
1384
                                 _mem.settings2.mrcha))
1385
        work.append(mrcha)
1386

    
1387
        mrchb = RadioSetting("settings2.mrchb", "MR B channel",
1388
                             RadioSettingValueInteger(0, 199,
1389
                                 _mem.settings2.mrchb))
1390
        work.append(mrchb)
1391

    
1392
        def convert_bytes_to_freq(bytes):
1393
            real_freq = 0
1394
            for byte in bytes:
1395
                real_freq = (real_freq * 10) + byte
1396
            return chirp_common.format_freq(real_freq * 10)
1397

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

    
1419
        def apply_freq(setting, obj):
1420
            value = chirp_common.parse_freq(str(setting.value)) / 10
1421
            for i in range(7, -1, -1):
1422
                obj.freq[i] = value % 10
1423
                value /= 10
1424

    
1425
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1426
                                        _mem.vfo.a.freq))
1427
        val1a.set_validate_callback(my_validate)
1428
        vfoafreq = RadioSetting("vfo.a.freq", "VFO A frequency", val1a)
1429
        vfoafreq.set_apply_callback(apply_freq, _mem.vfo.a)
1430
        work.append(vfoafreq)
1431

    
1432
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1433
                                        _mem.vfo.b.freq))
1434
        val1b.set_validate_callback(my_validate)
1435
        vfobfreq = RadioSetting("vfo.b.freq", "VFO B frequency", val1b)
1436
        vfobfreq.set_apply_callback(apply_freq, _mem.vfo.b)
1437
        work.append(vfobfreq)
1438

    
1439
        vfoashiftd = RadioSetting("vfo.a.shiftd", "VFO A shift",
1440
                                  RadioSettingValueList(LIST_SHIFT, LIST_SHIFT[
1441
                                      _mem.vfo.a.shiftd]))
1442
        work.append(vfoashiftd)
1443

    
1444
        vfobshiftd = RadioSetting("vfo.b.shiftd", "VFO B shift",
1445
                                  RadioSettingValueList(LIST_SHIFT, LIST_SHIFT[
1446
                                      _mem.vfo.b.shiftd]))
1447
        work.append(vfobshiftd)
1448

    
1449
        def convert_bytes_to_offset(bytes):
1450
            real_offset = 0
1451
            for byte in bytes:
1452
                real_offset = (real_offset * 10) + byte
1453
            return chirp_common.format_freq(real_offset * 10000)
1454

    
1455
        def apply_offset(setting, obj):
1456
            value = chirp_common.parse_freq(str(setting.value)) / 10000
1457
            for i in range(3, -1, -1):
1458
                obj.offset[i] = value % 10
1459
                value /= 10
1460

    
1461
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1462
                                        _mem.vfo.a.offset))
1463
        vfoaoffset = RadioSetting("vfo.a.offset",
1464
                                  "VFO A offset (0.00-99.95)", val1a)
1465
        vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
1466
        work.append(vfoaoffset)
1467

    
1468
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1469
                                        _mem.vfo.b.offset))
1470
        vfoboffset = RadioSetting("vfo.b.offset",
1471
                                  "VFO B offset (0.00-99.95)", val1b)
1472
        vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
1473
        work.append(vfoboffset)
1474

    
1475
        vfoatxp = RadioSetting("vfo.a.power", "VFO A power",
1476
                                RadioSettingValueList(LIST_TXP,LIST_TXP[
1477
                                    _mem.vfo.a.power]))
1478
        work.append(vfoatxp)
1479

    
1480
        vfobtxp = RadioSetting("vfo.b.power", "VFO B power",
1481
                                RadioSettingValueList(LIST_TXP,LIST_TXP[
1482
                                    _mem.vfo.b.power]))
1483
        work.append(vfobtxp)
1484

    
1485
        vfoawide = RadioSetting("vfo.a.wide", "VFO A bandwidth",
1486
                                RadioSettingValueList(LIST_WIDE,LIST_WIDE[
1487
                                    _mem.vfo.a.wide]))
1488
        work.append(vfoawide)
1489

    
1490
        vfobwide = RadioSetting("vfo.b.wide", "VFO B bandwidth",
1491
                                RadioSettingValueList(LIST_WIDE,LIST_WIDE[
1492
                                    _mem.vfo.b.wide]))
1493
        work.append(vfobwide)
1494

    
1495
        vfoastep = RadioSetting("vfo.a.step", "VFO A step",
1496
                                RadioSettingValueList(LIST_STEP,LIST_STEP[
1497
                                    _mem.vfo.a.step]))
1498
        work.append(vfoastep)
1499

    
1500
        vfobstep = RadioSetting("vfo.b.step", "VFO B step",
1501
                                RadioSettingValueList(LIST_STEP,LIST_STEP[
1502
                                    _mem.vfo.b.step]))
1503
        work.append(vfobstep)
1504

    
1505
        vfoaoptsig = RadioSetting("vfo.a.optsig", "VFO A optional signal",
1506
                                  RadioSettingValueList(OPTSIG_LIST,
1507
                                      OPTSIG_LIST[_mem.vfo.a.optsig]))
1508
        work.append(vfoaoptsig)
1509

    
1510
        vfoboptsig = RadioSetting("vfo.b.optsig", "VFO B optional signal",
1511
                                  RadioSettingValueList(OPTSIG_LIST,
1512
                                      OPTSIG_LIST[_mem.vfo.b.optsig]))
1513
        work.append(vfoboptsig)
1514

    
1515
        vfoaspmute = RadioSetting("vfo.a.spmute", "VFO A speaker mute",
1516
                                  RadioSettingValueList(SPMUTE_LIST,
1517
                                      SPMUTE_LIST[_mem.vfo.a.spmute]))
1518
        work.append(vfoaspmute)
1519

    
1520
        vfobspmute = RadioSetting("vfo.b.spmute", "VFO B speaker mute",
1521
                                  RadioSettingValueList(SPMUTE_LIST,
1522
                                      SPMUTE_LIST[_mem.vfo.b.spmute]))
1523
        work.append(vfobspmute)
1524

    
1525
        vfoascr = RadioSetting("vfo.a.scramble", "VFO A scramble",
1526
                               RadioSettingValueBoolean(_mem.vfo.a.scramble))
1527
        work.append(vfoascr)
1528

    
1529
        vfobscr = RadioSetting("vfo.b.scramble", "VFO B scramble",
1530
                               RadioSettingValueBoolean(_mem.vfo.b.scramble))
1531
        work.append(vfobscr)
1532

    
1533
        vfoascode = RadioSetting("vfo.a.scode", "VFO A PTT-ID",
1534
                                 RadioSettingValueList(PTTIDCODE_LIST,
1535
                                     PTTIDCODE_LIST[_mem.vfo.a.scode]))
1536
        work.append(vfoascode)
1537

    
1538
        vfobscode = RadioSetting("vfo.b.scode", "VFO B PTT-ID",
1539
                                 RadioSettingValueList(PTTIDCODE_LIST,
1540
                                     PTTIDCODE_LIST[_mem.vfo.b.scode]))
1541
        work.append(vfobscode)
1542

    
1543
        pttid = RadioSetting("settings.pttid", "PTT ID",
1544
                             RadioSettingValueList(PTTID_LIST,
1545
                                 PTTID_LIST[_mem.settings.pttid]))
1546
        work.append(pttid)
1547

    
1548
        return top
1549

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

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

    
1589
    @classmethod
1590
    def match_model(cls, filedata, filename):
1591
        match_size = False
1592
        match_model = False
1593

    
1594
        # testing the file data size
1595
        if len(filedata) == MEM_SIZE:
1596
            match_size = True
1597

    
1598
        # testing the firmware model fingerprint
1599
        match_model = model_match(cls, filedata)
1600

    
1601
        if match_size and match_model:
1602
            return True
1603
        else:
1604
            return False
1605

    
1606

    
1607
# Declaring Aliases (Clones of the real radios)
1608
class JT2705M(chirp_common.Alias):
1609
    VENDOR = "Jetstream"
1610
    MODEL = "JT2705M"
1611

    
1612

    
1613
class JT6188Mini(chirp_common.Alias):
1614
    VENDOR = "Juentai"
1615
    MODEL = "JT-6188 Mini"
1616

    
1617

    
1618
class JT6188Plus(chirp_common.Alias):
1619
    VENDOR = "Juentai"
1620
    MODEL = "JT-6188 Plus"
1621

    
1622

    
1623
class SSGT890(chirp_common.Alias):
1624
    VENDOR = "Sainsonic"
1625
    MODEL = "GT-890"
1626

    
1627

    
1628
class ZastoneMP300(chirp_common.Alias):
1629
    VENDOR = "Zastone"
1630
    MODEL = "MP-300"
1631

    
1632

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

    
1643

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

    
1655

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

    
1666

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

    
1677

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

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

    
1709

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

    
1725

    
1726
@directory.register
1727
class LT588UV(BTech):
1728
    """LUITON LT-588UV"""
1729
    VENDOR = "LUITON"
1730
    MODEL = "LT-588UV"
1731
    _vhf_range = (136000000, 175000000)
1732
    _uhf_range = (400000000, 481000000)
1733
    _magic = MSTRING_KT8900
1734
    _fileid = [LT588UV_fp, ]
(11-11/13)