Project

General

Profile

Bug #9187 » uv5r_uv5x.py

Jim Unroe, 07/09/2021 06:38 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_291 = "\x50\xBB\xFF\x20\x12\x06\x25"
368
UV5R_MODEL_F11 = "\x50\xBB\xFF\x13\xA1\x11\xDD"
369
UV5R_MODEL_UV82 = "\x50\xBB\xFF\x20\x13\x01\x05"
370
UV5R_MODEL_UV6 = "\x50\xBB\xFF\x20\x12\x08\x23"
371
UV5R_MODEL_UV6_ORIG = "\x50\xBB\xFF\x12\x03\x98\x4D"
372
UV5R_MODEL_A58 = "\x50\xBB\xFF\x20\x14\x04\x13"
373

    
374

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

    
378

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

    
382

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

    
387

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

    
395

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

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

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

    
411
    serial.write("\x02")
412

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

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

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

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

    
455
    return ident
456

    
457

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

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

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

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

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

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

    
488
    return chunk
489

    
490

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

    
502

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

    
507

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

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

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

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

    
538

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

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

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

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

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

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

    
595

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

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

    
605

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
697

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

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

    
711

    
712
class BaofengUV5R(chirp_common.CloneModeRadio):
713

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

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

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

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

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

    
789
        normal_bands = [self._vhf_range, self._uhf_range]
790
        rax_bands = [self._vhf_range, self._220_range]
791

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

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

    
809
        if match_size and match_model:
810
            return True
811
        else:
812
            return False
813

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

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

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

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

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

    
843
    def _get_mem(self, number):
844
        return self._memobj.memory[number]
845

    
846
    def _get_nam(self, number):
847
        return self._memobj.names[number]
848

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

    
853
        mem = chirp_common.Memory()
854
        mem.number = number
855

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

    
860
        mem.freq = int(_mem.rxfreq) * 10
861

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

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

    
881
        dtcs_pol = ["N", "N"]
882

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

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

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

    
925
        mem.dtcs_polarity = "".join(dtcs_pol)
926

    
927
        if not _mem.scan:
928
            mem.skip = "S"
929

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

    
941
        mem.mode = _mem.wide and "FM" or "NFM"
942

    
943
        mem.extra = RadioSettingGroup("Extra", "extra")
944

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

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

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

    
959
        return mem
960

    
961
    def _set_mem(self, number):
962
        return self._memobj.memory[number]
963

    
964
    def _set_nam(self, number):
965
        return self._memobj.names[number]
966

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

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

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

    
990
        _mem.set_raw("\x00" * 16)
991

    
992
        _mem.rxfreq = mem.freq / 10
993

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

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

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

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

    
1047
        _mem.scan = mem.skip != "S"
1048
        _mem.wide = mem.mode == "FM"
1049

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

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

    
1065
        for setting in mem.extra:
1066
            setattr(_mem, setting.get_name(), setting.value)
1067

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

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

    
1088
        raise Exception("Unrecognized firmware version string")
1089

    
1090
    def _my_upper_band(self):
1091
        band_tag = _upper_band_from_image(self)
1092
        return band_tag
1093

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

    
1105
        group = RadioSettings(basic, advanced)
1106

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1492
            if self._tri_power:
1493
                if _vfoa.txpower3 > 0x02:
1494
                    val = 0x00
1495
                else:
1496
                    val = _vfoa.txpower3
1497
                rs = RadioSetting("vfoa.txpower3", "VFO A Power",
1498
                                  RadioSettingValueList(
1499
                                      TXPOWER3_LIST,
1500
                                      TXPOWER3_LIST[val]))
1501
                workmode.append(rs)
1502

    
1503
                if _vfob.txpower3 > 0x02:
1504
                    val = 0x00
1505
                else:
1506
                    val = _vfob.txpower3
1507
                rs = RadioSetting("vfob.txpower3", "VFO B Power",
1508
                                  RadioSettingValueList(
1509
                                      TXPOWER3_LIST,
1510
                                      TXPOWER3_LIST[val]))
1511
                workmode.append(rs)
1512
            else:
1513
                rs = RadioSetting("vfoa.txpower", "VFO A Power",
1514
                                  RadioSettingValueList(
1515
                                      TXPOWER_LIST,
1516
                                      TXPOWER_LIST[_vfoa.txpower]))
1517
                workmode.append(rs)
1518

    
1519
                rs = RadioSetting("vfob.txpower", "VFO B Power",
1520
                                  RadioSettingValueList(
1521
                                      TXPOWER_LIST,
1522
                                      TXPOWER_LIST[_vfob.txpower]))
1523
                workmode.append(rs)
1524

    
1525
            rs = RadioSetting("vfoa.widenarr", "VFO A Bandwidth",
1526
                              RadioSettingValueList(
1527
                                  BANDWIDTH_LIST,
1528
                                  BANDWIDTH_LIST[_vfoa.widenarr]))
1529
            workmode.append(rs)
1530

    
1531
            rs = RadioSetting("vfob.widenarr", "VFO B Bandwidth",
1532
                              RadioSettingValueList(
1533
                                  BANDWIDTH_LIST,
1534
                                  BANDWIDTH_LIST[_vfob.widenarr]))
1535
            workmode.append(rs)
1536

    
1537
            rs = RadioSetting("vfoa.scode", "VFO A PTT-ID",
1538
                              RadioSettingValueList(
1539
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfoa.scode]))
1540
            workmode.append(rs)
1541

    
1542
            rs = RadioSetting("vfob.scode", "VFO B PTT-ID",
1543
                              RadioSettingValueList(
1544
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfob.scode]))
1545
            workmode.append(rs)
1546

    
1547
            if not self._is_orig():
1548
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1549
                                  RadioSettingValueList(
1550
                                      STEP291_LIST, STEP291_LIST[_vfoa.step]))
1551
                workmode.append(rs)
1552
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1553
                                  RadioSettingValueList(
1554
                                      STEP291_LIST, STEP291_LIST[_vfob.step]))
1555
                workmode.append(rs)
1556
            else:
1557
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1558
                                  RadioSettingValueList(
1559
                                      STEP_LIST, STEP_LIST[_vfoa.step]))
1560
                workmode.append(rs)
1561
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1562
                                  RadioSettingValueList(
1563
                                      STEP_LIST, STEP_LIST[_vfob.step]))
1564
                workmode.append(rs)
1565

    
1566
        fm_preset = RadioSettingGroup("fm_preset", "FM Radio Preset")
1567
        group.append(fm_preset)
1568

    
1569
        if _fm_presets <= 108.0 * 10 - 650:
1570
            preset = _fm_presets / 10.0 + 65
1571
        elif _fm_presets >= 65.0 * 10 and _fm_presets <= 108.0 * 10:
1572
            preset = _fm_presets / 10.0
1573
        else:
1574
            preset = 76.0
1575
        rs = RadioSetting("fm_presets", "FM Preset(MHz)",
1576
                          RadioSettingValueFloat(65, 108.0, preset, 0.1, 1))
1577
        fm_preset.append(rs)
1578

    
1579
        dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
1580
        group.append(dtmf)
1581

    
1582
        if str(self._memobj.firmware_msg.line1) == "HN5RV01":
1583
            dtmfchars = "0123456789ABCD*#"
1584
        else:
1585
            dtmfchars = "0123456789 *#ABCD"
1586

    
1587
        for i in range(0, 15):
1588
            _codeobj = self._memobj.pttid[i].code
1589
            _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1590
            val = RadioSettingValueString(0, 5, _code, False)
1591
            val.set_charset(dtmfchars)
1592
            rs = RadioSetting("pttid/%i.code" % i,
1593
                              "PTT ID Code %i" % (i + 1), val)
1594

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

    
1606
        dtmfcharsani = "0123456789"
1607

    
1608
        _codeobj = self._memobj.ani.code
1609
        _code = "".join([dtmfcharsani[x] for x in _codeobj if int(x) < 0x1F])
1610
        val = RadioSettingValueString(0, 5, _code, False)
1611
        val.set_charset(dtmfcharsani)
1612
        rs = RadioSetting("ani.code", "ANI Code", val)
1613

    
1614
        def apply_code(setting, obj):
1615
            code = []
1616
            for j in range(0, 5):
1617
                try:
1618
                    code.append(dtmfchars.index(str(setting.value)[j]))
1619
                except IndexError:
1620
                    code.append(0xFF)
1621
            obj.code = code
1622
        rs.set_apply_callback(apply_code, _ani)
1623
        dtmf.append(rs)
1624

    
1625
        rs = RadioSetting("ani.aniid", "ANI ID",
1626
                          RadioSettingValueList(PTTID_LIST,
1627
                                                PTTID_LIST[_ani.aniid]))
1628
        dtmf.append(rs)
1629

    
1630
        _codeobj = self._memobj.ani.alarmcode
1631
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1632
        val = RadioSettingValueString(0, 3, _code, False)
1633
        val.set_charset(dtmfchars)
1634
        rs = RadioSetting("ani.alarmcode", "Alarm Code", val)
1635

    
1636
        def apply_code(setting, obj):
1637
            alarmcode = []
1638
            for j in range(0, 3):
1639
                try:
1640
                    alarmcode.append(dtmfchars.index(str(setting.value)[j]))
1641
                except IndexError:
1642
                    alarmcode.append(0xFF)
1643
            obj.alarmcode = alarmcode
1644
        rs.set_apply_callback(apply_code, _ani)
1645
        dtmf.append(rs)
1646

    
1647
        rs = RadioSetting("dtmfst", "DTMF Sidetone",
1648
                          RadioSettingValueList(DTMFST_LIST,
1649
                                                DTMFST_LIST[_settings.dtmfst]))
1650
        dtmf.append(rs)
1651

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

    
1661
        if _ani.dtmfoff > 0xC3:
1662
            val = 0x00
1663
        else:
1664
            val = _ani.dtmfoff
1665
        rs = RadioSetting("ani.dtmfoff", "DTMF Speed (off)",
1666
                          RadioSettingValueList(DTMFSPEED_LIST,
1667
                                                DTMFSPEED_LIST[val]))
1668
        dtmf.append(rs)
1669

    
1670
        rs = RadioSetting("pttlt", "PTT ID Delay",
1671
                          RadioSettingValueInteger(0, 50, _settings.pttlt))
1672
        dtmf.append(rs)
1673

    
1674
        if not self._is_orig() and self._aux_block:
1675
            service = RadioSettingGroup("service", "Service Settings")
1676
            group.append(service)
1677

    
1678
            for band in ["vhf", "uhf"]:
1679
                for index in range(0, 10):
1680
                    key = "squelch_new.%s.sql%i" % (band, index)
1681
                    if band == "vhf":
1682
                        _obj = self._memobj.squelch_new.vhf
1683
                    elif band == "uhf":
1684
                        _obj = self._memobj.squelch_new.uhf
1685
                    name = "%s Squelch %i" % (band.upper(), index)
1686
                    rs = RadioSetting(key, name,
1687
                                      RadioSettingValueInteger(
1688
                                          0, 123,
1689
                                          getattr(_obj, "sql%i" % (index))))
1690
                    service.append(rs)
1691

    
1692
        return group
1693

    
1694
    def get_settings(self):
1695
        try:
1696
            return self._get_settings()
1697
        except:
1698
            import traceback
1699
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1700
            return None
1701

    
1702
    def set_settings(self, settings):
1703
        _settings = self._memobj.settings
1704
        for element in settings:
1705
            if not isinstance(element, RadioSetting):
1706
                if element.get_name() == "fm_preset":
1707
                    self._set_fm_preset(element)
1708
                else:
1709
                    self.set_settings(element)
1710
                    continue
1711
            else:
1712
                try:
1713
                    name = element.get_name()
1714
                    if "." in name:
1715
                        bits = name.split(".")
1716
                        obj = self._memobj
1717
                        for bit in bits[:-1]:
1718
                            if "/" in bit:
1719
                                bit, index = bit.split("/", 1)
1720
                                index = int(index)
1721
                                obj = getattr(obj, bit)[index]
1722
                            else:
1723
                                obj = getattr(obj, bit)
1724
                        setting = bits[-1]
1725
                    else:
1726
                        obj = _settings
1727
                        setting = element.get_name()
1728

    
1729
                    if element.has_apply_callback():
1730
                        LOG.debug("Using apply callback")
1731
                        element.run_apply_callback()
1732
                    elif element.value.get_mutable():
1733
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1734
                        setattr(obj, setting, element.value)
1735
                except Exception, e:
1736
                    LOG.debug(element.get_name())
1737
                    raise
1738

    
1739
    def _set_fm_preset(self, settings):
1740
        for element in settings:
1741
            try:
1742
                val = element.value
1743
                if self._memobj.fm_presets <= 108.0 * 10 - 650:
1744
                    value = int(val.get_value() * 10 - 650)
1745
                else:
1746
                    value = int(val.get_value() * 10)
1747
                LOG.debug("Setting fm_presets = %s" % (value))
1748
                self._memobj.fm_presets = value
1749
            except Exception, e:
1750
                LOG.debug(element.get_name())
1751
                raise
1752

    
1753

    
1754
class UV5XAlias(chirp_common.Alias):
1755
    VENDOR = "Baofeng"
1756
    MODEL = "UV-5X"
1757

    
1758

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

    
1763

    
1764
class RT5RVAlias(chirp_common.Alias):
1765
    VENDOR = "Retevis"
1766
    MODEL = "RT5RV"
1767

    
1768

    
1769
class RT5Alias(chirp_common.Alias):
1770
    VENDOR = "Retevis"
1771
    MODEL = "RT5"
1772

    
1773

    
1774
class RT5_TPAlias(chirp_common.Alias):
1775
    VENDOR = "Retevis"
1776
    MODEL = "RT5(tri-power)"
1777

    
1778

    
1779
class RH5RAlias(chirp_common.Alias):
1780
    VENDOR = "Rugged"
1781
    MODEL = "RH5R"
1782

    
1783

    
1784
class ROUV5REXAlias(chirp_common.Alias):
1785
    VENDOR = "Radioddity"
1786
    MODEL = "UV-5R EX"
1787

    
1788

    
1789
class A5RAlias(chirp_common.Alias):
1790
    VENDOR = "Ansoko"
1791
    MODEL = "A-5R"
1792

    
1793

    
1794
@directory.register
1795
class BaofengUV5RGeneric(BaofengUV5R):
1796
    ALIASES = [UV5XAlias, RT5RAlias, RT5RVAlias, RT5Alias, RH5RAlias,
1797
               ROUV5REXAlias, A5RAlias]
1798

    
1799

    
1800
@directory.register
1801
class BaofengF11Radio(BaofengUV5R):
1802
    VENDOR = "Baofeng"
1803
    MODEL = "F-11"
1804
    _basetype = BASETYPE_F11
1805
    _idents = [UV5R_MODEL_F11]
1806

    
1807
    def _is_orig(self):
1808
        # Override this for F11 to always return False
1809
        return False
1810

    
1811

    
1812
@directory.register
1813
class BaofengUV82Radio(BaofengUV5R):
1814
    MODEL = "UV-82"
1815
    _basetype = BASETYPE_UV82
1816
    _idents = [UV5R_MODEL_UV82]
1817
    _vhf_range = (130000000, 176000000)
1818
    _uhf_range = (400000000, 521000000)
1819
    _valid_chars = chirp_common.CHARSET_ASCII
1820

    
1821
    def _is_orig(self):
1822
        # Override this for UV82 to always return False
1823
        return False
1824

    
1825

    
1826
@directory.register
1827
class Radioddity82X3Radio(BaofengUV82Radio):
1828
    VENDOR = "Radioddity"
1829
    MODEL = "UV-82X3"
1830
    _basetype = BASETYPE_UV82X3
1831

    
1832
    def get_features(self):
1833
        rf = BaofengUV5R.get_features(self)
1834
        rf.valid_bands = [self._vhf_range,
1835
                          (200000000, 260000000),
1836
                          self._uhf_range]
1837
        return rf
1838

    
1839

    
1840
@directory.register
1841
class BaofengUV6Radio(BaofengUV5R):
1842

    
1843
    """Baofeng UV-6/UV-7"""
1844
    VENDOR = "Baofeng"
1845
    MODEL = "UV-6"
1846
    _basetype = BASETYPE_UV6
1847
    _idents = [UV5R_MODEL_UV6,
1848
               UV5R_MODEL_UV6_ORIG
1849
               ]
1850
    _aux_block = False
1851

    
1852
    def get_features(self):
1853
        rf = BaofengUV5R.get_features(self)
1854
        rf.memory_bounds = (1, 128)
1855
        return rf
1856

    
1857
    def _get_mem(self, number):
1858
        return self._memobj.memory[number - 1]
1859

    
1860
    def _get_nam(self, number):
1861
        return self._memobj.names[number - 1]
1862

    
1863
    def _set_mem(self, number):
1864
        return self._memobj.memory[number - 1]
1865

    
1866
    def _set_nam(self, number):
1867
        return self._memobj.names[number - 1]
1868

    
1869
    def _is_orig(self):
1870
        # Override this for UV6 to always return False
1871
        return False
1872

    
1873

    
1874
@directory.register
1875
class IntekKT980Radio(BaofengUV5R):
1876
    VENDOR = "Intek"
1877
    MODEL = "KT-980HP"
1878
    _basetype = BASETYPE_KT980HP
1879
    _idents = [UV5R_MODEL_291]
1880
    _vhf_range = (130000000, 180000000)
1881
    _uhf_range = (400000000, 521000000)
1882
    _tri_power = True
1883

    
1884
    def get_features(self):
1885
        rf = BaofengUV5R.get_features(self)
1886
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1887
        return rf
1888

    
1889
    def _is_orig(self):
1890
        # Override this for KT980HP to always return False
1891
        return False
1892

    
1893

    
1894
class ROGA5SAlias(chirp_common.Alias):
1895
    VENDOR = "Radioddity"
1896
    MODEL = "GA-5S"
1897

    
1898

    
1899
class UV5XPAlias(chirp_common.Alias):
1900
    VENDOR = "Baofeng"
1901
    MODEL = "UV-5XP"
1902

    
1903

    
1904
class TSTIF8Alias(chirp_common.Alias):
1905
    VENDOR = "TechSide"
1906
    MODEL = "TI-F8+"
1907

    
1908

    
1909
class TenwayUV5RPro(chirp_common.Alias):
1910
    VENDOR = 'Tenway'
1911
    MODEL = 'UV-5R Pro'
1912

    
1913

    
1914
@directory.register
1915
class BaofengBFF8HPRadio(BaofengUV5R):
1916
    VENDOR = "Baofeng"
1917
    MODEL = "BF-F8HP"
1918
    ALIASES = [RT5_TPAlias, ROGA5SAlias, UV5XPAlias, TSTIF8Alias,
1919
               TenwayUV5RPro]
1920
    _basetype = BASETYPE_F8HP
1921
    _idents = [UV5R_MODEL_291,
1922
               UV5R_MODEL_A58
1923
               ]
1924
    _vhf_range = (130000000, 180000000)
1925
    _uhf_range = (400000000, 521000000)
1926
    _tri_power = True
1927

    
1928
    def get_features(self):
1929
        rf = BaofengUV5R.get_features(self)
1930
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1931
        return rf
1932

    
1933
    def _is_orig(self):
1934
        # Override this for BFF8HP to always return False
1935
        return False
1936

    
1937

    
1938
class TenwayUV82Pro(chirp_common.Alias):
1939
    VENDOR = 'Tenway'
1940
    MODEL = 'UV-82 Pro'
1941

    
1942

    
1943
@directory.register
1944
class BaofengUV82HPRadio(BaofengUV5R):
1945
    VENDOR = "Baofeng"
1946
    MODEL = "UV-82HP"
1947
    ALIASES = [TenwayUV82Pro]
1948
    _basetype = BASETYPE_UV82HP
1949
    _idents = [UV5R_MODEL_UV82]
1950
    _vhf_range = (136000000, 175000000)
1951
    _uhf_range = (400000000, 521000000)
1952
    _tri_power = True
1953

    
1954
    def get_features(self):
1955
        rf = BaofengUV5R.get_features(self)
1956
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1957
        return rf
1958

    
1959
    def _is_orig(self):
1960
        # Override this for UV82HP to always return False
1961
        return False
1962

    
1963

    
1964
class TDUV5RRadio(chirp_common.Alias):
1965
    VENDOR = "TIDRADIO"
1966
    MODEL = "TD-UV5R TriPower"
1967

    
1968

    
1969
@directory.register
1970
class RadioddityUV5RX3Radio(BaofengUV5R):
1971
    VENDOR = "Radioddity"
1972
    MODEL = "UV-5RX3"
1973
    ALIASES = [TDUV5RRadio]
1974

    
1975
    def get_features(self):
1976
        rf = BaofengUV5R.get_features(self)
1977
        rf.valid_bands = [self._vhf_range,
1978
                          (200000000, 260000000),
1979
                          self._uhf_range]
1980
        return rf
1981

    
1982
    @classmethod
1983
    def match_model(cls, filename, filedata):
1984
        return False
1985

    
1986

    
1987
@directory.register
1988
class RadioddityGT5RRadio(BaofengUV5R):
1989
    VENDOR = 'Baofeng'
1990
    MODEL = 'GT-5R'
1991

    
1992
    vhftx = [144000000, 148000000]
1993
    uhftx = [420000000, 450000000]
1994

    
1995
    def set_memory(self, mem):
1996
        # If memory is outside the TX limits, the radio will refuse
1997
        # transmit. Radioddity asked for us to enforce this behavior
1998
        # in chirp for consistency.
1999
        if not (mem.freq >= self.vhftx[0] and mem.freq < self.vhftx[1]) and \
2000
           not (mem.freq >= self.uhftx[0] and mem.freq < self.uhftx[1]):
2001
            LOG.info('Memory frequency outside TX limits of radio; '
2002
                     'forcing duplex=off')
2003
            mem.duplex = 'off'
2004
            mem.offset = 0
2005
        BaofengUV5R.set_memory(self, mem)
2006

    
2007
    @classmethod
2008
    def match_model(cls, filename, filedata):
2009
        return False
(2-2/3)