Project

General

Profile

Bug #8321 ยป uv5r_fix_for_hn5rv_firmware.py

Jim Unroe, 10/16/2020 07:11 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 not any(type in radio_version for type in radio._basetype):
560
        # This radio can't be properly detected by parsing its firmware
561
        # version.
562
        raise errors.RadioError("Incorrect 'Model' selected.")
563
    else:
564
        # This radio can be properly detected by parsing its firmware version.
565
        # There is no need to append its model type to the end of the image.
566
        append_model = False
567

    
568
    # Main block
569
    LOG.debug("downloading main block...")
570
    for i in range(0, 0x1800, 0x40):
571
        data += _read_block(radio, i, 0x40, False)
572
        _do_status(radio, i)
573
    _do_status(radio, radio.get_memsize())
574
    LOG.debug("done.")
575
    if radio._aux_block:
576
        LOG.debug("downloading aux block...")
577
        # Auxiliary block starts at 0x1ECO (?)
578
        for i in range(0x1EC0, 0x2000, 0x40):
579
            data += _read_block(radio, i, 0x40, False)
580

    
581
    if append_model:
582
        data += radio.MODEL.ljust(8)
583

    
584
    LOG.debug("done.")
585
    return memmap.MemoryMap(data)
586

    
587

    
588
def _send_block(radio, addr, data):
589
    msg = struct.pack(">BHB", ord("X"), addr, len(data))
590
    radio.pipe.write(msg + data)
591
    time.sleep(0.05)
592

    
593
    ack = radio.pipe.read(1)
594
    if ack != "\x06":
595
        raise errors.RadioError("Radio refused to accept block 0x%04x" % addr)
596

    
597

    
598
def _do_upload(radio):
599
    ident = _ident_radio(radio)
600
    radio_upper_band = ident[3:4]
601
    image_upper_band = _upper_band_from_image(radio)
602

    
603
    if image_upper_band == vhf_220_radio or radio_upper_band == vhf_220_radio:
604
        if image_upper_band != radio_upper_band:
605
            raise errors.RadioError("Image not supported by radio")
606

    
607
    image_version = _firmware_version_from_image(radio)
608
    radio_version = _get_radio_firmware_version(radio)
609
    LOG.info("Image Version is %s" % repr(image_version))
610
    LOG.info("Radio Version is %s" % repr(radio_version))
611

    
612
    # default ranges
613
    _ranges_main_default = [
614
        (0x0008, 0x0CF8),
615
        (0x0D08, 0x0DF8),
616
        (0x0E08, 0x1808)
617
        ]
618
    _ranges_aux_default = [
619
        (0x1EC0, 0x1EF0),
620
        ]
621

    
622
    # extra aux ranges
623
    _ranges_aux_extra = [
624
        (0x1F60, 0x1F70),
625
        (0x1F80, 0x1F90),
626
        (0x1FC0, 0x1FD0)
627
        ]
628

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

    
650
    if not radio._aux_block:
651
        image_matched_radio = True
652

    
653
    # Main block
654
    for start_addr, end_addr in ranges_main:
655
        for i in range(start_addr, end_addr, 0x10):
656
            _send_block(radio, i - 0x08, radio.get_mmap()[i:i + 0x10])
657
            _do_status(radio, i)
658
        _do_status(radio, radio.get_memsize())
659

    
660
    if len(radio.get_mmap().get_packed()) == 0x1808:
661
        LOG.info("Old image, not writing aux block")
662
        return  # Old image, no aux block
663

    
664
    # Auxiliary block at radio address 0x1EC0, our offset 0x1808
665
    for start_addr, end_addr in ranges_aux:
666
        for i in range(start_addr, end_addr, 0x10):
667
            addr = 0x1808 + (i - 0x1EC0)
668
            _send_block(radio, i, radio.get_mmap()[addr:addr + 0x10])
669

    
670
    if not image_matched_radio:
671
        msg = ("Upload finished, but the 'Other Settings' "
672
               "could not be sent because the firmware "
673
               "version of the image (%s) does not match "
674
               "that of the radio (%s).")
675
        raise errors.RadioError(msg % (image_version, radio_version))
676

    
677
UV5R_POWER_LEVELS = [chirp_common.PowerLevel("High", watts=4.00),
678
                     chirp_common.PowerLevel("Low",  watts=1.00)]
679

    
680
UV5R_POWER_LEVELS3 = [chirp_common.PowerLevel("High", watts=8.00),
681
                      chirp_common.PowerLevel("Med",  watts=4.00),
682
                      chirp_common.PowerLevel("Low",  watts=1.00)]
683

    
684
UV5R_DTCS = sorted(chirp_common.DTCS_CODES + [645])
685

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

    
689

    
690
def model_match(cls, data):
691
    """Match the opened/downloaded image to the correct version"""
692

    
693
    if len(data) == 0x1950:
694
        rid = data[0x1948:0x1950]
695
        return rid.startswith(cls.MODEL)
696
    elif len(data) == 0x1948:
697
        rid = data[cls._fw_ver_file_start:cls._fw_ver_file_stop]
698
        if any(type in rid for type in cls._basetype):
699
            return True
700
    else:
701
        return False
702

    
703

    
704
class BaofengUV5R(chirp_common.CloneModeRadio):
705

    
706
    """Baofeng UV-5R"""
707
    VENDOR = "Baofeng"
708
    MODEL = "UV-5R"
709
    BAUD_RATE = 9600
710

    
711
    _memsize = 0x1808
712
    _basetype = BASETYPE_UV5R
713
    _idents = [UV5R_MODEL_291,
714
               UV5R_MODEL_ORIG
715
               ]
716
    _vhf_range = (136000000, 174000000)
717
    _220_range = (220000000, 260000000)
718
    _uhf_range = (400000000, 520000000)
719
    _aux_block = True
720
    _tri_power = False
721
    _mem_params = (0x1828  # poweron_msg offset
722
                   )
723
    # offset of fw version in image file
724
    _fw_ver_file_start = 0x1838
725
    _fw_ver_file_stop = 0x1846
726

    
727
    _ranges_main = [
728
                    (0x0008, 0x1808),
729
                   ]
730
    _ranges_aux = [
731
                   (0x1EC0, 0x2000),
732
                  ]
733
    _valid_chars = UV5R_CHARSET
734

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

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

    
780
        normal_bands = [self._vhf_range, self._uhf_range]
781
        rax_bands = [self._vhf_range, self._220_range]
782

    
783
        if self._mmap is None:
784
            rf.valid_bands = [normal_bands[0], rax_bands[1], normal_bands[1]]
785
        elif not self._is_orig() and self._my_upper_band() == vhf_220_radio:
786
            rf.valid_bands = rax_bands
787
        else:
788
            rf.valid_bands = normal_bands
789
        rf.memory_bounds = (0, 127)
790
        return rf
791

    
792
    @classmethod
793
    def match_model(cls, filedata, filename):
794
        match_size = False
795
        match_model = False
796
        if len(filedata) in [0x1808, 0x1948, 0x1950]:
797
            match_size = True
798
        match_model = model_match(cls, filedata)
799

    
800
        if match_size and match_model:
801
            return True
802
        else:
803
            return False
804

    
805
    def process_mmap(self):
806
        self._memobj = bitwise.parse(MEM_FORMAT % self._mem_params, self._mmap)
807

    
808
    def sync_in(self):
809
        try:
810
            self._mmap = _do_download(self)
811
        except errors.RadioError:
812
            raise
813
        except Exception, e:
814
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
815
        self.process_mmap()
816

    
817
    def sync_out(self):
818
        try:
819
            _do_upload(self)
820
        except errors.RadioError:
821
            raise
822
        except Exception, e:
823
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
824

    
825
    def get_raw_memory(self, number):
826
        return repr(self._memobj.memory[number])
827

    
828
    def _is_txinh(self, _mem):
829
        raw_tx = ""
830
        for i in range(0, 4):
831
            raw_tx += _mem.txfreq[i].get_raw()
832
        return raw_tx == "\xFF\xFF\xFF\xFF"
833

    
834
    def _get_mem(self, number):
835
        return self._memobj.memory[number]
836

    
837
    def _get_nam(self, number):
838
        return self._memobj.names[number]
839

    
840
    def get_memory(self, number):
841
        _mem = self._get_mem(number)
842
        _nam = self._get_nam(number)
843

    
844
        mem = chirp_common.Memory()
845
        mem.number = number
846

    
847
        if _mem.get_raw()[0] == "\xff":
848
            mem.empty = True
849
            return mem
850

    
851
        mem.freq = int(_mem.rxfreq) * 10
852

    
853
        if self._is_txinh(_mem):
854
            mem.duplex = "off"
855
            mem.offset = 0
856
        elif int(_mem.rxfreq) == int(_mem.txfreq):
857
            mem.duplex = ""
858
            mem.offset = 0
859
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 70000000:
860
            mem.duplex = "split"
861
            mem.offset = int(_mem.txfreq) * 10
862
        else:
863
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
864
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
865

    
866
        for char in _nam.name:
867
            if str(char) == "\xFF":
868
                char = " "  # The UV-5R software may have 0xFF mid-name
869
            mem.name += str(char)
870
        mem.name = mem.name.rstrip()
871

    
872
        dtcs_pol = ["N", "N"]
873

    
874
        if _mem.txtone in [0, 0xFFFF]:
875
            txmode = ""
876
        elif _mem.txtone >= 0x0258:
877
            txmode = "Tone"
878
            mem.rtone = int(_mem.txtone) / 10.0
879
        elif _mem.txtone <= 0x0258:
880
            txmode = "DTCS"
881
            if _mem.txtone > 0x69:
882
                index = _mem.txtone - 0x6A
883
                dtcs_pol[0] = "R"
884
            else:
885
                index = _mem.txtone - 1
886
            mem.dtcs = UV5R_DTCS[index]
887
        else:
888
            LOG.warn("Bug: txtone is %04x" % _mem.txtone)
889

    
890
        if _mem.rxtone in [0, 0xFFFF]:
891
            rxmode = ""
892
        elif _mem.rxtone >= 0x0258:
893
            rxmode = "Tone"
894
            mem.ctone = int(_mem.rxtone) / 10.0
895
        elif _mem.rxtone <= 0x0258:
896
            rxmode = "DTCS"
897
            if _mem.rxtone >= 0x6A:
898
                index = _mem.rxtone - 0x6A
899
                dtcs_pol[1] = "R"
900
            else:
901
                index = _mem.rxtone - 1
902
            mem.rx_dtcs = UV5R_DTCS[index]
903
        else:
904
            LOG.warn("Bug: rxtone is %04x" % _mem.rxtone)
905

    
906
        if txmode == "Tone" and not rxmode:
907
            mem.tmode = "Tone"
908
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
909
            mem.tmode = "TSQL"
910
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
911
            mem.tmode = "DTCS"
912
        elif rxmode or txmode:
913
            mem.tmode = "Cross"
914
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
915

    
916
        mem.dtcs_polarity = "".join(dtcs_pol)
917

    
918
        if not _mem.scan:
919
            mem.skip = "S"
920

    
921
        if self._tri_power:
922
            levels = UV5R_POWER_LEVELS3
923
        else:
924
            levels = UV5R_POWER_LEVELS
925
        try:
926
            mem.power = levels[_mem.lowpower]
927
        except IndexError:
928
            LOG.error("Radio reported invalid power level %s (in %s)" %
929
                      (_mem.lowpower, levels))
930
            mem.power = levels[0]
931

    
932
        mem.mode = _mem.wide and "FM" or "NFM"
933

    
934
        mem.extra = RadioSettingGroup("Extra", "extra")
935

    
936
        rs = RadioSetting("bcl", "BCL",
937
                          RadioSettingValueBoolean(_mem.bcl))
938
        mem.extra.append(rs)
939

    
940
        rs = RadioSetting("pttid", "PTT ID",
941
                          RadioSettingValueList(PTTID_LIST,
942
                                                PTTID_LIST[_mem.pttid]))
943
        mem.extra.append(rs)
944

    
945
        rs = RadioSetting("scode", "PTT ID Code",
946
                          RadioSettingValueList(PTTIDCODE_LIST,
947
                                                PTTIDCODE_LIST[_mem.scode]))
948
        mem.extra.append(rs)
949

    
950
        return mem
951

    
952
    def _set_mem(self, number):
953
        return self._memobj.memory[number]
954

    
955
    def _set_nam(self, number):
956
        return self._memobj.names[number]
957

    
958
    def set_memory(self, mem):
959
        _mem = self._get_mem(mem.number)
960
        _nam = self._get_nam(mem.number)
961

    
962
        if mem.empty:
963
            _mem.set_raw("\xff" * 16)
964
            _nam.set_raw("\xff" * 16)
965
            return
966

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

    
981
        _mem.set_raw("\x00" * 16)
982

    
983
        _mem.rxfreq = mem.freq / 10
984

    
985
        if mem.duplex == "off":
986
            for i in range(0, 4):
987
                _mem.txfreq[i].set_raw("\xFF")
988
        elif mem.duplex == "split":
989
            _mem.txfreq = mem.offset / 10
990
        elif mem.duplex == "+":
991
            _mem.txfreq = (mem.freq + mem.offset) / 10
992
        elif mem.duplex == "-":
993
            _mem.txfreq = (mem.freq - mem.offset) / 10
994
        else:
995
            _mem.txfreq = mem.freq / 10
996

    
997
        _namelength = self.get_features().valid_name_length
998
        for i in range(_namelength):
999
            try:
1000
                _nam.name[i] = mem.name[i]
1001
            except IndexError:
1002
                _nam.name[i] = "\xFF"
1003

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

    
1033
        if txmode == "DTCS" and mem.dtcs_polarity[0] == "R":
1034
            _mem.txtone += 0x69
1035
        if rxmode == "DTCS" and mem.dtcs_polarity[1] == "R":
1036
            _mem.rxtone += 0x69
1037

    
1038
        _mem.scan = mem.skip != "S"
1039
        _mem.wide = mem.mode == "FM"
1040

    
1041
        if mem.power:
1042
            if self._tri_power:
1043
                levels = [str(l) for l in UV5R_POWER_LEVELS3]
1044
                _mem.lowpower = levels.index(str(mem.power))
1045
            else:
1046
                _mem.lowpower = UV5R_POWER_LEVELS.index(mem.power)
1047
        else:
1048
            _mem.lowpower = 0
1049

    
1050
        if not was_empty:
1051
            # restoring old extra-settings (issue 4121
1052
            _mem.bcl.set_value(prev_bcl)
1053
            _mem.scode.set_value(prev_scode)
1054
            _mem.pttid.set_value(prev_pttid)
1055

    
1056
        for setting in mem.extra:
1057
            setattr(_mem, setting.get_name(), setting.value)
1058

    
1059
    def _is_orig(self):
1060
        version_tag = _firmware_version_from_image(self)
1061
        LOG.debug("@_is_orig, version_tag: %s", util.hexprint(version_tag))
1062
        try:
1063
            if 'BFB' in version_tag:
1064
                idx = version_tag.index("BFB") + 3
1065
                version = int(version_tag[idx:idx + 3])
1066
                return version < 291
1067
            return False
1068
        except:
1069
            pass
1070
        raise errors.RadioError("Unable to parse version string %s" %
1071
                                version_tag)
1072

    
1073
    def _my_version(self):
1074
        version_tag = _firmware_version_from_image(self)
1075
        if 'BFB' in version_tag:
1076
            idx = version_tag.index("BFB") + 3
1077
            return int(version_tag[idx:idx + 3])
1078

    
1079
        raise Exception("Unrecognized firmware version string")
1080

    
1081
    def _my_upper_band(self):
1082
        band_tag = _upper_band_from_image(self)
1083
        return band_tag
1084

    
1085
    def _get_settings(self):
1086
        _ani = self._memobj.ani
1087
        _fm_presets = self._memobj.fm_presets
1088
        _settings = self._memobj.settings
1089
        _squelch = self._memobj.squelch_new
1090
        _vfoa = self._memobj.vfoa
1091
        _vfob = self._memobj.vfob
1092
        _wmchannel = self._memobj.wmchannel
1093
        basic = RadioSettingGroup("basic", "Basic Settings")
1094
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
1095

    
1096
        group = RadioSettings(basic, advanced)
1097

    
1098
        rs = RadioSetting("squelch", "Carrier Squelch Level",
1099
                          RadioSettingValueInteger(0, 9, _settings.squelch))
1100
        basic.append(rs)
1101

    
1102
        rs = RadioSetting("save", "Battery Saver",
1103
                          RadioSettingValueList(
1104
                              SAVE_LIST, SAVE_LIST[_settings.save]))
1105
        basic.append(rs)
1106

    
1107
        rs = RadioSetting("vox", "VOX Sensitivity",
1108
                          RadioSettingValueList(
1109
                              VOX_LIST, VOX_LIST[_settings.vox]))
1110
        advanced.append(rs)
1111

    
1112
        if self.MODEL == "UV-6":
1113
            # NOTE: The UV-6 calls this byte voxenable, but the UV-5R calls it
1114
            # autolk. Since this is a minor difference, it will be referred to
1115
            # by the wrong name for the UV-6.
1116
            rs = RadioSetting("autolk", "Vox",
1117
                              RadioSettingValueBoolean(_settings.autolk))
1118
            advanced.append(rs)
1119

    
1120
        if self.MODEL != "UV-6":
1121
            rs = RadioSetting("abr", "Backlight Timeout",
1122
                              RadioSettingValueInteger(0, 24, _settings.abr))
1123
            basic.append(rs)
1124

    
1125
        rs = RadioSetting("tdr", "Dual Watch",
1126
                          RadioSettingValueBoolean(_settings.tdr))
1127
        advanced.append(rs)
1128

    
1129
        if self.MODEL == "UV-6":
1130
            rs = RadioSetting("tdrch", "Dual Watch Channel",
1131
                              RadioSettingValueList(
1132
                                  TDRCH_LIST, TDRCH_LIST[_settings.tdrch]))
1133
            advanced.append(rs)
1134

    
1135
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1136
                              RadioSettingValueBoolean(_settings.tdrab))
1137
            advanced.append(rs)
1138
        else:
1139
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1140
                              RadioSettingValueList(
1141
                                  TDRAB_LIST, TDRAB_LIST[_settings.tdrab]))
1142
            advanced.append(rs)
1143

    
1144
        if self.MODEL == "UV-6":
1145
            rs = RadioSetting("alarm", "Alarm Sound",
1146
                              RadioSettingValueBoolean(_settings.alarm))
1147
            advanced.append(rs)
1148

    
1149
        if _settings.almod > 0x02:
1150
            val = 0x01
1151
        else:
1152
            val = _settings.almod
1153
        rs = RadioSetting("almod", "Alarm Mode",
1154
                          RadioSettingValueList(
1155
                              ALMOD_LIST, ALMOD_LIST[val]))
1156
        advanced.append(rs)
1157

    
1158
        rs = RadioSetting("beep", "Beep",
1159
                          RadioSettingValueBoolean(_settings.beep))
1160
        basic.append(rs)
1161

    
1162
        rs = RadioSetting("timeout", "Timeout Timer",
1163
                          RadioSettingValueList(
1164
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
1165
        basic.append(rs)
1166

    
1167
        if self._is_orig() and self._my_version() < 251:
1168
            rs = RadioSetting("voice", "Voice",
1169
                              RadioSettingValueBoolean(_settings.voice))
1170
            advanced.append(rs)
1171
        else:
1172
            if self.MODEL != "TI-F8+":
1173
                rs = RadioSetting("voice", "Voice",
1174
                                  RadioSettingValueList(
1175
                                      VOICE_LIST, VOICE_LIST[_settings.voice]))
1176
                advanced.append(rs)
1177

    
1178
        rs = RadioSetting("screv", "Scan Resume",
1179
                          RadioSettingValueList(
1180
                              RESUME_LIST, RESUME_LIST[_settings.screv]))
1181
        advanced.append(rs)
1182

    
1183
        if self.MODEL != "UV-6":
1184
            rs = RadioSetting("mdfa", "Display Mode (A)",
1185
                              RadioSettingValueList(
1186
                                  MODE_LIST, MODE_LIST[_settings.mdfa]))
1187
            basic.append(rs)
1188

    
1189
            rs = RadioSetting("mdfb", "Display Mode (B)",
1190
                              RadioSettingValueList(
1191
                                  MODE_LIST, MODE_LIST[_settings.mdfb]))
1192
            basic.append(rs)
1193

    
1194
        rs = RadioSetting("bcl", "Busy Channel Lockout",
1195
                          RadioSettingValueBoolean(_settings.bcl))
1196
        advanced.append(rs)
1197

    
1198
        if self.MODEL != "UV-6":
1199
            rs = RadioSetting("autolk", "Automatic Key Lock",
1200
                              RadioSettingValueBoolean(_settings.autolk))
1201
            advanced.append(rs)
1202

    
1203
        rs = RadioSetting("fmradio", "Broadcast FM Radio",
1204
                          RadioSettingValueBoolean(_settings.fmradio))
1205
        advanced.append(rs)
1206

    
1207
        if self.MODEL != "UV-6":
1208
            rs = RadioSetting("wtled", "Standby LED Color",
1209
                              RadioSettingValueList(
1210
                                  COLOR_LIST, COLOR_LIST[_settings.wtled]))
1211
            basic.append(rs)
1212

    
1213
            rs = RadioSetting("rxled", "RX LED Color",
1214
                              RadioSettingValueList(
1215
                                  COLOR_LIST, COLOR_LIST[_settings.rxled]))
1216
            basic.append(rs)
1217

    
1218
            rs = RadioSetting("txled", "TX LED Color",
1219
                              RadioSettingValueList(
1220
                                  COLOR_LIST, COLOR_LIST[_settings.txled]))
1221
            basic.append(rs)
1222

    
1223
        if isinstance(self, BaofengUV82Radio):
1224
            rs = RadioSetting("roger", "Roger Beep (TX)",
1225
                              RadioSettingValueBoolean(_settings.roger))
1226
            basic.append(rs)
1227
            rs = RadioSetting("rogerrx", "Roger Beep (RX)",
1228
                              RadioSettingValueList(
1229
                                  ROGERRX_LIST,
1230
                                  ROGERRX_LIST[_settings.rogerrx]))
1231
            basic.append(rs)
1232
        else:
1233
            rs = RadioSetting("roger", "Roger Beep",
1234
                              RadioSettingValueBoolean(_settings.roger))
1235
            basic.append(rs)
1236

    
1237
        rs = RadioSetting("ste", "Squelch Tail Eliminate (HT to HT)",
1238
                          RadioSettingValueBoolean(_settings.ste))
1239
        advanced.append(rs)
1240

    
1241
        rs = RadioSetting("rpste", "Squelch Tail Eliminate (repeater)",
1242
                          RadioSettingValueList(
1243
                              RPSTE_LIST, RPSTE_LIST[_settings.rpste]))
1244
        advanced.append(rs)
1245

    
1246
        rs = RadioSetting("rptrl", "STE Repeater Delay",
1247
                          RadioSettingValueList(
1248
                              STEDELAY_LIST, STEDELAY_LIST[_settings.rptrl]))
1249
        advanced.append(rs)
1250

    
1251
        if self.MODEL != "UV-6":
1252
            rs = RadioSetting("reset", "RESET Menu",
1253
                              RadioSettingValueBoolean(_settings.reset))
1254
            advanced.append(rs)
1255

    
1256
            rs = RadioSetting("menu", "All Menus",
1257
                              RadioSettingValueBoolean(_settings.menu))
1258
            advanced.append(rs)
1259

    
1260
        if self.MODEL == "F-11":
1261
            # this is an F-11 only feature
1262
            rs = RadioSetting("vfomrlock", "VFO/MR Button",
1263
                              RadioSettingValueBoolean(_settings.vfomrlock))
1264
            advanced.append(rs)
1265

    
1266
        if isinstance(self, BaofengUV82Radio):
1267
            # this is a UV-82C only feature
1268
            rs = RadioSetting("vfomrlock", "VFO/MR Switching (UV-82C only)",
1269
                              RadioSettingValueBoolean(_settings.vfomrlock))
1270
            advanced.append(rs)
1271

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

    
1279
        if isinstance(self, BaofengUV82Radio):
1280
            # this is an UV-82C only feature
1281
            rs = RadioSetting("singleptt", "Single PTT (UV-82C only)",
1282
                              RadioSettingValueBoolean(_settings.singleptt))
1283
            advanced.append(rs)
1284

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

    
1291
        if self.MODEL == "UV-82HP":
1292
            # this is an UV-82HP only feature
1293
            rs = RadioSetting(
1294
                "tdrch", "Tone Burst Frequency (BTech UV-82HP only)",
1295
                RadioSettingValueList(RTONE_LIST, RTONE_LIST[_settings.tdrch]))
1296
            advanced.append(rs)
1297

    
1298
        if len(self._mmap.get_packed()) == 0x1808:
1299
            # Old image, without aux block
1300
            return group
1301

    
1302
        if self.MODEL != "UV-6":
1303
            other = RadioSettingGroup("other", "Other Settings")
1304
            group.append(other)
1305

    
1306
            def _filter(name):
1307
                filtered = ""
1308
                for char in str(name):
1309
                    if char in chirp_common.CHARSET_ASCII:
1310
                        filtered += char
1311
                    else:
1312
                        filtered += " "
1313
                return filtered
1314

    
1315
            _msg = self._memobj.firmware_msg
1316
            val = RadioSettingValueString(0, 7, _filter(_msg.line1))
1317
            val.set_mutable(False)
1318
            rs = RadioSetting("firmware_msg.line1", "Firmware Message 1", val)
1319
            other.append(rs)
1320

    
1321
            val = RadioSettingValueString(0, 7, _filter(_msg.line2))
1322
            val.set_mutable(False)
1323
            rs = RadioSetting("firmware_msg.line2", "Firmware Message 2", val)
1324
            other.append(rs)
1325

    
1326
            _msg = self._memobj.sixpoweron_msg
1327
            rs = RadioSetting("sixpoweron_msg.line1", "6+Power-On Message 1",
1328
                              RadioSettingValueString(
1329
                                  0, 7, _filter(_msg.line1)))
1330
            other.append(rs)
1331
            rs = RadioSetting("sixpoweron_msg.line2", "6+Power-On Message 2",
1332
                              RadioSettingValueString(
1333
                                  0, 7, _filter(_msg.line2)))
1334
            other.append(rs)
1335

    
1336
            _msg = self._memobj.poweron_msg
1337
            rs = RadioSetting("poweron_msg.line1", "Power-On Message 1",
1338
                              RadioSettingValueString(
1339
                                  0, 7, _filter(_msg.line1)))
1340
            other.append(rs)
1341
            rs = RadioSetting("poweron_msg.line2", "Power-On Message 2",
1342
                              RadioSettingValueString(
1343
                                  0, 7, _filter(_msg.line2)))
1344
            other.append(rs)
1345

    
1346
            rs = RadioSetting("ponmsg", "Power-On Message",
1347
                              RadioSettingValueList(
1348
                                  PONMSG_LIST, PONMSG_LIST[_settings.ponmsg]))
1349
            other.append(rs)
1350

    
1351
            if self._is_orig():
1352
                limit = "limits_old"
1353
            else:
1354
                limit = "limits_new"
1355

    
1356
            vhf_limit = getattr(self._memobj, limit).vhf
1357
            rs = RadioSetting("%s.vhf.lower" % limit, "VHF Lower Limit (MHz)",
1358
                              RadioSettingValueInteger(1, 1000,
1359
                                                       vhf_limit.lower))
1360
            other.append(rs)
1361

    
1362
            rs = RadioSetting("%s.vhf.upper" % limit, "VHF Upper Limit (MHz)",
1363
                              RadioSettingValueInteger(1, 1000,
1364
                                                       vhf_limit.upper))
1365
            other.append(rs)
1366

    
1367
            rs = RadioSetting("%s.vhf.enable" % limit, "VHF TX Enabled",
1368
                              RadioSettingValueBoolean(vhf_limit.enable))
1369
            other.append(rs)
1370

    
1371
            uhf_limit = getattr(self._memobj, limit).uhf
1372
            rs = RadioSetting("%s.uhf.lower" % limit, "UHF Lower Limit (MHz)",
1373
                              RadioSettingValueInteger(1, 1000,
1374
                                                       uhf_limit.lower))
1375
            other.append(rs)
1376
            rs = RadioSetting("%s.uhf.upper" % limit, "UHF Upper Limit (MHz)",
1377
                              RadioSettingValueInteger(1, 1000,
1378
                                                       uhf_limit.upper))
1379
            other.append(rs)
1380
            rs = RadioSetting("%s.uhf.enable" % limit, "UHF TX Enabled",
1381
                              RadioSettingValueBoolean(uhf_limit.enable))
1382
            other.append(rs)
1383

    
1384
        if self.MODEL != "UV-6":
1385
            workmode = RadioSettingGroup("workmode", "Work Mode Settings")
1386
            group.append(workmode)
1387

    
1388
            rs = RadioSetting("displayab", "Display",
1389
                              RadioSettingValueList(
1390
                                  AB_LIST, AB_LIST[_settings.displayab]))
1391
            workmode.append(rs)
1392

    
1393
            rs = RadioSetting("workmode", "VFO/MR Mode",
1394
                              RadioSettingValueList(
1395
                                  WORKMODE_LIST,
1396
                                  WORKMODE_LIST[_settings.workmode]))
1397
            workmode.append(rs)
1398

    
1399
            rs = RadioSetting("keylock", "Keypad Lock",
1400
                              RadioSettingValueBoolean(_settings.keylock))
1401
            workmode.append(rs)
1402

    
1403
            rs = RadioSetting("wmchannel.mrcha", "MR A Channel",
1404
                              RadioSettingValueInteger(0, 127,
1405
                                                       _wmchannel.mrcha))
1406
            workmode.append(rs)
1407

    
1408
            rs = RadioSetting("wmchannel.mrchb", "MR B Channel",
1409
                              RadioSettingValueInteger(0, 127,
1410
                                                       _wmchannel.mrchb))
1411
            workmode.append(rs)
1412

    
1413
            def convert_bytes_to_freq(bytes):
1414
                real_freq = 0
1415
                for byte in bytes:
1416
                    real_freq = (real_freq * 10) + byte
1417
                return chirp_common.format_freq(real_freq * 10)
1418

    
1419
            def my_validate(value):
1420
                value = chirp_common.parse_freq(value)
1421
                if 17400000 <= value and value < 40000000:
1422
                    msg = ("Can't be between 174.00000-400.00000")
1423
                    raise InvalidValueError(msg)
1424
                return chirp_common.format_freq(value)
1425

    
1426
            def apply_freq(setting, obj):
1427
                value = chirp_common.parse_freq(str(setting.value)) / 10
1428
                obj.band = value >= 40000000
1429
                for i in range(7, -1, -1):
1430
                    obj.freq[i] = value % 10
1431
                    value /= 10
1432

    
1433
            val1a = RadioSettingValueString(0, 10,
1434
                                            convert_bytes_to_freq(_vfoa.freq))
1435
            val1a.set_validate_callback(my_validate)
1436
            rs = RadioSetting("vfoa.freq", "VFO A Frequency", val1a)
1437
            rs.set_apply_callback(apply_freq, _vfoa)
1438
            workmode.append(rs)
1439

    
1440
            val1b = RadioSettingValueString(0, 10,
1441
                                            convert_bytes_to_freq(_vfob.freq))
1442
            val1b.set_validate_callback(my_validate)
1443
            rs = RadioSetting("vfob.freq", "VFO B Frequency", val1b)
1444
            rs.set_apply_callback(apply_freq, _vfob)
1445
            workmode.append(rs)
1446

    
1447
            rs = RadioSetting("vfoa.sftd", "VFO A Shift",
1448
                              RadioSettingValueList(
1449
                                  SHIFTD_LIST, SHIFTD_LIST[_vfoa.sftd]))
1450
            workmode.append(rs)
1451

    
1452
            rs = RadioSetting("vfob.sftd", "VFO B Shift",
1453
                              RadioSettingValueList(
1454
                                  SHIFTD_LIST, SHIFTD_LIST[_vfob.sftd]))
1455
            workmode.append(rs)
1456

    
1457
            def convert_bytes_to_offset(bytes):
1458
                real_offset = 0
1459
                for byte in bytes:
1460
                    real_offset = (real_offset * 10) + byte
1461
                return chirp_common.format_freq(real_offset * 1000)
1462

    
1463
            def apply_offset(setting, obj):
1464
                value = chirp_common.parse_freq(str(setting.value)) / 1000
1465
                for i in range(5, -1, -1):
1466
                    obj.offset[i] = value % 10
1467
                    value /= 10
1468

    
1469
            val1a = RadioSettingValueString(
1470
                0, 10, convert_bytes_to_offset(_vfoa.offset))
1471
            rs = RadioSetting("vfoa.offset",
1472
                              "VFO A Offset (0.0-999.999)", val1a)
1473
            rs.set_apply_callback(apply_offset, _vfoa)
1474
            workmode.append(rs)
1475

    
1476
            val1b = RadioSettingValueString(
1477
                0, 10, convert_bytes_to_offset(_vfob.offset))
1478
            rs = RadioSetting("vfob.offset",
1479
                              "VFO B Offset (0.0-999.999)", val1b)
1480
            rs.set_apply_callback(apply_offset, _vfob)
1481
            workmode.append(rs)
1482

    
1483
            if self._tri_power:
1484
                rs = RadioSetting("vfoa.txpower3", "VFO A Power",
1485
                                  RadioSettingValueList(
1486
                                      TXPOWER3_LIST,
1487
                                      TXPOWER3_LIST[_vfoa.txpower3]))
1488
                workmode.append(rs)
1489

    
1490
                rs = RadioSetting("vfob.txpower3", "VFO B Power",
1491
                                  RadioSettingValueList(
1492
                                      TXPOWER3_LIST,
1493
                                      TXPOWER3_LIST[_vfob.txpower3]))
1494
                workmode.append(rs)
1495
            else:
1496
                rs = RadioSetting("vfoa.txpower", "VFO A Power",
1497
                                  RadioSettingValueList(
1498
                                      TXPOWER_LIST,
1499
                                      TXPOWER_LIST[_vfoa.txpower]))
1500
                workmode.append(rs)
1501

    
1502
                rs = RadioSetting("vfob.txpower", "VFO B Power",
1503
                                  RadioSettingValueList(
1504
                                      TXPOWER_LIST,
1505
                                      TXPOWER_LIST[_vfob.txpower]))
1506
                workmode.append(rs)
1507

    
1508
            rs = RadioSetting("vfoa.widenarr", "VFO A Bandwidth",
1509
                              RadioSettingValueList(
1510
                                  BANDWIDTH_LIST,
1511
                                  BANDWIDTH_LIST[_vfoa.widenarr]))
1512
            workmode.append(rs)
1513

    
1514
            rs = RadioSetting("vfob.widenarr", "VFO B Bandwidth",
1515
                              RadioSettingValueList(
1516
                                  BANDWIDTH_LIST,
1517
                                  BANDWIDTH_LIST[_vfob.widenarr]))
1518
            workmode.append(rs)
1519

    
1520
            rs = RadioSetting("vfoa.scode", "VFO A PTT-ID",
1521
                              RadioSettingValueList(
1522
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfoa.scode]))
1523
            workmode.append(rs)
1524

    
1525
            rs = RadioSetting("vfob.scode", "VFO B PTT-ID",
1526
                              RadioSettingValueList(
1527
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfob.scode]))
1528
            workmode.append(rs)
1529

    
1530
            if not self._is_orig():
1531
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1532
                                  RadioSettingValueList(
1533
                                      STEP291_LIST, STEP291_LIST[_vfoa.step]))
1534
                workmode.append(rs)
1535
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1536
                                  RadioSettingValueList(
1537
                                      STEP291_LIST, STEP291_LIST[_vfob.step]))
1538
                workmode.append(rs)
1539
            else:
1540
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1541
                                  RadioSettingValueList(
1542
                                      STEP_LIST, STEP_LIST[_vfoa.step]))
1543
                workmode.append(rs)
1544
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1545
                                  RadioSettingValueList(
1546
                                      STEP_LIST, STEP_LIST[_vfob.step]))
1547
                workmode.append(rs)
1548

    
1549
        fm_preset = RadioSettingGroup("fm_preset", "FM Radio Preset")
1550
        group.append(fm_preset)
1551

    
1552
        if _fm_presets <= 108.0 * 10 - 650:
1553
            preset = _fm_presets / 10.0 + 65
1554
        elif _fm_presets >= 65.0 * 10 and _fm_presets <= 108.0 * 10:
1555
            preset = _fm_presets / 10.0
1556
        else:
1557
            preset = 76.0
1558
        rs = RadioSetting("fm_presets", "FM Preset(MHz)",
1559
                          RadioSettingValueFloat(65, 108.0, preset, 0.1, 1))
1560
        fm_preset.append(rs)
1561

    
1562
        dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
1563
        group.append(dtmf)
1564

    
1565
        if str(self._memobj.firmware_msg.line1) == "HN5RV01":
1566
            dtmfchars = "0123456789ABCD*#"
1567
        else:
1568
            dtmfchars = "0123456789 *#ABCD"
1569

    
1570
        for i in range(0, 15):
1571
            _codeobj = self._memobj.pttid[i].code
1572
            _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1573
            val = RadioSettingValueString(0, 5, _code, False)
1574
            val.set_charset(dtmfchars)
1575
            rs = RadioSetting("pttid/%i.code" % i,
1576
                              "PTT ID Code %i" % (i + 1), val)
1577

    
1578
            def apply_code(setting, obj):
1579
                code = []
1580
                for j in range(0, 5):
1581
                    try:
1582
                        code.append(dtmfchars.index(str(setting.value)[j]))
1583
                    except IndexError:
1584
                        code.append(0xFF)
1585
                obj.code = code
1586
            rs.set_apply_callback(apply_code, self._memobj.pttid[i])
1587
            dtmf.append(rs)
1588

    
1589
        dtmfcharsani = "0123456789"
1590

    
1591
        _codeobj = self._memobj.ani.code
1592
        _code = "".join([dtmfcharsani[x] for x in _codeobj if int(x) < 0x1F])
1593
        val = RadioSettingValueString(0, 5, _code, False)
1594
        val.set_charset(dtmfcharsani)
1595
        rs = RadioSetting("ani.code", "ANI Code", val)
1596

    
1597
        def apply_code(setting, obj):
1598
            code = []
1599
            for j in range(0, 5):
1600
                try:
1601
                    code.append(dtmfchars.index(str(setting.value)[j]))
1602
                except IndexError:
1603
                    code.append(0xFF)
1604
            obj.code = code
1605
        rs.set_apply_callback(apply_code, _ani)
1606
        dtmf.append(rs)
1607

    
1608
        rs = RadioSetting("ani.aniid", "ANI ID",
1609
                          RadioSettingValueList(PTTID_LIST,
1610
                                                PTTID_LIST[_ani.aniid]))
1611
        dtmf.append(rs)
1612

    
1613
        _codeobj = self._memobj.ani.alarmcode
1614
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1615
        val = RadioSettingValueString(0, 3, _code, False)
1616
        val.set_charset(dtmfchars)
1617
        rs = RadioSetting("ani.alarmcode", "Alarm Code", val)
1618

    
1619
        def apply_code(setting, obj):
1620
            alarmcode = []
1621
            for j in range(0, 3):
1622
                try:
1623
                    alarmcode.append(dtmfchars.index(str(setting.value)[j]))
1624
                except IndexError:
1625
                    alarmcode.append(0xFF)
1626
            obj.alarmcode = alarmcode
1627
        rs.set_apply_callback(apply_code, _ani)
1628
        dtmf.append(rs)
1629

    
1630
        rs = RadioSetting("dtmfst", "DTMF Sidetone",
1631
                          RadioSettingValueList(DTMFST_LIST,
1632
                                                DTMFST_LIST[_settings.dtmfst]))
1633
        dtmf.append(rs)
1634

    
1635
        if _ani.dtmfon > 0xC3:
1636
            val = 0x00
1637
        else:
1638
            val = _ani.dtmfon
1639
        rs = RadioSetting("ani.dtmfon", "DTMF Speed (on)",
1640
                          RadioSettingValueList(DTMFSPEED_LIST,
1641
                                                DTMFSPEED_LIST[val]))
1642
        dtmf.append(rs)
1643

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

    
1653
        rs = RadioSetting("pttlt", "PTT ID Delay",
1654
                          RadioSettingValueInteger(0, 50, _settings.pttlt))
1655
        dtmf.append(rs)
1656

    
1657
        if not self._is_orig() and self._aux_block:
1658
            service = RadioSettingGroup("service", "Service Settings")
1659
            group.append(service)
1660

    
1661
            for band in ["vhf", "uhf"]:
1662
                for index in range(0, 10):
1663
                    key = "squelch_new.%s.sql%i" % (band, index)
1664
                    if band == "vhf":
1665
                        _obj = self._memobj.squelch_new.vhf
1666
                    elif band == "uhf":
1667
                        _obj = self._memobj.squelch_new.uhf
1668
                    name = "%s Squelch %i" % (band.upper(), index)
1669
                    rs = RadioSetting(key, name,
1670
                                      RadioSettingValueInteger(
1671
                                          0, 123,
1672
                                          getattr(_obj, "sql%i" % (index))))
1673
                    service.append(rs)
1674

    
1675
        return group
1676

    
1677
    def get_settings(self):
1678
        try:
1679
            return self._get_settings()
1680
        except:
1681
            import traceback
1682
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1683
            return None
1684

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

    
1712
                    if element.has_apply_callback():
1713
                        LOG.debug("Using apply callback")
1714
                        element.run_apply_callback()
1715
                    elif element.value.get_mutable():
1716
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1717
                        setattr(obj, setting, element.value)
1718
                except Exception, e:
1719
                    LOG.debug(element.get_name())
1720
                    raise
1721

    
1722
    def _set_fm_preset(self, settings):
1723
        for element in settings:
1724
            try:
1725
                val = element.value
1726
                if self._memobj.fm_presets <= 108.0 * 10 - 650:
1727
                    value = int(val.get_value() * 10 - 650)
1728
                else:
1729
                    value = int(val.get_value() * 10)
1730
                LOG.debug("Setting fm_presets = %s" % (value))
1731
                self._memobj.fm_presets = value
1732
            except Exception, e:
1733
                LOG.debug(element.get_name())
1734
                raise
1735

    
1736

    
1737
class UV5XAlias(chirp_common.Alias):
1738
    VENDOR = "Baofeng"
1739
    MODEL = "UV-5X"
1740

    
1741

    
1742
class RT5RAlias(chirp_common.Alias):
1743
    VENDOR = "Retevis"
1744
    MODEL = "RT-5R"
1745

    
1746

    
1747
class RT5RVAlias(chirp_common.Alias):
1748
    VENDOR = "Retevis"
1749
    MODEL = "RT-5RV"
1750

    
1751

    
1752
class RT5Alias(chirp_common.Alias):
1753
    VENDOR = "Retevis"
1754
    MODEL = "RT5"
1755

    
1756

    
1757
class RT5_TPAlias(chirp_common.Alias):
1758
    VENDOR = "Retevis"
1759
    MODEL = "RT5(tri-power)"
1760

    
1761

    
1762
class RH5RAlias(chirp_common.Alias):
1763
    VENDOR = "Rugged"
1764
    MODEL = "RH5R"
1765

    
1766

    
1767
class ROUV5REXAlias(chirp_common.Alias):
1768
    VENDOR = "Radioddity"
1769
    MODEL = "UV-5R EX"
1770

    
1771

    
1772
class A5RAlias(chirp_common.Alias):
1773
    VENDOR = "Ansoko"
1774
    MODEL = "A-5R"
1775

    
1776

    
1777
@directory.register
1778
class BaofengUV5RGeneric(BaofengUV5R):
1779
    ALIASES = [UV5XAlias, RT5RAlias, RT5RVAlias, RT5Alias, RH5RAlias,
1780
               ROUV5REXAlias, A5RAlias]
1781

    
1782

    
1783
@directory.register
1784
class BaofengF11Radio(BaofengUV5R):
1785
    VENDOR = "Baofeng"
1786
    MODEL = "F-11"
1787
    _basetype = BASETYPE_F11
1788
    _idents = [UV5R_MODEL_F11]
1789

    
1790
    def _is_orig(self):
1791
        # Override this for F11 to always return False
1792
        return False
1793

    
1794

    
1795
@directory.register
1796
class BaofengUV82Radio(BaofengUV5R):
1797
    MODEL = "UV-82"
1798
    _basetype = BASETYPE_UV82
1799
    _idents = [UV5R_MODEL_UV82]
1800
    _vhf_range = (130000000, 176000000)
1801
    _uhf_range = (400000000, 521000000)
1802
    _valid_chars = chirp_common.CHARSET_ASCII
1803

    
1804
    def _is_orig(self):
1805
        # Override this for UV82 to always return False
1806
        return False
1807

    
1808

    
1809
@directory.register
1810
class Radioddity82X3Radio(BaofengUV82Radio):
1811
    VENDOR = "Radioddity"
1812
    MODEL = "UV-82X3"
1813
    _basetype = BASETYPE_UV82X3
1814

    
1815
    def get_features(self):
1816
        rf = BaofengUV5R.get_features(self)
1817
        rf.valid_bands = [self._vhf_range,
1818
                          (200000000, 260000000),
1819
                          self._uhf_range]
1820
        return rf
1821

    
1822

    
1823
@directory.register
1824
class BaofengUV6Radio(BaofengUV5R):
1825

    
1826
    """Baofeng UV-6/UV-7"""
1827
    VENDOR = "Baofeng"
1828
    MODEL = "UV-6"
1829
    _basetype = BASETYPE_UV6
1830
    _idents = [UV5R_MODEL_UV6,
1831
               UV5R_MODEL_UV6_ORIG
1832
               ]
1833
    _aux_block = False
1834

    
1835
    def get_features(self):
1836
        rf = BaofengUV5R.get_features(self)
1837
        rf.memory_bounds = (1, 128)
1838
        return rf
1839

    
1840
    def _get_mem(self, number):
1841
        return self._memobj.memory[number - 1]
1842

    
1843
    def _get_nam(self, number):
1844
        return self._memobj.names[number - 1]
1845

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

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

    
1852
    def _is_orig(self):
1853
        # Override this for UV6 to always return False
1854
        return False
1855

    
1856

    
1857
@directory.register
1858
class IntekKT980Radio(BaofengUV5R):
1859
    VENDOR = "Intek"
1860
    MODEL = "KT-980HP"
1861
    _basetype = BASETYPE_KT980HP
1862
    _idents = [UV5R_MODEL_291]
1863
    _vhf_range = (130000000, 180000000)
1864
    _uhf_range = (400000000, 521000000)
1865
    _tri_power = True
1866

    
1867
    def get_features(self):
1868
        rf = BaofengUV5R.get_features(self)
1869
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1870
        return rf
1871

    
1872
    def _is_orig(self):
1873
        # Override this for KT980HP to always return False
1874
        return False
1875

    
1876

    
1877
class ROGA5SAlias(chirp_common.Alias):
1878
    VENDOR = "Radioddity"
1879
    MODEL = "GA-5S"
1880

    
1881

    
1882
class UV5XPAlias(chirp_common.Alias):
1883
    VENDOR = "Baofeng"
1884
    MODEL = "UV-5XP"
1885

    
1886

    
1887
class TSTIF8Alias(chirp_common.Alias):
1888
    VENDOR = "TechSide"
1889
    MODEL = "TI-F8+"
1890

    
1891

    
1892
class TenwayUV5RPro(chirp_common.Alias):
1893
    VENDOR = 'Tenway'
1894
    MODEL = 'UV-5R Pro'
1895

    
1896

    
1897
@directory.register
1898
class BaofengBFF8HPRadio(BaofengUV5R):
1899
    VENDOR = "Baofeng"
1900
    MODEL = "BF-F8HP"
1901
    ALIASES = [RT5_TPAlias, ROGA5SAlias, UV5XPAlias, TSTIF8Alias,
1902
               TenwayUV5RPro]
1903
    _basetype = BASETYPE_F8HP
1904
    _idents = [UV5R_MODEL_291,
1905
               UV5R_MODEL_A58
1906
               ]
1907
    _vhf_range = (130000000, 180000000)
1908
    _uhf_range = (400000000, 521000000)
1909
    _tri_power = True
1910

    
1911
    def get_features(self):
1912
        rf = BaofengUV5R.get_features(self)
1913
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1914
        return rf
1915

    
1916
    def _is_orig(self):
1917
        # Override this for BFF8HP to always return False
1918
        return False
1919

    
1920

    
1921
class TenwayUV82Pro(chirp_common.Alias):
1922
    VENDOR = 'Tenway'
1923
    MODEL = 'UV-82 Pro'
1924

    
1925

    
1926
@directory.register
1927
class BaofengUV82HPRadio(BaofengUV5R):
1928
    VENDOR = "Baofeng"
1929
    MODEL = "UV-82HP"
1930
    ALIASES = [TenwayUV82Pro]
1931
    _basetype = BASETYPE_UV82HP
1932
    _idents = [UV5R_MODEL_UV82]
1933
    _vhf_range = (136000000, 175000000)
1934
    _uhf_range = (400000000, 521000000)
1935
    _tri_power = True
1936

    
1937
    def get_features(self):
1938
        rf = BaofengUV5R.get_features(self)
1939
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1940
        return rf
1941

    
1942
    def _is_orig(self):
1943
        # Override this for UV82HP to always return False
1944
        return False
1945

    
1946

    
1947
class TDUV5RRadio(chirp_common.Alias):
1948
    VENDOR = "TIDRADIO"
1949
    MODEL = "TD-UV5R TriPower"
1950

    
1951

    
1952
@directory.register
1953
class RadioddityUV5RX3Radio(BaofengUV5R):
1954
    VENDOR = "Radioddity"
1955
    MODEL = "UV-5RX3"
1956
    ALIASES = [TDUV5RRadio]
1957

    
1958
    def get_features(self):
1959
        rf = BaofengUV5R.get_features(self)
1960
        rf.valid_bands = [self._vhf_range,
1961
                          (200000000, 260000000),
1962
                          self._uhf_range]
1963
        return rf
1964

    
1965
    @classmethod
1966
    def match_model(cls, filename, filedata):
1967
        return False
    (1-1/1)