Project

General

Profile

Bug #8473 » uv5r_test.py

Tests for "radio version" with 14 spaces - Jim Unroe, 11/24/2020 03:05 PM

 
1
# Copyright 2012 Dan Smith <dsmith@danplanet.com>
2
#
3
# This program is free software: you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation, either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
15

    
16
import struct
17
import time
18
import os
19
import logging
20

    
21
from chirp import chirp_common, errors, util, directory, memmap
22
from chirp import bitwise
23
from chirp.settings import RadioSetting, RadioSettingGroup, \
24
    RadioSettingValueInteger, RadioSettingValueList, \
25
    RadioSettingValueBoolean, RadioSettingValueString, \
26
    RadioSettingValueFloat, InvalidValueError, RadioSettings
27
from textwrap import dedent
28

    
29
LOG = logging.getLogger(__name__)
30

    
31
MEM_FORMAT = """
32
#seekto 0x0008;
33
struct {
34
  lbcd rxfreq[4];
35
  lbcd txfreq[4];
36
  ul16 rxtone;
37
  ul16 txtone;
38
  u8 unused1:3,
39
     isuhf:1,
40
     scode:4;
41
  u8 unknown1:7,
42
     txtoneicon:1;
43
  u8 mailicon:3,
44
     unknown2:3,
45
     lowpower:2;
46
  u8 unknown3:1,
47
     wide:1,
48
     unknown4:2,
49
     bcl:1,
50
     scan:1,
51
     pttid:2;
52
} memory[128];
53

    
54
#seekto 0x0B08;
55
struct {
56
  u8 code[5];
57
  u8 unused[11];
58
} pttid[15];
59

    
60
#seekto 0x0C88;
61
struct {
62
  u8 code222[3];
63
  u8 unused222[2];
64
  u8 code333[3];
65
  u8 unused333[2];
66
  u8 alarmcode[3];
67
  u8 unused119[2];
68
  u8 unknown1;
69
  u8 code555[3];
70
  u8 unused555[2];
71
  u8 code666[3];
72
  u8 unused666[2];
73
  u8 code777[3];
74
  u8 unused777[2];
75
  u8 unknown2;
76
  u8 code60606[5];
77
  u8 code70707[5];
78
  u8 code[5];
79
  u8 unused1:6,
80
     aniid:2;
81
  u8 unknown[2];
82
  u8 dtmfon;
83
  u8 dtmfoff;
84
} ani;
85

    
86
#seekto 0x0E28;
87
struct {
88
  u8 squelch;
89
  u8 step;
90
  u8 unknown1;
91
  u8 save;
92
  u8 vox;
93
  u8 unknown2;
94
  u8 abr;
95
  u8 tdr;
96
  u8 beep;
97
  u8 timeout;
98
  u8 unknown3[4];
99
  u8 voice;
100
  u8 unknown4;
101
  u8 dtmfst;
102
  u8 unknown5;
103
  u8 unknown12:6,
104
     screv:2;
105
  u8 pttid;
106
  u8 pttlt;
107
  u8 mdfa;
108
  u8 mdfb;
109
  u8 bcl;
110
  u8 autolk; // NOTE: The UV-6 calls this byte voxenable, but the UV-5R
111
             // calls it autolk. Since this is a minor difference, it will
112
             // be referred to by the wrong name for the UV-6.
113
  u8 sftd;
114
  u8 unknown6[3];
115
  u8 wtled;
116
  u8 rxled;
117
  u8 txled;
118
  u8 almod;
119
  u8 band;
120
  u8 tdrab;
121
  u8 ste;
122
  u8 rpste;
123
  u8 rptrl;
124
  u8 ponmsg;
125
  u8 roger;
126
  u8 rogerrx;
127
  u8 tdrch; // NOTE: The UV-82HP calls this byte rtone, but the UV-6
128
            // calls it tdrch. Since this is a minor difference, it will
129
            // be referred to by the wrong name for the UV-82HP.
130
  u8 displayab:1,
131
     unknown1:2,
132
     fmradio:1,
133
     alarm:1,
134
     unknown2:1,
135
     reset:1,
136
     menu:1;
137
  u8 unknown1:6,
138
     singleptt:1,
139
     vfomrlock:1;
140
  u8 workmode;
141
  u8 keylock;
142
} settings;
143

    
144
#seekto 0x0E7E;
145
struct {
146
  u8 unused1:1,
147
     mrcha:7;
148
  u8 unused2:1,
149
     mrchb:7;
150
} wmchannel;
151

    
152
#seekto 0x0F10;
153
struct {
154
  u8 freq[8];
155
  u8 offset[6];
156
  ul16 rxtone;
157
  ul16 txtone;
158
  u8 unused1:7,
159
     band:1;
160
  u8 unknown3;
161
  u8 unused2:2,
162
     sftd:2,
163
     scode:4;
164
  u8 unknown4;
165
  u8 unused3:1
166
     step:3,
167
     unused4:4;
168
  u8 txpower:1,
169
     widenarr:1,
170
     unknown5:4,
171
     txpower3:2;
172
} vfoa;
173

    
174
#seekto 0x0F30;
175
struct {
176
  u8 freq[8];
177
  u8 offset[6];
178
  ul16 rxtone;
179
  ul16 txtone;
180
  u8 unused1:7,
181
     band:1;
182
  u8 unknown3;
183
  u8 unused2:2,
184
     sftd:2,
185
     scode:4;
186
  u8 unknown4;
187
  u8 unused3:1
188
     step:3,
189
     unused4:4;
190
  u8 txpower:1,
191
     widenarr:1,
192
     unknown5:4,
193
     txpower3:2;
194
} vfob;
195

    
196
#seekto 0x0F56;
197
u16 fm_presets;
198

    
199
#seekto 0x1008;
200
struct {
201
  char name[7];
202
  u8 unknown2[9];
203
} names[128];
204

    
205
#seekto 0x1818;
206
struct {
207
  char line1[7];
208
  char line2[7];
209
} sixpoweron_msg;
210

    
211
#seekto 0x%04X;
212
struct {
213
  char line1[7];
214
  char line2[7];
215
} poweron_msg;
216

    
217
#seekto 0x1838;
218
struct {
219
  char line1[7];
220
  char line2[7];
221
} firmware_msg;
222

    
223
struct limit {
224
  u8 enable;
225
  bbcd lower[2];
226
  bbcd upper[2];
227
};
228

    
229
#seekto 0x1908;
230
struct {
231
  struct limit vhf;
232
  struct limit uhf;
233
} limits_new;
234

    
235
#seekto 0x1910;
236
struct {
237
  u8 unknown1[2];
238
  struct limit vhf;
239
  u8 unknown2;
240
  u8 unknown3[8];
241
  u8 unknown4[2];
242
  struct limit uhf;
243
} limits_old;
244

    
245
struct squelch {
246
  u8 sql0;
247
  u8 sql1;
248
  u8 sql2;
249
  u8 sql3;
250
  u8 sql4;
251
  u8 sql5;
252
  u8 sql6;
253
  u8 sql7;
254
  u8 sql8;
255
  u8 sql9;
256
};
257

    
258
#seekto 0x18A8;
259
struct {
260
  struct squelch vhf;
261
  u8 unknown1[6];
262
  u8 unknown2[16];
263
  struct squelch uhf;
264
} squelch_new;
265

    
266
#seekto 0x18E8;
267
struct {
268
  struct squelch vhf;
269
  u8 unknown[6];
270
  struct squelch uhf;
271
} squelch_old;
272

    
273
"""
274

    
275
# 0x1EC0 - 0x2000
276

    
277
vhf_220_radio = "\x02"
278

    
279
BASETYPE_UV5R = ["BFS", "BFB", "N5R-2", "N5R2", "N5RV", "BTS", "D5R2", "B5R2"]
280
BASETYPE_F11 = ["USA"]
281
BASETYPE_UV82 = ["US2S2", "B82S", "BF82", "N82-2", "N822"]
282
BASETYPE_BJ55 = ["BJ55"]  # needed for for the Baojie UV-55 in bjuv55.py
283
BASETYPE_UV6 = ["BF1", "UV6"]
284
BASETYPE_KT980HP = ["BFP3V3 B"]
285
BASETYPE_F8HP = ["BFP3V3 F", "N5R-3", "N5R3", "F5R3", "BFT", "N5RV"]
286
BASETYPE_UV82HP = ["N82-3", "N823", "N5R2"]
287
BASETYPE_UV82X3 = ["HN5RV01"]
288
BASETYPE_LIST = BASETYPE_UV5R + BASETYPE_F11 + BASETYPE_UV82 + \
289
    BASETYPE_BJ55 + BASETYPE_UV6 + BASETYPE_KT980HP + \
290
    BASETYPE_F8HP + BASETYPE_UV82HP + BASETYPE_UV82X3
291

    
292
AB_LIST = ["A", "B"]
293
ALMOD_LIST = ["Site", "Tone", "Code"]
294
BANDWIDTH_LIST = ["Wide", "Narrow"]
295
COLOR_LIST = ["Off", "Blue", "Orange", "Purple"]
296
DTMFSPEED_LIST = ["%s ms" % x for x in range(50, 2010, 10)]
297
DTMFST_LIST = ["OFF", "DT-ST", "ANI-ST", "DT+ANI"]
298
MODE_LIST = ["Channel", "Name", "Frequency"]
299
PONMSG_LIST = ["Full", "Message"]
300
PTTID_LIST = ["Off", "BOT", "EOT", "Both"]
301
PTTIDCODE_LIST = ["%s" % x for x in range(1, 16)]
302
RTONE_LIST = ["1000 Hz", "1450 Hz", "1750 Hz", "2100Hz"]
303
RESUME_LIST = ["TO", "CO", "SE"]
304
ROGERRX_LIST = ["Off"] + AB_LIST
305
RPSTE_LIST = ["OFF"] + ["%s" % x for x in range(1, 11)]
306
SAVE_LIST = ["Off", "1:1", "1:2", "1:3", "1:4"]
307
SCODE_LIST = ["%s" % x for x in range(1, 16)]
308
SHIFTD_LIST = ["Off", "+", "-"]
309
STEDELAY_LIST = ["OFF"] + ["%s ms" % x for x in range(100, 1100, 100)]
310
STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 25.0]
311
STEP_LIST = [str(x) for x in STEPS]
312
STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 20.0, 25.0, 50.0]
313
STEP291_LIST = [str(x) for x in STEPS]
314
TDRAB_LIST = ["Off"] + AB_LIST
315
TDRCH_LIST = ["CH%s" % x for x in range(1, 129)]
316
TIMEOUT_LIST = ["%s sec" % x for x in range(15, 615, 15)]
317
TXPOWER_LIST = ["High", "Low"]
318
TXPOWER3_LIST = ["High", "Mid", "Low"]
319
VOICE_LIST = ["Off", "English", "Chinese"]
320
VOX_LIST = ["OFF"] + ["%s" % x for x in range(1, 11)]
321
WORKMODE_LIST = ["Frequency", "Channel"]
322

    
323
SETTING_LISTS = {
324
    "almod": ALMOD_LIST,
325
    "aniid": PTTID_LIST,
326
    "displayab": AB_LIST,
327
    "dtmfst": DTMFST_LIST,
328
    "dtmfspeed": DTMFSPEED_LIST,
329
    "mdfa": MODE_LIST,
330
    "mdfb": MODE_LIST,
331
    "ponmsg": PONMSG_LIST,
332
    "pttid": PTTID_LIST,
333
    "rtone": RTONE_LIST,
334
    "rogerrx": ROGERRX_LIST,
335
    "rpste": RPSTE_LIST,
336
    "rxled": COLOR_LIST,
337
    "save": SAVE_LIST,
338
    "scode": PTTIDCODE_LIST,
339
    "screv": RESUME_LIST,
340
    "sftd": SHIFTD_LIST,
341
    "stedelay": STEDELAY_LIST,
342
    "step": STEP_LIST,
343
    "step291": STEP291_LIST,
344
    "tdrab": TDRAB_LIST,
345
    "tdrch": TDRCH_LIST,
346
    "timeout": TIMEOUT_LIST,
347
    "txled": COLOR_LIST,
348
    "txpower": TXPOWER_LIST,
349
    "txpower3": TXPOWER3_LIST,
350
    "voice": VOICE_LIST,
351
    "vox": VOX_LIST,
352
    "widenarr": BANDWIDTH_LIST,
353
    "workmode": WORKMODE_LIST,
354
    "wtled": COLOR_LIST
355
}
356

    
357

    
358
def _do_status(radio, block):
359
    status = chirp_common.Status()
360
    status.msg = "Cloning"
361
    status.cur = block
362
    status.max = radio.get_memsize()
363
    radio.status_fn(status)
364

    
365
UV5R_MODEL_ORIG = "\x50\xBB\xFF\x01\x25\x98\x4D"
366
UV5R_MODEL_291 = "\x50\xBB\xFF\x20\x12\x07\x25"
367
UV5R_MODEL_F11 = "\x50\xBB\xFF\x13\xA1\x11\xDD"
368
UV5R_MODEL_UV82 = "\x50\xBB\xFF\x20\x13\x01\x05"
369
UV5R_MODEL_UV6 = "\x50\xBB\xFF\x20\x12\x08\x23"
370
UV5R_MODEL_UV6_ORIG = "\x50\xBB\xFF\x12\x03\x98\x4D"
371
UV5R_MODEL_A58 = "\x50\xBB\xFF\x20\x14\x04\x13"
372

    
373

    
374
def _upper_band_from_data(data):
375
    return data[0x03:0x04]
376

    
377

    
378
def _upper_band_from_image(radio):
379
    return _upper_band_from_data(radio.get_mmap())
380

    
381

    
382
def _firmware_version_from_data(data, version_start, version_stop):
383
    version_tag = data[version_start:version_stop]
384
    return version_tag
385

    
386

    
387
def _firmware_version_from_image(radio):
388
    version = _firmware_version_from_data(radio.get_mmap(),
389
                                          radio._fw_ver_file_start,
390
                                          radio._fw_ver_file_stop)
391
    LOG.debug("_firmware_version_from_image: " + util.hexprint(version))
392
    return version
393

    
394

    
395
def _do_ident(radio, magic, secondack=True):
396
    serial = radio.pipe
397
    serial.timeout = 1
398

    
399
    LOG.info("Sending Magic: %s" % util.hexprint(magic))
400
    for byte in magic:
401
        serial.write(byte)
402
        time.sleep(0.01)
403
    ack = serial.read(1)
404

    
405
    if ack != "\x06":
406
        if ack:
407
            LOG.debug(repr(ack))
408
        raise errors.RadioError("Radio did not respond")
409

    
410
    serial.write("\x02")
411

    
412
    # Until recently, the "ident" returned by the radios supported by this
413
    # driver have always been 8 bytes long. The image sturcture is the 8 byte
414
    # "ident" followed by the downloaded memory data. So all of the settings
415
    # structures are offset by 8 bytes. The ident returned from a UV-6 radio
416
    # can be 8 bytes (original model) or now 12 bytes.
417
    #
418
    # To accomodate this, the "ident" is now read one byte at a time until the
419
    # last byte ("\xdd") is encountered. The bytes containing the value "\x01"
420
    # are discarded to shrink the "ident" length down to 8 bytes to keep the
421
    # image data aligned with the existing settings structures.
422

    
423
    # Ok, get the response
424
    response = ""
425
    for i in range(1, 13):
426
        byte = serial.read(1)
427
        response += byte
428
        # stop reading once the last byte ("\xdd") is encountered
429
        if byte == "\xdd":
430
            break
431

    
432
    # check if response is OK
433
    if len(response) in [8, 12]:
434
        # DEBUG
435
        LOG.info("Valid response, got this:")
436
        LOG.debug(util.hexprint(response))
437
        if len(response) == 12:
438
            ident = response[0] + response[3] + response[5] + response[7:]
439
        else:
440
            ident = response
441
    else:
442
        # bad response
443
        msg = "Unexpected response, got this:"
444
        msg += util.hexprint(response)
445
        LOG.debug(msg)
446
        raise errors.RadioError("Unexpected response from radio.")
447

    
448
    if secondack:
449
        serial.write("\x06")
450
        ack = serial.read(1)
451
        if ack != "\x06":
452
            raise errors.RadioError("Radio refused clone")
453

    
454
    return ident
455

    
456

    
457
def _read_block(radio, start, size, first_command=False):
458
    msg = struct.pack(">BHB", ord("S"), start, size)
459
    radio.pipe.write(msg)
460

    
461
    if first_command is False:
462
        ack = radio.pipe.read(1)
463
        if ack != "\x06":
464
            raise errors.RadioError(
465
                "Radio refused to send second block 0x%04x" % start)
466

    
467
    answer = radio.pipe.read(4)
468
    if len(answer) != 4:
469
        raise errors.RadioError("Radio refused to send block 0x%04x" % start)
470

    
471
    cmd, addr, length = struct.unpack(">BHB", answer)
472
    if cmd != ord("X") or addr != start or length != size:
473
        LOG.error("Invalid answer for block 0x%04x:" % start)
474
        LOG.debug("CMD: %s  ADDR: %04x  SIZE: %02x" % (cmd, addr, length))
475
        raise errors.RadioError("Unknown response from radio")
476

    
477
    chunk = radio.pipe.read(0x40)
478
    if not chunk:
479
        raise errors.RadioError("Radio did not send block 0x%04x" % start)
480
    elif len(chunk) != size:
481
        LOG.error("Chunk length was 0x%04i" % len(chunk))
482
        raise errors.RadioError("Radio sent incomplete block 0x%04x" % start)
483

    
484
    radio.pipe.write("\x06")
485
    time.sleep(0.05)
486

    
487
    return chunk
488

    
489

    
490
def _get_radio_firmware_version(radio):
491
    if radio.MODEL == "BJ-UV55":
492
        block = _read_block(radio, 0x1FF0, 0x40, True)
493
        version = block[0:6]
494
    else:
495
        block1 = _read_block(radio, 0x1EC0, 0x40, True)
496
        block2 = _read_block(radio, 0x1F00, 0x40, False)
497
        block = block1 + block2
498
        version = block[48:62]
499
    return version
500

    
501

    
502
IDENT_BLACKLIST = {
503
    "\x50\x0D\x0C\x20\x16\x03\x28": "Radio identifies as BTECH UV-5X3",
504
}
505

    
506

    
507
def _ident_radio(radio):
508
    for magic in radio._idents:
509
        error = None
510
        try:
511
            data = _do_ident(radio, magic)
512
            return data
513
        except errors.RadioError, e:
514
            LOG.error("uv5r._ident_radio: %s", e)
515
            error = e
516
            time.sleep(2)
517

    
518
    for magic, reason in IDENT_BLACKLIST.items():
519
        try:
520
            _do_ident(radio, magic, secondack=False)
521
        except errors.RadioError as e:
522
            # No match, try the next one
523
            continue
524

    
525
        # If we got here, it means we identified the radio as
526
        # something other than one of our valid idents. Warn
527
        # the user so they can do the right thing.
528
        LOG.warning(('Identified radio as a blacklisted model '
529
                     '(details: %s)') % reason)
530
        raise errors.RadioError(('%s. Please choose the proper vendor/'
531
                                 'model and try again.') % reason)
532

    
533
    if error:
534
        raise error
535
    raise errors.RadioError("Radio did not respond")
536

    
537

    
538
def _do_download(radio):
539
    data = _ident_radio(radio)
540

    
541
    radio_version = _get_radio_firmware_version(radio)
542
    LOG.info("Radio Version is %s" % repr(radio_version))
543

    
544
    if "HN5RV" in radio_version:
545
        # A radio with HN5RV firmware has been detected. It could be a
546
        # UV-5R style radio with HIGH/LOW power levels or it could be a
547
        # BF-F8HP style radio with HIGH/MID/LOW power levels.
548
        # We are going to count on the user to make the right choice and
549
        # then append that model type to the end of the image so it can
550
        # be properly detected when loaded.
551
        append_model = True
552
    elif "\xFF" * 7 in radio_version:
553
        # A radio UV-5R style radio that reports no firmware version has
554
        # been detected.
555
        # We are going to count on the user to make the right choice and
556
        # then append that model type to the end of the image so it can
557
        # be properly detected when loaded.
558
        append_model = True
559
    elif "\x20" * 14 in radio_version:
560
        # A radio UV-5R style radio that reports no firmware version has
561
        # been detected.
562
        # We are going to count on the user to make the right choice and
563
        # then append that model type to the end of the image so it can
564
        # be properly detected when loaded.
565
        append_model = True
566
    elif not any(type in radio_version for type in radio._basetype):
567
        # This radio can't be properly detected by parsing its firmware
568
        # version.
569
        raise errors.RadioError("Incorrect 'Model' selected.")
570
    else:
571
        # This radio can be properly detected by parsing its firmware version.
572
        # There is no need to append its model type to the end of the image.
573
        append_model = False
574

    
575
    # Main block
576
    LOG.debug("downloading main block...")
577
    for i in range(0, 0x1800, 0x40):
578
        data += _read_block(radio, i, 0x40, False)
579
        _do_status(radio, i)
580
    _do_status(radio, radio.get_memsize())
581
    LOG.debug("done.")
582
    if radio._aux_block:
583
        LOG.debug("downloading aux block...")
584
        # Auxiliary block starts at 0x1ECO (?)
585
        for i in range(0x1EC0, 0x2000, 0x40):
586
            data += _read_block(radio, i, 0x40, False)
587

    
588
    if append_model:
589
        data += radio.MODEL.ljust(8)
590

    
591
    LOG.debug("done.")
592
    return memmap.MemoryMap(data)
593

    
594

    
595
def _send_block(radio, addr, data):
596
    msg = struct.pack(">BHB", ord("X"), addr, len(data))
597
    radio.pipe.write(msg + data)
598
    time.sleep(0.05)
599

    
600
    ack = radio.pipe.read(1)
601
    if ack != "\x06":
602
        raise errors.RadioError("Radio refused to accept block 0x%04x" % addr)
603

    
604

    
605
def _do_upload(radio):
606
    ident = _ident_radio(radio)
607
    radio_upper_band = ident[3:4]
608
    image_upper_band = _upper_band_from_image(radio)
609

    
610
    if image_upper_band == vhf_220_radio or radio_upper_band == vhf_220_radio:
611
        if image_upper_band != radio_upper_band:
612
            raise errors.RadioError("Image not supported by radio")
613

    
614
    image_version = _firmware_version_from_image(radio)
615
    radio_version = _get_radio_firmware_version(radio)
616
    LOG.info("Image Version is %s" % repr(image_version))
617
    LOG.info("Radio Version is %s" % repr(radio_version))
618

    
619
    # default ranges
620
    _ranges_main_default = [
621
        (0x0008, 0x0CF8),
622
        (0x0D08, 0x0DF8),
623
        (0x0E08, 0x1808)
624
        ]
625
    _ranges_aux_default = [
626
        (0x1EC0, 0x1EF0),
627
        ]
628

    
629
    # extra aux ranges
630
    _ranges_aux_extra = [
631
        (0x1F60, 0x1F70),
632
        (0x1F80, 0x1F90),
633
        (0x1FC0, 0x1FD0)
634
        ]
635

    
636
    if image_version == radio_version:
637
        image_matched_radio = True
638
        if image_version.startswith("HN5RV"):
639
            ranges_main = _ranges_main_default
640
            ranges_aux = _ranges_aux_default + _ranges_aux_extra
641
        elif image_version == 0xFF * 7:
642
            ranges_main = _ranges_main_default
643
            ranges_aux = _ranges_aux_default + _ranges_aux_extra
644
        else:
645
            ranges_main = radio._ranges_main
646
            ranges_aux = radio._ranges_aux
647
    elif any(type in radio_version for type in radio._basetype):
648
        image_matched_radio = False
649
        ranges_main = _ranges_main_default
650
        ranges_aux = _ranges_aux_default
651
    else:
652
        msg = ("The upload was stopped because the firmware "
653
               "version of the image (%s) does not match that "
654
               "of the radio (%s).")
655
        raise errors.RadioError(msg % (image_version, radio_version))
656

    
657
    if not radio._aux_block:
658
        image_matched_radio = True
659

    
660
    # Main block
661
    for start_addr, end_addr in ranges_main:
662
        for i in range(start_addr, end_addr, 0x10):
663
            _send_block(radio, i - 0x08, radio.get_mmap()[i:i + 0x10])
664
            _do_status(radio, i)
665
        _do_status(radio, radio.get_memsize())
666

    
667
    if len(radio.get_mmap().get_packed()) == 0x1808:
668
        LOG.info("Old image, not writing aux block")
669
        return  # Old image, no aux block
670

    
671
    # Auxiliary block at radio address 0x1EC0, our offset 0x1808
672
    for start_addr, end_addr in ranges_aux:
673
        for i in range(start_addr, end_addr, 0x10):
674
            addr = 0x1808 + (i - 0x1EC0)
675
            _send_block(radio, i, radio.get_mmap()[addr:addr + 0x10])
676

    
677
    if not image_matched_radio:
678
        msg = ("Upload finished, but the 'Other Settings' "
679
               "could not be sent because the firmware "
680
               "version of the image (%s) does not match "
681
               "that of the radio (%s).")
682
        raise errors.RadioError(msg % (image_version, radio_version))
683

    
684
UV5R_POWER_LEVELS = [chirp_common.PowerLevel("High", watts=4.00),
685
                     chirp_common.PowerLevel("Low",  watts=1.00)]
686

    
687
UV5R_POWER_LEVELS3 = [chirp_common.PowerLevel("High", watts=8.00),
688
                      chirp_common.PowerLevel("Med",  watts=4.00),
689
                      chirp_common.PowerLevel("Low",  watts=1.00)]
690

    
691
UV5R_DTCS = sorted(chirp_common.DTCS_CODES + [645])
692

    
693
UV5R_CHARSET = chirp_common.CHARSET_UPPER_NUMERIC + \
694
    "!@#$%^&*()+-=[]:\";'<>?,./"
695

    
696

    
697
def model_match(cls, data):
698
    """Match the opened/downloaded image to the correct version"""
699

    
700
    if len(data) == 0x1950:
701
        rid = data[0x1948:0x1950]
702
        return rid.startswith(cls.MODEL)
703
    elif len(data) == 0x1948:
704
        rid = data[cls._fw_ver_file_start:cls._fw_ver_file_stop]
705
        if any(type in rid for type in cls._basetype):
706
            return True
707
    else:
708
        return False
709

    
710

    
711
class BaofengUV5R(chirp_common.CloneModeRadio):
712

    
713
    """Baofeng UV-5R"""
714
    VENDOR = "Baofeng"
715
    MODEL = "UV-5R"
716
    BAUD_RATE = 9600
717

    
718
    _memsize = 0x1808
719
    _basetype = BASETYPE_UV5R
720
    _idents = [UV5R_MODEL_291,
721
               UV5R_MODEL_ORIG
722
               ]
723
    _vhf_range = (136000000, 174000000)
724
    _220_range = (220000000, 260000000)
725
    _uhf_range = (400000000, 520000000)
726
    _aux_block = True
727
    _tri_power = False
728
    _mem_params = (0x1828  # poweron_msg offset
729
                   )
730
    # offset of fw version in image file
731
    _fw_ver_file_start = 0x1838
732
    _fw_ver_file_stop = 0x1846
733

    
734
    _ranges_main = [
735
                    (0x0008, 0x1808),
736
                   ]
737
    _ranges_aux = [
738
                   (0x1EC0, 0x2000),
739
                  ]
740
    _valid_chars = UV5R_CHARSET
741

    
742
    @classmethod
743
    def get_prompts(cls):
744
        rp = chirp_common.RadioPrompts()
745
        rp.experimental = \
746
            ('Due to the fact that the manufacturer continues to '
747
             'release new versions of the firmware with obscure and '
748
             'hard-to-track changes, this driver may not work with '
749
             'your device. Thus far and to the best knowledge of the '
750
             'author, no UV-5R radios have been harmed by using CHIRP. '
751
             'However, proceed at your own risk!')
752
        rp.pre_download = _(dedent("""\
753
            1. Turn radio off.
754
            2. Connect cable to mic/spkr connector.
755
            3. Make sure connector is firmly connected.
756
            4. Turn radio on (volume may need to be set at 100%).
757
            5. Ensure that the radio is tuned to channel with no activity.
758
            6. Click OK to download image from device."""))
759
        rp.pre_upload = _(dedent("""\
760
            1. Turn radio off.
761
            2. Connect cable to mic/spkr connector.
762
            3. Make sure connector is firmly connected.
763
            4. Turn radio on (volume may need to be set at 100%).
764
            5. Ensure that the radio is tuned to channel with no activity.
765
            6. Click OK to upload image to device."""))
766
        return rp
767

    
768
    def get_features(self):
769
        rf = chirp_common.RadioFeatures()
770
        rf.has_settings = True
771
        rf.has_bank = False
772
        rf.has_cross = True
773
        rf.has_rx_dtcs = True
774
        rf.has_tuning_step = False
775
        rf.can_odd_split = True
776
        rf.valid_name_length = 7
777
        rf.valid_characters = self._valid_chars
778
        rf.valid_skips = ["", "S"]
779
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
780
        rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone",
781
                                "->Tone", "->DTCS", "DTCS->", "DTCS->DTCS"]
782
        rf.valid_power_levels = UV5R_POWER_LEVELS
783
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
784
        rf.valid_modes = ["FM", "NFM"]
785
        rf.valid_tuning_steps = STEPS
786

    
787
        normal_bands = [self._vhf_range, self._uhf_range]
788
        rax_bands = [self._vhf_range, self._220_range]
789

    
790
        if self._mmap is None:
791
            rf.valid_bands = [normal_bands[0], rax_bands[1], normal_bands[1]]
792
        elif not self._is_orig() and self._my_upper_band() == vhf_220_radio:
793
            rf.valid_bands = rax_bands
794
        else:
795
            rf.valid_bands = normal_bands
796
        rf.memory_bounds = (0, 127)
797
        return rf
798

    
799
    @classmethod
800
    def match_model(cls, filedata, filename):
801
        match_size = False
802
        match_model = False
803
        if len(filedata) in [0x1808, 0x1948, 0x1950]:
804
            match_size = True
805
        match_model = model_match(cls, filedata)
806

    
807
        if match_size and match_model:
808
            return True
809
        else:
810
            return False
811

    
812
    def process_mmap(self):
813
        self._memobj = bitwise.parse(MEM_FORMAT % self._mem_params, self._mmap)
814

    
815
    def sync_in(self):
816
        try:
817
            self._mmap = _do_download(self)
818
        except errors.RadioError:
819
            raise
820
        except Exception, e:
821
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
822
        self.process_mmap()
823

    
824
    def sync_out(self):
825
        try:
826
            _do_upload(self)
827
        except errors.RadioError:
828
            raise
829
        except Exception, e:
830
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
831

    
832
    def get_raw_memory(self, number):
833
        return repr(self._memobj.memory[number])
834

    
835
    def _is_txinh(self, _mem):
836
        raw_tx = ""
837
        for i in range(0, 4):
838
            raw_tx += _mem.txfreq[i].get_raw()
839
        return raw_tx == "\xFF\xFF\xFF\xFF"
840

    
841
    def _get_mem(self, number):
842
        return self._memobj.memory[number]
843

    
844
    def _get_nam(self, number):
845
        return self._memobj.names[number]
846

    
847
    def get_memory(self, number):
848
        _mem = self._get_mem(number)
849
        _nam = self._get_nam(number)
850

    
851
        mem = chirp_common.Memory()
852
        mem.number = number
853

    
854
        if _mem.get_raw()[0] == "\xff":
855
            mem.empty = True
856
            return mem
857

    
858
        mem.freq = int(_mem.rxfreq) * 10
859

    
860
        if self._is_txinh(_mem):
861
            mem.duplex = "off"
862
            mem.offset = 0
863
        elif int(_mem.rxfreq) == int(_mem.txfreq):
864
            mem.duplex = ""
865
            mem.offset = 0
866
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 70000000:
867
            mem.duplex = "split"
868
            mem.offset = int(_mem.txfreq) * 10
869
        else:
870
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
871
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
872

    
873
        for char in _nam.name:
874
            if str(char) == "\xFF":
875
                char = " "  # The UV-5R software may have 0xFF mid-name
876
            mem.name += str(char)
877
        mem.name = mem.name.rstrip()
878

    
879
        dtcs_pol = ["N", "N"]
880

    
881
        if _mem.txtone in [0, 0xFFFF]:
882
            txmode = ""
883
        elif _mem.txtone >= 0x0258:
884
            txmode = "Tone"
885
            mem.rtone = int(_mem.txtone) / 10.0
886
        elif _mem.txtone <= 0x0258:
887
            txmode = "DTCS"
888
            if _mem.txtone > 0x69:
889
                index = _mem.txtone - 0x6A
890
                dtcs_pol[0] = "R"
891
            else:
892
                index = _mem.txtone - 1
893
            mem.dtcs = UV5R_DTCS[index]
894
        else:
895
            LOG.warn("Bug: txtone is %04x" % _mem.txtone)
896

    
897
        if _mem.rxtone in [0, 0xFFFF]:
898
            rxmode = ""
899
        elif _mem.rxtone >= 0x0258:
900
            rxmode = "Tone"
901
            mem.ctone = int(_mem.rxtone) / 10.0
902
        elif _mem.rxtone <= 0x0258:
903
            rxmode = "DTCS"
904
            if _mem.rxtone >= 0x6A:
905
                index = _mem.rxtone - 0x6A
906
                dtcs_pol[1] = "R"
907
            else:
908
                index = _mem.rxtone - 1
909
            mem.rx_dtcs = UV5R_DTCS[index]
910
        else:
911
            LOG.warn("Bug: rxtone is %04x" % _mem.rxtone)
912

    
913
        if txmode == "Tone" and not rxmode:
914
            mem.tmode = "Tone"
915
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
916
            mem.tmode = "TSQL"
917
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
918
            mem.tmode = "DTCS"
919
        elif rxmode or txmode:
920
            mem.tmode = "Cross"
921
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
922

    
923
        mem.dtcs_polarity = "".join(dtcs_pol)
924

    
925
        if not _mem.scan:
926
            mem.skip = "S"
927

    
928
        if self._tri_power:
929
            levels = UV5R_POWER_LEVELS3
930
        else:
931
            levels = UV5R_POWER_LEVELS
932
        try:
933
            mem.power = levels[_mem.lowpower]
934
        except IndexError:
935
            LOG.error("Radio reported invalid power level %s (in %s)" %
936
                      (_mem.lowpower, levels))
937
            mem.power = levels[0]
938

    
939
        mem.mode = _mem.wide and "FM" or "NFM"
940

    
941
        mem.extra = RadioSettingGroup("Extra", "extra")
942

    
943
        rs = RadioSetting("bcl", "BCL",
944
                          RadioSettingValueBoolean(_mem.bcl))
945
        mem.extra.append(rs)
946

    
947
        rs = RadioSetting("pttid", "PTT ID",
948
                          RadioSettingValueList(PTTID_LIST,
949
                                                PTTID_LIST[_mem.pttid]))
950
        mem.extra.append(rs)
951

    
952
        rs = RadioSetting("scode", "PTT ID Code",
953
                          RadioSettingValueList(PTTIDCODE_LIST,
954
                                                PTTIDCODE_LIST[_mem.scode]))
955
        mem.extra.append(rs)
956

    
957
        return mem
958

    
959
    def _set_mem(self, number):
960
        return self._memobj.memory[number]
961

    
962
    def _set_nam(self, number):
963
        return self._memobj.names[number]
964

    
965
    def set_memory(self, mem):
966
        _mem = self._get_mem(mem.number)
967
        _nam = self._get_nam(mem.number)
968

    
969
        if mem.empty:
970
            _mem.set_raw("\xff" * 16)
971
            _nam.set_raw("\xff" * 16)
972
            return
973

    
974
        was_empty = False
975
        # same method as used in get_memory to find
976
        # out whether a raw memory is empty
977
        if _mem.get_raw()[0] == "\xff":
978
            was_empty = True
979
            LOG.debug("UV5R: this mem was empty")
980
        else:
981
            # memorize old extra-values before erasing the whole memory
982
            # used to solve issue 4121
983
            LOG.debug("mem was not empty, memorize extra-settings")
984
            prev_bcl = _mem.bcl.get_value()
985
            prev_scode = _mem.scode.get_value()
986
            prev_pttid = _mem.pttid.get_value()
987

    
988
        _mem.set_raw("\x00" * 16)
989

    
990
        _mem.rxfreq = mem.freq / 10
991

    
992
        if mem.duplex == "off":
993
            for i in range(0, 4):
994
                _mem.txfreq[i].set_raw("\xFF")
995
        elif mem.duplex == "split":
996
            _mem.txfreq = mem.offset / 10
997
        elif mem.duplex == "+":
998
            _mem.txfreq = (mem.freq + mem.offset) / 10
999
        elif mem.duplex == "-":
1000
            _mem.txfreq = (mem.freq - mem.offset) / 10
1001
        else:
1002
            _mem.txfreq = mem.freq / 10
1003

    
1004
        _namelength = self.get_features().valid_name_length
1005
        for i in range(_namelength):
1006
            try:
1007
                _nam.name[i] = mem.name[i]
1008
            except IndexError:
1009
                _nam.name[i] = "\xFF"
1010

    
1011
        rxmode = txmode = ""
1012
        if mem.tmode == "Tone":
1013
            _mem.txtone = int(mem.rtone * 10)
1014
            _mem.rxtone = 0
1015
        elif mem.tmode == "TSQL":
1016
            _mem.txtone = int(mem.ctone * 10)
1017
            _mem.rxtone = int(mem.ctone * 10)
1018
        elif mem.tmode == "DTCS":
1019
            rxmode = txmode = "DTCS"
1020
            _mem.txtone = UV5R_DTCS.index(mem.dtcs) + 1
1021
            _mem.rxtone = UV5R_DTCS.index(mem.dtcs) + 1
1022
        elif mem.tmode == "Cross":
1023
            txmode, rxmode = mem.cross_mode.split("->", 1)
1024
            if txmode == "Tone":
1025
                _mem.txtone = int(mem.rtone * 10)
1026
            elif txmode == "DTCS":
1027
                _mem.txtone = UV5R_DTCS.index(mem.dtcs) + 1
1028
            else:
1029
                _mem.txtone = 0
1030
            if rxmode == "Tone":
1031
                _mem.rxtone = int(mem.ctone * 10)
1032
            elif rxmode == "DTCS":
1033
                _mem.rxtone = UV5R_DTCS.index(mem.rx_dtcs) + 1
1034
            else:
1035
                _mem.rxtone = 0
1036
        else:
1037
            _mem.rxtone = 0
1038
            _mem.txtone = 0
1039

    
1040
        if txmode == "DTCS" and mem.dtcs_polarity[0] == "R":
1041
            _mem.txtone += 0x69
1042
        if rxmode == "DTCS" and mem.dtcs_polarity[1] == "R":
1043
            _mem.rxtone += 0x69
1044

    
1045
        _mem.scan = mem.skip != "S"
1046
        _mem.wide = mem.mode == "FM"
1047

    
1048
        if mem.power:
1049
            if self._tri_power:
1050
                levels = [str(l) for l in UV5R_POWER_LEVELS3]
1051
                _mem.lowpower = levels.index(str(mem.power))
1052
            else:
1053
                _mem.lowpower = UV5R_POWER_LEVELS.index(mem.power)
1054
        else:
1055
            _mem.lowpower = 0
1056

    
1057
        if not was_empty:
1058
            # restoring old extra-settings (issue 4121
1059
            _mem.bcl.set_value(prev_bcl)
1060
            _mem.scode.set_value(prev_scode)
1061
            _mem.pttid.set_value(prev_pttid)
1062

    
1063
        for setting in mem.extra:
1064
            setattr(_mem, setting.get_name(), setting.value)
1065

    
1066
    def _is_orig(self):
1067
        version_tag = _firmware_version_from_image(self)
1068
        LOG.debug("@_is_orig, version_tag: %s", util.hexprint(version_tag))
1069
        try:
1070
            if 'BFB' in version_tag:
1071
                idx = version_tag.index("BFB") + 3
1072
                version = int(version_tag[idx:idx + 3])
1073
                return version < 291
1074
            return False
1075
        except:
1076
            pass
1077
        raise errors.RadioError("Unable to parse version string %s" %
1078
                                version_tag)
1079

    
1080
    def _my_version(self):
1081
        version_tag = _firmware_version_from_image(self)
1082
        if 'BFB' in version_tag:
1083
            idx = version_tag.index("BFB") + 3
1084
            return int(version_tag[idx:idx + 3])
1085

    
1086
        raise Exception("Unrecognized firmware version string")
1087

    
1088
    def _my_upper_band(self):
1089
        band_tag = _upper_band_from_image(self)
1090
        return band_tag
1091

    
1092
    def _get_settings(self):
1093
        _ani = self._memobj.ani
1094
        _fm_presets = self._memobj.fm_presets
1095
        _settings = self._memobj.settings
1096
        _squelch = self._memobj.squelch_new
1097
        _vfoa = self._memobj.vfoa
1098
        _vfob = self._memobj.vfob
1099
        _wmchannel = self._memobj.wmchannel
1100
        basic = RadioSettingGroup("basic", "Basic Settings")
1101
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
1102

    
1103
        group = RadioSettings(basic, advanced)
1104

    
1105
        rs = RadioSetting("squelch", "Carrier Squelch Level",
1106
                          RadioSettingValueInteger(0, 9, _settings.squelch))
1107
        basic.append(rs)
1108

    
1109
        rs = RadioSetting("save", "Battery Saver",
1110
                          RadioSettingValueList(
1111
                              SAVE_LIST, SAVE_LIST[_settings.save]))
1112
        basic.append(rs)
1113

    
1114
        rs = RadioSetting("vox", "VOX Sensitivity",
1115
                          RadioSettingValueList(
1116
                              VOX_LIST, VOX_LIST[_settings.vox]))
1117
        advanced.append(rs)
1118

    
1119
        if self.MODEL == "UV-6":
1120
            # NOTE: The UV-6 calls this byte voxenable, but the UV-5R calls it
1121
            # autolk. Since this is a minor difference, it will be referred to
1122
            # by the wrong name for the UV-6.
1123
            rs = RadioSetting("autolk", "Vox",
1124
                              RadioSettingValueBoolean(_settings.autolk))
1125
            advanced.append(rs)
1126

    
1127
        if self.MODEL != "UV-6":
1128
            rs = RadioSetting("abr", "Backlight Timeout",
1129
                              RadioSettingValueInteger(0, 24, _settings.abr))
1130
            basic.append(rs)
1131

    
1132
        rs = RadioSetting("tdr", "Dual Watch",
1133
                          RadioSettingValueBoolean(_settings.tdr))
1134
        advanced.append(rs)
1135

    
1136
        if self.MODEL == "UV-6":
1137
            rs = RadioSetting("tdrch", "Dual Watch Channel",
1138
                              RadioSettingValueList(
1139
                                  TDRCH_LIST, TDRCH_LIST[_settings.tdrch]))
1140
            advanced.append(rs)
1141

    
1142
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1143
                              RadioSettingValueBoolean(_settings.tdrab))
1144
            advanced.append(rs)
1145
        else:
1146
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1147
                              RadioSettingValueList(
1148
                                  TDRAB_LIST, TDRAB_LIST[_settings.tdrab]))
1149
            advanced.append(rs)
1150

    
1151
        if self.MODEL == "UV-6":
1152
            rs = RadioSetting("alarm", "Alarm Sound",
1153
                              RadioSettingValueBoolean(_settings.alarm))
1154
            advanced.append(rs)
1155

    
1156
        if _settings.almod > 0x02:
1157
            val = 0x01
1158
        else:
1159
            val = _settings.almod
1160
        rs = RadioSetting("almod", "Alarm Mode",
1161
                          RadioSettingValueList(
1162
                              ALMOD_LIST, ALMOD_LIST[val]))
1163
        advanced.append(rs)
1164

    
1165
        rs = RadioSetting("beep", "Beep",
1166
                          RadioSettingValueBoolean(_settings.beep))
1167
        basic.append(rs)
1168

    
1169
        rs = RadioSetting("timeout", "Timeout Timer",
1170
                          RadioSettingValueList(
1171
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
1172
        basic.append(rs)
1173

    
1174
        if self._is_orig() and self._my_version() < 251:
1175
            rs = RadioSetting("voice", "Voice",
1176
                              RadioSettingValueBoolean(_settings.voice))
1177
            advanced.append(rs)
1178
        else:
1179
            if self.MODEL != "TI-F8+":
1180
                rs = RadioSetting("voice", "Voice",
1181
                                  RadioSettingValueList(
1182
                                      VOICE_LIST, VOICE_LIST[_settings.voice]))
1183
                advanced.append(rs)
1184

    
1185
        rs = RadioSetting("screv", "Scan Resume",
1186
                          RadioSettingValueList(
1187
                              RESUME_LIST, RESUME_LIST[_settings.screv]))
1188
        advanced.append(rs)
1189

    
1190
        if self.MODEL != "UV-6":
1191
            rs = RadioSetting("mdfa", "Display Mode (A)",
1192
                              RadioSettingValueList(
1193
                                  MODE_LIST, MODE_LIST[_settings.mdfa]))
1194
            basic.append(rs)
1195

    
1196
            rs = RadioSetting("mdfb", "Display Mode (B)",
1197
                              RadioSettingValueList(
1198
                                  MODE_LIST, MODE_LIST[_settings.mdfb]))
1199
            basic.append(rs)
1200

    
1201
        rs = RadioSetting("bcl", "Busy Channel Lockout",
1202
                          RadioSettingValueBoolean(_settings.bcl))
1203
        advanced.append(rs)
1204

    
1205
        if self.MODEL != "UV-6":
1206
            rs = RadioSetting("autolk", "Automatic Key Lock",
1207
                              RadioSettingValueBoolean(_settings.autolk))
1208
            advanced.append(rs)
1209

    
1210
        rs = RadioSetting("fmradio", "Broadcast FM Radio",
1211
                          RadioSettingValueBoolean(_settings.fmradio))
1212
        advanced.append(rs)
1213

    
1214
        if self.MODEL != "UV-6":
1215
            rs = RadioSetting("wtled", "Standby LED Color",
1216
                              RadioSettingValueList(
1217
                                  COLOR_LIST, COLOR_LIST[_settings.wtled]))
1218
            basic.append(rs)
1219

    
1220
            rs = RadioSetting("rxled", "RX LED Color",
1221
                              RadioSettingValueList(
1222
                                  COLOR_LIST, COLOR_LIST[_settings.rxled]))
1223
            basic.append(rs)
1224

    
1225
            rs = RadioSetting("txled", "TX LED Color",
1226
                              RadioSettingValueList(
1227
                                  COLOR_LIST, COLOR_LIST[_settings.txled]))
1228
            basic.append(rs)
1229

    
1230
        if isinstance(self, BaofengUV82Radio):
1231
            rs = RadioSetting("roger", "Roger Beep (TX)",
1232
                              RadioSettingValueBoolean(_settings.roger))
1233
            basic.append(rs)
1234
            rs = RadioSetting("rogerrx", "Roger Beep (RX)",
1235
                              RadioSettingValueList(
1236
                                  ROGERRX_LIST,
1237
                                  ROGERRX_LIST[_settings.rogerrx]))
1238
            basic.append(rs)
1239
        else:
1240
            rs = RadioSetting("roger", "Roger Beep",
1241
                              RadioSettingValueBoolean(_settings.roger))
1242
            basic.append(rs)
1243

    
1244
        rs = RadioSetting("ste", "Squelch Tail Eliminate (HT to HT)",
1245
                          RadioSettingValueBoolean(_settings.ste))
1246
        advanced.append(rs)
1247

    
1248
        rs = RadioSetting("rpste", "Squelch Tail Eliminate (repeater)",
1249
                          RadioSettingValueList(
1250
                              RPSTE_LIST, RPSTE_LIST[_settings.rpste]))
1251
        advanced.append(rs)
1252

    
1253
        rs = RadioSetting("rptrl", "STE Repeater Delay",
1254
                          RadioSettingValueList(
1255
                              STEDELAY_LIST, STEDELAY_LIST[_settings.rptrl]))
1256
        advanced.append(rs)
1257

    
1258
        if self.MODEL != "UV-6":
1259
            rs = RadioSetting("reset", "RESET Menu",
1260
                              RadioSettingValueBoolean(_settings.reset))
1261
            advanced.append(rs)
1262

    
1263
            rs = RadioSetting("menu", "All Menus",
1264
                              RadioSettingValueBoolean(_settings.menu))
1265
            advanced.append(rs)
1266

    
1267
        if self.MODEL == "F-11":
1268
            # this is an F-11 only feature
1269
            rs = RadioSetting("vfomrlock", "VFO/MR Button",
1270
                              RadioSettingValueBoolean(_settings.vfomrlock))
1271
            advanced.append(rs)
1272

    
1273
        if isinstance(self, BaofengUV82Radio):
1274
            # this is a UV-82C only feature
1275
            rs = RadioSetting("vfomrlock", "VFO/MR Switching (UV-82C only)",
1276
                              RadioSettingValueBoolean(_settings.vfomrlock))
1277
            advanced.append(rs)
1278

    
1279
        if self.MODEL == "UV-82HP":
1280
            # this is a UV-82HP only feature
1281
            rs = RadioSetting(
1282
                "vfomrlock", "VFO/MR Switching (BTech UV-82HP only)",
1283
                RadioSettingValueBoolean(_settings.vfomrlock))
1284
            advanced.append(rs)
1285

    
1286
        if isinstance(self, BaofengUV82Radio):
1287
            # this is an UV-82C only feature
1288
            rs = RadioSetting("singleptt", "Single PTT (UV-82C only)",
1289
                              RadioSettingValueBoolean(_settings.singleptt))
1290
            advanced.append(rs)
1291

    
1292
        if self.MODEL == "UV-82HP":
1293
            # this is an UV-82HP only feature
1294
            rs = RadioSetting("singleptt", "Single PTT (BTech UV-82HP only)",
1295
                              RadioSettingValueBoolean(_settings.singleptt))
1296
            advanced.append(rs)
1297

    
1298
        if self.MODEL == "UV-82HP":
1299
            # this is an UV-82HP only feature
1300
            rs = RadioSetting(
1301
                "tdrch", "Tone Burst Frequency (BTech UV-82HP only)",
1302
                RadioSettingValueList(RTONE_LIST, RTONE_LIST[_settings.tdrch]))
1303
            advanced.append(rs)
1304

    
1305
        if len(self._mmap.get_packed()) == 0x1808:
1306
            # Old image, without aux block
1307
            return group
1308

    
1309
        if self.MODEL != "UV-6":
1310
            other = RadioSettingGroup("other", "Other Settings")
1311
            group.append(other)
1312

    
1313
            def _filter(name):
1314
                filtered = ""
1315
                for char in str(name):
1316
                    if char in chirp_common.CHARSET_ASCII:
1317
                        filtered += char
1318
                    else:
1319
                        filtered += " "
1320
                return filtered
1321

    
1322
            _msg = self._memobj.firmware_msg
1323
            val = RadioSettingValueString(0, 7, _filter(_msg.line1))
1324
            val.set_mutable(False)
1325
            rs = RadioSetting("firmware_msg.line1", "Firmware Message 1", val)
1326
            other.append(rs)
1327

    
1328
            val = RadioSettingValueString(0, 7, _filter(_msg.line2))
1329
            val.set_mutable(False)
1330
            rs = RadioSetting("firmware_msg.line2", "Firmware Message 2", val)
1331
            other.append(rs)
1332

    
1333
            _msg = self._memobj.sixpoweron_msg
1334
            rs = RadioSetting("sixpoweron_msg.line1", "6+Power-On Message 1",
1335
                              RadioSettingValueString(
1336
                                  0, 7, _filter(_msg.line1)))
1337
            other.append(rs)
1338
            rs = RadioSetting("sixpoweron_msg.line2", "6+Power-On Message 2",
1339
                              RadioSettingValueString(
1340
                                  0, 7, _filter(_msg.line2)))
1341
            other.append(rs)
1342

    
1343
            _msg = self._memobj.poweron_msg
1344
            rs = RadioSetting("poweron_msg.line1", "Power-On Message 1",
1345
                              RadioSettingValueString(
1346
                                  0, 7, _filter(_msg.line1)))
1347
            other.append(rs)
1348
            rs = RadioSetting("poweron_msg.line2", "Power-On Message 2",
1349
                              RadioSettingValueString(
1350
                                  0, 7, _filter(_msg.line2)))
1351
            other.append(rs)
1352

    
1353
            rs = RadioSetting("ponmsg", "Power-On Message",
1354
                              RadioSettingValueList(
1355
                                  PONMSG_LIST, PONMSG_LIST[_settings.ponmsg]))
1356
            other.append(rs)
1357

    
1358
            if self._is_orig():
1359
                limit = "limits_old"
1360
            else:
1361
                limit = "limits_new"
1362

    
1363
            vhf_limit = getattr(self._memobj, limit).vhf
1364
            rs = RadioSetting("%s.vhf.lower" % limit, "VHF Lower Limit (MHz)",
1365
                              RadioSettingValueInteger(1, 1000,
1366
                                                       vhf_limit.lower))
1367
            other.append(rs)
1368

    
1369
            rs = RadioSetting("%s.vhf.upper" % limit, "VHF Upper Limit (MHz)",
1370
                              RadioSettingValueInteger(1, 1000,
1371
                                                       vhf_limit.upper))
1372
            other.append(rs)
1373

    
1374
            rs = RadioSetting("%s.vhf.enable" % limit, "VHF TX Enabled",
1375
                              RadioSettingValueBoolean(vhf_limit.enable))
1376
            other.append(rs)
1377

    
1378
            uhf_limit = getattr(self._memobj, limit).uhf
1379
            rs = RadioSetting("%s.uhf.lower" % limit, "UHF Lower Limit (MHz)",
1380
                              RadioSettingValueInteger(1, 1000,
1381
                                                       uhf_limit.lower))
1382
            other.append(rs)
1383
            rs = RadioSetting("%s.uhf.upper" % limit, "UHF Upper Limit (MHz)",
1384
                              RadioSettingValueInteger(1, 1000,
1385
                                                       uhf_limit.upper))
1386
            other.append(rs)
1387
            rs = RadioSetting("%s.uhf.enable" % limit, "UHF TX Enabled",
1388
                              RadioSettingValueBoolean(uhf_limit.enable))
1389
            other.append(rs)
1390

    
1391
        if self.MODEL != "UV-6":
1392
            workmode = RadioSettingGroup("workmode", "Work Mode Settings")
1393
            group.append(workmode)
1394

    
1395
            rs = RadioSetting("displayab", "Display",
1396
                              RadioSettingValueList(
1397
                                  AB_LIST, AB_LIST[_settings.displayab]))
1398
            workmode.append(rs)
1399

    
1400
            rs = RadioSetting("workmode", "VFO/MR Mode",
1401
                              RadioSettingValueList(
1402
                                  WORKMODE_LIST,
1403
                                  WORKMODE_LIST[_settings.workmode]))
1404
            workmode.append(rs)
1405

    
1406
            rs = RadioSetting("keylock", "Keypad Lock",
1407
                              RadioSettingValueBoolean(_settings.keylock))
1408
            workmode.append(rs)
1409

    
1410
            rs = RadioSetting("wmchannel.mrcha", "MR A Channel",
1411
                              RadioSettingValueInteger(0, 127,
1412
                                                       _wmchannel.mrcha))
1413
            workmode.append(rs)
1414

    
1415
            rs = RadioSetting("wmchannel.mrchb", "MR B Channel",
1416
                              RadioSettingValueInteger(0, 127,
1417
                                                       _wmchannel.mrchb))
1418
            workmode.append(rs)
1419

    
1420
            def convert_bytes_to_freq(bytes):
1421
                real_freq = 0
1422
                for byte in bytes:
1423
                    real_freq = (real_freq * 10) + byte
1424
                return chirp_common.format_freq(real_freq * 10)
1425

    
1426
            def my_validate(value):
1427
                value = chirp_common.parse_freq(value)
1428
                if 17400000 <= value and value < 40000000:
1429
                    msg = ("Can't be between 174.00000-400.00000")
1430
                    raise InvalidValueError(msg)
1431
                return chirp_common.format_freq(value)
1432

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

    
1440
            val1a = RadioSettingValueString(0, 10,
1441
                                            convert_bytes_to_freq(_vfoa.freq))
1442
            val1a.set_validate_callback(my_validate)
1443
            rs = RadioSetting("vfoa.freq", "VFO A Frequency", val1a)
1444
            rs.set_apply_callback(apply_freq, _vfoa)
1445
            workmode.append(rs)
1446

    
1447
            val1b = RadioSettingValueString(0, 10,
1448
                                            convert_bytes_to_freq(_vfob.freq))
1449
            val1b.set_validate_callback(my_validate)
1450
            rs = RadioSetting("vfob.freq", "VFO B Frequency", val1b)
1451
            rs.set_apply_callback(apply_freq, _vfob)
1452
            workmode.append(rs)
1453

    
1454
            rs = RadioSetting("vfoa.sftd", "VFO A Shift",
1455
                              RadioSettingValueList(
1456
                                  SHIFTD_LIST, SHIFTD_LIST[_vfoa.sftd]))
1457
            workmode.append(rs)
1458

    
1459
            rs = RadioSetting("vfob.sftd", "VFO B Shift",
1460
                              RadioSettingValueList(
1461
                                  SHIFTD_LIST, SHIFTD_LIST[_vfob.sftd]))
1462
            workmode.append(rs)
1463

    
1464
            def convert_bytes_to_offset(bytes):
1465
                real_offset = 0
1466
                for byte in bytes:
1467
                    real_offset = (real_offset * 10) + byte
1468
                return chirp_common.format_freq(real_offset * 1000)
1469

    
1470
            def apply_offset(setting, obj):
1471
                value = chirp_common.parse_freq(str(setting.value)) / 1000
1472
                for i in range(5, -1, -1):
1473
                    obj.offset[i] = value % 10
1474
                    value /= 10
1475

    
1476
            val1a = RadioSettingValueString(
1477
                0, 10, convert_bytes_to_offset(_vfoa.offset))
1478
            rs = RadioSetting("vfoa.offset",
1479
                              "VFO A Offset (0.0-999.999)", val1a)
1480
            rs.set_apply_callback(apply_offset, _vfoa)
1481
            workmode.append(rs)
1482

    
1483
            val1b = RadioSettingValueString(
1484
                0, 10, convert_bytes_to_offset(_vfob.offset))
1485
            rs = RadioSetting("vfob.offset",
1486
                              "VFO B Offset (0.0-999.999)", val1b)
1487
            rs.set_apply_callback(apply_offset, _vfob)
1488
            workmode.append(rs)
1489

    
1490
            if self._tri_power:
1491
                rs = RadioSetting("vfoa.txpower3", "VFO A Power",
1492
                                  RadioSettingValueList(
1493
                                      TXPOWER3_LIST,
1494
                                      TXPOWER3_LIST[_vfoa.txpower3]))
1495
                workmode.append(rs)
1496

    
1497
                rs = RadioSetting("vfob.txpower3", "VFO B Power",
1498
                                  RadioSettingValueList(
1499
                                      TXPOWER3_LIST,
1500
                                      TXPOWER3_LIST[_vfob.txpower3]))
1501
                workmode.append(rs)
1502
            else:
1503
                rs = RadioSetting("vfoa.txpower", "VFO A Power",
1504
                                  RadioSettingValueList(
1505
                                      TXPOWER_LIST,
1506
                                      TXPOWER_LIST[_vfoa.txpower]))
1507
                workmode.append(rs)
1508

    
1509
                rs = RadioSetting("vfob.txpower", "VFO B Power",
1510
                                  RadioSettingValueList(
1511
                                      TXPOWER_LIST,
1512
                                      TXPOWER_LIST[_vfob.txpower]))
1513
                workmode.append(rs)
1514

    
1515
            rs = RadioSetting("vfoa.widenarr", "VFO A Bandwidth",
1516
                              RadioSettingValueList(
1517
                                  BANDWIDTH_LIST,
1518
                                  BANDWIDTH_LIST[_vfoa.widenarr]))
1519
            workmode.append(rs)
1520

    
1521
            rs = RadioSetting("vfob.widenarr", "VFO B Bandwidth",
1522
                              RadioSettingValueList(
1523
                                  BANDWIDTH_LIST,
1524
                                  BANDWIDTH_LIST[_vfob.widenarr]))
1525
            workmode.append(rs)
1526

    
1527
            rs = RadioSetting("vfoa.scode", "VFO A PTT-ID",
1528
                              RadioSettingValueList(
1529
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfoa.scode]))
1530
            workmode.append(rs)
1531

    
1532
            rs = RadioSetting("vfob.scode", "VFO B PTT-ID",
1533
                              RadioSettingValueList(
1534
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfob.scode]))
1535
            workmode.append(rs)
1536

    
1537
            if not self._is_orig():
1538
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1539
                                  RadioSettingValueList(
1540
                                      STEP291_LIST, STEP291_LIST[_vfoa.step]))
1541
                workmode.append(rs)
1542
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1543
                                  RadioSettingValueList(
1544
                                      STEP291_LIST, STEP291_LIST[_vfob.step]))
1545
                workmode.append(rs)
1546
            else:
1547
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1548
                                  RadioSettingValueList(
1549
                                      STEP_LIST, STEP_LIST[_vfoa.step]))
1550
                workmode.append(rs)
1551
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1552
                                  RadioSettingValueList(
1553
                                      STEP_LIST, STEP_LIST[_vfob.step]))
1554
                workmode.append(rs)
1555

    
1556
        fm_preset = RadioSettingGroup("fm_preset", "FM Radio Preset")
1557
        group.append(fm_preset)
1558

    
1559
        if _fm_presets <= 108.0 * 10 - 650:
1560
            preset = _fm_presets / 10.0 + 65
1561
        elif _fm_presets >= 65.0 * 10 and _fm_presets <= 108.0 * 10:
1562
            preset = _fm_presets / 10.0
1563
        else:
1564
            preset = 76.0
1565
        rs = RadioSetting("fm_presets", "FM Preset(MHz)",
1566
                          RadioSettingValueFloat(65, 108.0, preset, 0.1, 1))
1567
        fm_preset.append(rs)
1568

    
1569
        dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
1570
        group.append(dtmf)
1571

    
1572
        if str(self._memobj.firmware_msg.line1) == "HN5RV01":
1573
            dtmfchars = "0123456789ABCD*#"
1574
        else:
1575
            dtmfchars = "0123456789 *#ABCD"
1576

    
1577
        for i in range(0, 15):
1578
            _codeobj = self._memobj.pttid[i].code
1579
            _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1580
            val = RadioSettingValueString(0, 5, _code, False)
1581
            val.set_charset(dtmfchars)
1582
            rs = RadioSetting("pttid/%i.code" % i,
1583
                              "PTT ID Code %i" % (i + 1), val)
1584

    
1585
            def apply_code(setting, obj):
1586
                code = []
1587
                for j in range(0, 5):
1588
                    try:
1589
                        code.append(dtmfchars.index(str(setting.value)[j]))
1590
                    except IndexError:
1591
                        code.append(0xFF)
1592
                obj.code = code
1593
            rs.set_apply_callback(apply_code, self._memobj.pttid[i])
1594
            dtmf.append(rs)
1595

    
1596
        dtmfcharsani = "0123456789"
1597

    
1598
        _codeobj = self._memobj.ani.code
1599
        _code = "".join([dtmfcharsani[x] for x in _codeobj if int(x) < 0x1F])
1600
        val = RadioSettingValueString(0, 5, _code, False)
1601
        val.set_charset(dtmfcharsani)
1602
        rs = RadioSetting("ani.code", "ANI Code", val)
1603

    
1604
        def apply_code(setting, obj):
1605
            code = []
1606
            for j in range(0, 5):
1607
                try:
1608
                    code.append(dtmfchars.index(str(setting.value)[j]))
1609
                except IndexError:
1610
                    code.append(0xFF)
1611
            obj.code = code
1612
        rs.set_apply_callback(apply_code, _ani)
1613
        dtmf.append(rs)
1614

    
1615
        rs = RadioSetting("ani.aniid", "ANI ID",
1616
                          RadioSettingValueList(PTTID_LIST,
1617
                                                PTTID_LIST[_ani.aniid]))
1618
        dtmf.append(rs)
1619

    
1620
        _codeobj = self._memobj.ani.alarmcode
1621
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1622
        val = RadioSettingValueString(0, 3, _code, False)
1623
        val.set_charset(dtmfchars)
1624
        rs = RadioSetting("ani.alarmcode", "Alarm Code", val)
1625

    
1626
        def apply_code(setting, obj):
1627
            alarmcode = []
1628
            for j in range(0, 3):
1629
                try:
1630
                    alarmcode.append(dtmfchars.index(str(setting.value)[j]))
1631
                except IndexError:
1632
                    alarmcode.append(0xFF)
1633
            obj.alarmcode = alarmcode
1634
        rs.set_apply_callback(apply_code, _ani)
1635
        dtmf.append(rs)
1636

    
1637
        rs = RadioSetting("dtmfst", "DTMF Sidetone",
1638
                          RadioSettingValueList(DTMFST_LIST,
1639
                                                DTMFST_LIST[_settings.dtmfst]))
1640
        dtmf.append(rs)
1641

    
1642
        if _ani.dtmfon > 0xC3:
1643
            val = 0x00
1644
        else:
1645
            val = _ani.dtmfon
1646
        rs = RadioSetting("ani.dtmfon", "DTMF Speed (on)",
1647
                          RadioSettingValueList(DTMFSPEED_LIST,
1648
                                                DTMFSPEED_LIST[val]))
1649
        dtmf.append(rs)
1650

    
1651
        if _ani.dtmfoff > 0xC3:
1652
            val = 0x00
1653
        else:
1654
            val = _ani.dtmfoff
1655
        rs = RadioSetting("ani.dtmfoff", "DTMF Speed (off)",
1656
                          RadioSettingValueList(DTMFSPEED_LIST,
1657
                                                DTMFSPEED_LIST[val]))
1658
        dtmf.append(rs)
1659

    
1660
        rs = RadioSetting("pttlt", "PTT ID Delay",
1661
                          RadioSettingValueInteger(0, 50, _settings.pttlt))
1662
        dtmf.append(rs)
1663

    
1664
        if not self._is_orig() and self._aux_block:
1665
            service = RadioSettingGroup("service", "Service Settings")
1666
            group.append(service)
1667

    
1668
            for band in ["vhf", "uhf"]:
1669
                for index in range(0, 10):
1670
                    key = "squelch_new.%s.sql%i" % (band, index)
1671
                    if band == "vhf":
1672
                        _obj = self._memobj.squelch_new.vhf
1673
                    elif band == "uhf":
1674
                        _obj = self._memobj.squelch_new.uhf
1675
                    name = "%s Squelch %i" % (band.upper(), index)
1676
                    rs = RadioSetting(key, name,
1677
                                      RadioSettingValueInteger(
1678
                                          0, 123,
1679
                                          getattr(_obj, "sql%i" % (index))))
1680
                    service.append(rs)
1681

    
1682
        return group
1683

    
1684
    def get_settings(self):
1685
        try:
1686
            return self._get_settings()
1687
        except:
1688
            import traceback
1689
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1690
            return None
1691

    
1692
    def set_settings(self, settings):
1693
        _settings = self._memobj.settings
1694
        for element in settings:
1695
            if not isinstance(element, RadioSetting):
1696
                if element.get_name() == "fm_preset":
1697
                    self._set_fm_preset(element)
1698
                else:
1699
                    self.set_settings(element)
1700
                    continue
1701
            else:
1702
                try:
1703
                    name = element.get_name()
1704
                    if "." in name:
1705
                        bits = name.split(".")
1706
                        obj = self._memobj
1707
                        for bit in bits[:-1]:
1708
                            if "/" in bit:
1709
                                bit, index = bit.split("/", 1)
1710
                                index = int(index)
1711
                                obj = getattr(obj, bit)[index]
1712
                            else:
1713
                                obj = getattr(obj, bit)
1714
                        setting = bits[-1]
1715
                    else:
1716
                        obj = _settings
1717
                        setting = element.get_name()
1718

    
1719
                    if element.has_apply_callback():
1720
                        LOG.debug("Using apply callback")
1721
                        element.run_apply_callback()
1722
                    elif element.value.get_mutable():
1723
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1724
                        setattr(obj, setting, element.value)
1725
                except Exception, e:
1726
                    LOG.debug(element.get_name())
1727
                    raise
1728

    
1729
    def _set_fm_preset(self, settings):
1730
        for element in settings:
1731
            try:
1732
                val = element.value
1733
                if self._memobj.fm_presets <= 108.0 * 10 - 650:
1734
                    value = int(val.get_value() * 10 - 650)
1735
                else:
1736
                    value = int(val.get_value() * 10)
1737
                LOG.debug("Setting fm_presets = %s" % (value))
1738
                self._memobj.fm_presets = value
1739
            except Exception, e:
1740
                LOG.debug(element.get_name())
1741
                raise
1742

    
1743

    
1744
class UV5XAlias(chirp_common.Alias):
1745
    VENDOR = "Baofeng"
1746
    MODEL = "UV-5X"
1747

    
1748

    
1749
class RT5RAlias(chirp_common.Alias):
1750
    VENDOR = "Retevis"
1751
    MODEL = "RT-5R"
1752

    
1753

    
1754
class RT5RVAlias(chirp_common.Alias):
1755
    VENDOR = "Retevis"
1756
    MODEL = "RT-5RV"
1757

    
1758

    
1759
class RT5Alias(chirp_common.Alias):
1760
    VENDOR = "Retevis"
1761
    MODEL = "RT5"
1762

    
1763

    
1764
class RT5_TPAlias(chirp_common.Alias):
1765
    VENDOR = "Retevis"
1766
    MODEL = "RT5(tri-power)"
1767

    
1768

    
1769
class RH5RAlias(chirp_common.Alias):
1770
    VENDOR = "Rugged"
1771
    MODEL = "RH5R"
1772

    
1773

    
1774
class ROUV5REXAlias(chirp_common.Alias):
1775
    VENDOR = "Radioddity"
1776
    MODEL = "UV-5R EX"
1777

    
1778

    
1779
class A5RAlias(chirp_common.Alias):
1780
    VENDOR = "Ansoko"
1781
    MODEL = "A-5R"
1782

    
1783

    
1784
@directory.register
1785
class BaofengUV5RGeneric(BaofengUV5R):
1786
    ALIASES = [UV5XAlias, RT5RAlias, RT5RVAlias, RT5Alias, RH5RAlias,
1787
               ROUV5REXAlias, A5RAlias]
1788

    
1789

    
1790
@directory.register
1791
class BaofengF11Radio(BaofengUV5R):
1792
    VENDOR = "Baofeng"
1793
    MODEL = "F-11"
1794
    _basetype = BASETYPE_F11
1795
    _idents = [UV5R_MODEL_F11]
1796

    
1797
    def _is_orig(self):
1798
        # Override this for F11 to always return False
1799
        return False
1800

    
1801

    
1802
@directory.register
1803
class BaofengUV82Radio(BaofengUV5R):
1804
    MODEL = "UV-82"
1805
    _basetype = BASETYPE_UV82
1806
    _idents = [UV5R_MODEL_UV82]
1807
    _vhf_range = (130000000, 176000000)
1808
    _uhf_range = (400000000, 521000000)
1809
    _valid_chars = chirp_common.CHARSET_ASCII
1810

    
1811
    def _is_orig(self):
1812
        # Override this for UV82 to always return False
1813
        return False
1814

    
1815

    
1816
@directory.register
1817
class Radioddity82X3Radio(BaofengUV82Radio):
1818
    VENDOR = "Radioddity"
1819
    MODEL = "UV-82X3"
1820
    _basetype = BASETYPE_UV82X3
1821

    
1822
    def get_features(self):
1823
        rf = BaofengUV5R.get_features(self)
1824
        rf.valid_bands = [self._vhf_range,
1825
                          (200000000, 260000000),
1826
                          self._uhf_range]
1827
        return rf
1828

    
1829

    
1830
@directory.register
1831
class BaofengUV6Radio(BaofengUV5R):
1832

    
1833
    """Baofeng UV-6/UV-7"""
1834
    VENDOR = "Baofeng"
1835
    MODEL = "UV-6"
1836
    _basetype = BASETYPE_UV6
1837
    _idents = [UV5R_MODEL_UV6,
1838
               UV5R_MODEL_UV6_ORIG
1839
               ]
1840
    _aux_block = False
1841

    
1842
    def get_features(self):
1843
        rf = BaofengUV5R.get_features(self)
1844
        rf.memory_bounds = (1, 128)
1845
        return rf
1846

    
1847
    def _get_mem(self, number):
1848
        return self._memobj.memory[number - 1]
1849

    
1850
    def _get_nam(self, number):
1851
        return self._memobj.names[number - 1]
1852

    
1853
    def _set_mem(self, number):
1854
        return self._memobj.memory[number - 1]
1855

    
1856
    def _set_nam(self, number):
1857
        return self._memobj.names[number - 1]
1858

    
1859
    def _is_orig(self):
1860
        # Override this for UV6 to always return False
1861
        return False
1862

    
1863

    
1864
@directory.register
1865
class IntekKT980Radio(BaofengUV5R):
1866
    VENDOR = "Intek"
1867
    MODEL = "KT-980HP"
1868
    _basetype = BASETYPE_KT980HP
1869
    _idents = [UV5R_MODEL_291]
1870
    _vhf_range = (130000000, 180000000)
1871
    _uhf_range = (400000000, 521000000)
1872
    _tri_power = True
1873

    
1874
    def get_features(self):
1875
        rf = BaofengUV5R.get_features(self)
1876
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1877
        return rf
1878

    
1879
    def _is_orig(self):
1880
        # Override this for KT980HP to always return False
1881
        return False
1882

    
1883

    
1884
class ROGA5SAlias(chirp_common.Alias):
1885
    VENDOR = "Radioddity"
1886
    MODEL = "GA-5S"
1887

    
1888

    
1889
class UV5XPAlias(chirp_common.Alias):
1890
    VENDOR = "Baofeng"
1891
    MODEL = "UV-5XP"
1892

    
1893

    
1894
class TSTIF8Alias(chirp_common.Alias):
1895
    VENDOR = "TechSide"
1896
    MODEL = "TI-F8+"
1897

    
1898

    
1899
class TenwayUV5RPro(chirp_common.Alias):
1900
    VENDOR = 'Tenway'
1901
    MODEL = 'UV-5R Pro'
1902

    
1903

    
1904
@directory.register
1905
class BaofengBFF8HPRadio(BaofengUV5R):
1906
    VENDOR = "Baofeng"
1907
    MODEL = "BF-F8HP"
1908
    ALIASES = [RT5_TPAlias, ROGA5SAlias, UV5XPAlias, TSTIF8Alias,
1909
               TenwayUV5RPro]
1910
    _basetype = BASETYPE_F8HP
1911
    _idents = [UV5R_MODEL_291,
1912
               UV5R_MODEL_A58
1913
               ]
1914
    _vhf_range = (130000000, 180000000)
1915
    _uhf_range = (400000000, 521000000)
1916
    _tri_power = True
1917

    
1918
    def get_features(self):
1919
        rf = BaofengUV5R.get_features(self)
1920
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1921
        return rf
1922

    
1923
    def _is_orig(self):
1924
        # Override this for BFF8HP to always return False
1925
        return False
1926

    
1927

    
1928
class TenwayUV82Pro(chirp_common.Alias):
1929
    VENDOR = 'Tenway'
1930
    MODEL = 'UV-82 Pro'
1931

    
1932

    
1933
@directory.register
1934
class BaofengUV82HPRadio(BaofengUV5R):
1935
    VENDOR = "Baofeng"
1936
    MODEL = "UV-82HP"
1937
    ALIASES = [TenwayUV82Pro]
1938
    _basetype = BASETYPE_UV82HP
1939
    _idents = [UV5R_MODEL_UV82]
1940
    _vhf_range = (136000000, 175000000)
1941
    _uhf_range = (400000000, 521000000)
1942
    _tri_power = True
1943

    
1944
    def get_features(self):
1945
        rf = BaofengUV5R.get_features(self)
1946
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1947
        return rf
1948

    
1949
    def _is_orig(self):
1950
        # Override this for UV82HP to always return False
1951
        return False
1952

    
1953

    
1954
class TDUV5RRadio(chirp_common.Alias):
1955
    VENDOR = "TIDRADIO"
1956
    MODEL = "TD-UV5R TriPower"
1957

    
1958

    
1959
@directory.register
1960
class RadioddityUV5RX3Radio(BaofengUV5R):
1961
    VENDOR = "Radioddity"
1962
    MODEL = "UV-5RX3"
1963
    ALIASES = [TDUV5RRadio]
1964

    
1965
    def get_features(self):
1966
        rf = BaofengUV5R.get_features(self)
1967
        rf.valid_bands = [self._vhf_range,
1968
                          (200000000, 260000000),
1969
                          self._uhf_range]
1970
        return rf
1971

    
1972
    @classmethod
1973
    def match_model(cls, filename, filedata):
1974
        return False
(3-3/5)