uv5r_tonfa.py

Jim Unroe, 06/01/2018 06:05 pm

Download (61.5 kB)

 
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 unknown1;
156
  u8 offset[4];
157
  u8 unknown2;
158
  ul16 rxtone;
159
  ul16 txtone;
160
  u8 unused1:7,
161
     band:1;
162
  u8 unknown3;
163
  u8 unused2:2,
164
     sftd:2,
165
     scode:4;
166
  u8 unknown4;
167
  u8 unused3:1
168
     step:3,
169
     unused4:4;
170
  u8 txpower:1,
171
     widenarr:1,
172
     unknown5:4,
173
     txpower3:2;
174
} vfoa;
175

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

    
200
#seekto 0x0F56;
201
u16 fm_presets;
202

    
203
#seekto 0x1008;
204
struct {
205
  char name[7];
206
  u8 unknown2[9];
207
} names[128];
208

    
209
#seekto 0x1818;
210
struct {
211
  char line1[7];
212
  char line2[7];
213
} sixpoweron_msg;
214

    
215
#seekto 0x%04X;
216
struct {
217
  char line1[7];
218
  char line2[7];
219
} poweron_msg;
220

    
221
#seekto 0x1838;
222
struct {
223
  char line1[7];
224
  char line2[7];
225
} firmware_msg;
226

    
227
struct limit {
228
  u8 enable;
229
  bbcd lower[2];
230
  bbcd upper[2];
231
};
232

    
233
#seekto 0x1908;
234
struct {
235
  struct limit vhf;
236
  struct limit uhf;
237
} limits_new;
238

    
239
#seekto 0x1910;
240
struct {
241
  u8 unknown1[2];
242
  struct limit vhf;
243
  u8 unknown2;
244
  u8 unknown3[8];
245
  u8 unknown4[2];
246
  struct limit uhf;
247
} limits_old;
248

    
249
struct squelch {
250
  u8 sql0;
251
  u8 sql1;
252
  u8 sql2;
253
  u8 sql3;
254
  u8 sql4;
255
  u8 sql5;
256
  u8 sql6;
257
  u8 sql7;
258
  u8 sql8;
259
  u8 sql9;
260
};
261

    
262
#seekto 0x18A8;
263
struct {
264
  struct squelch vhf;
265
  u8 unknown1[6];
266
  u8 unknown2[16];
267
  struct squelch uhf;
268
} squelch_new;
269

    
270
#seekto 0x18E8;
271
struct {
272
  struct squelch vhf;
273
  u8 unknown[6];
274
  struct squelch uhf;
275
} squelch_old;
276

    
277
"""
278

    
279
# 0x1EC0 - 0x2000
280

    
281
vhf_220_radio = "\x02"
282

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

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

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

    
360

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

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

    
376

    
377
def _upper_band_from_data(data):
378
    return data[0x03:0x04]
379

    
380

    
381
def _upper_band_from_image(radio):
382
    return _upper_band_from_data(radio.get_mmap())
383

    
384

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

    
389

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

    
397

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

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

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

    
413
    serial.write("\x02")
414

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

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

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

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

    
457
    return ident
458

    
459

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

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

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

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

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

    
487
    radio.pipe.write("\x06")
488
    time.sleep(0.05)
489

    
490
    return chunk
491

    
492

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

    
504

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

    
509

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

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

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

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

    
540

    
541
def _do_download(radio):
542
    data = _ident_radio(radio)
543

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

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

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

    
583
    if append_model:
584
        data += radio.MODEL.ljust(8)
585

    
586
    LOG.debug("done.")
587
    return memmap.MemoryMap(data)
588

    
589

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

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

    
599

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
688

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

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

    
702

    
703
class BaofengUV5R(chirp_common.CloneModeRadio,
704
                  chirp_common.ExperimentalRadio):
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
    _mem_params = (0x1828  # poweron_msg offset
720
                   )
721
    # offset of fw version in image file
722
    _fw_ver_file_start = 0x1838
723
    _fw_ver_file_stop = 0x1846
724

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

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

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

    
777
        normal_bands = [self._vhf_range, self._uhf_range]
778
        rax_bands = [self._vhf_range, self._220_range]
779

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

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

    
797
        if match_size and match_model:
798
            return True
799
        else:
800
            return False
801

    
802
    def process_mmap(self):
803
        self._memobj = bitwise.parse(MEM_FORMAT % self._mem_params, self._mmap)
804

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

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

    
822
    def get_raw_memory(self, number):
823
        return repr(self._memobj.memory[number])
824

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

    
831
    def _get_mem(self, number):
832
        return self._memobj.memory[number]
833

    
834
    def _get_nam(self, number):
835
        return self._memobj.names[number]
836

    
837
    def get_memory(self, number):
838
        _mem = self._get_mem(number)
839
        _nam = self._get_nam(number)
840

    
841
        mem = chirp_common.Memory()
842
        mem.number = number
843

    
844
        if _mem.get_raw()[0] == "\xff":
845
            mem.empty = True
846
            return mem
847

    
848
        mem.freq = int(_mem.rxfreq) * 10
849

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

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

    
869
        dtcs_pol = ["N", "N"]
870

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

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

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

    
913
        mem.dtcs_polarity = "".join(dtcs_pol)
914

    
915
        if not _mem.scan:
916
            mem.skip = "S"
917

    
918
        if self.MODEL in ("KT-980HP", "BF-F8HP", "UV-82HP"):
919
            levels = UV5R_POWER_LEVELS3
920
        else:
921
            levels = UV5R_POWER_LEVELS
922
        try:
923
            mem.power = levels[_mem.lowpower]
924
        except IndexError:
925
            LOG.error("Radio reported invalid power level %s (in %s)" %
926
                      (_mem.lowpower, levels))
927
            mem.power = levels[0]
928

    
929
        mem.mode = _mem.wide and "FM" or "NFM"
930

    
931
        mem.extra = RadioSettingGroup("Extra", "extra")
932

    
933
        rs = RadioSetting("bcl", "BCL",
934
                          RadioSettingValueBoolean(_mem.bcl))
935
        mem.extra.append(rs)
936

    
937
        rs = RadioSetting("pttid", "PTT ID",
938
                          RadioSettingValueList(PTTID_LIST,
939
                                                PTTID_LIST[_mem.pttid]))
940
        mem.extra.append(rs)
941

    
942
        rs = RadioSetting("scode", "PTT ID Code",
943
                          RadioSettingValueList(PTTIDCODE_LIST,
944
                                                PTTIDCODE_LIST[_mem.scode]))
945
        mem.extra.append(rs)
946

    
947
        return mem
948

    
949
    def _set_mem(self, number):
950
        return self._memobj.memory[number]
951

    
952
    def _set_nam(self, number):
953
        return self._memobj.names[number]
954

    
955
    def set_memory(self, mem):
956
        _mem = self._get_mem(mem.number)
957
        _nam = self._get_nam(mem.number)
958

    
959
        if mem.empty:
960
            _mem.set_raw("\xff" * 16)
961
            _nam.set_raw("\xff" * 16)
962
            return
963

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

    
978
        _mem.set_raw("\x00" * 16)
979

    
980
        _mem.rxfreq = mem.freq / 10
981

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

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

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

    
1030
        if txmode == "DTCS" and mem.dtcs_polarity[0] == "R":
1031
            _mem.txtone += 0x69
1032
        if rxmode == "DTCS" and mem.dtcs_polarity[1] == "R":
1033
            _mem.rxtone += 0x69
1034

    
1035
        _mem.scan = mem.skip != "S"
1036
        _mem.wide = mem.mode == "FM"
1037

    
1038
        if mem.power:
1039
            if self.MODEL in ("KT-980HP", "BF-F8HP", "UV-82HP"):
1040
                levels = [str(l) for l in UV5R_POWER_LEVELS3]
1041
                _mem.lowpower = levels.index(str(mem.power))
1042
            else:
1043
                _mem.lowpower = UV5R_POWER_LEVELS.index(mem.power)
1044
        else:
1045
            _mem.lowpower = 0
1046

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

    
1053
        for setting in mem.extra:
1054
            setattr(_mem, setting.get_name(), setting.value)
1055

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

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

    
1076
        raise Exception("Unrecognized firmware version string")
1077

    
1078
    def _my_upper_band(self):
1079
        band_tag = _upper_band_from_image(self)
1080
        return band_tag
1081

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

    
1093
        group = RadioSettings(basic, advanced)
1094

    
1095
        rs = RadioSetting("squelch", "Carrier Squelch Level",
1096
                          RadioSettingValueInteger(0, 9, _settings.squelch))
1097
        basic.append(rs)
1098

    
1099
        rs = RadioSetting("save", "Battery Saver",
1100
                          RadioSettingValueList(
1101
                              SAVE_LIST, SAVE_LIST[_settings.save]))
1102
        basic.append(rs)
1103

    
1104
        rs = RadioSetting("vox", "VOX Sensitivity",
1105
                          RadioSettingValueList(
1106
                              VOX_LIST, VOX_LIST[_settings.vox]))
1107
        advanced.append(rs)
1108

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

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

    
1122
        rs = RadioSetting("tdr", "Dual Watch",
1123
                          RadioSettingValueBoolean(_settings.tdr))
1124
        advanced.append(rs)
1125

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

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

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

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

    
1155
        rs = RadioSetting("beep", "Beep",
1156
                          RadioSettingValueBoolean(_settings.beep))
1157
        basic.append(rs)
1158

    
1159
        rs = RadioSetting("timeout", "Timeout Timer",
1160
                          RadioSettingValueList(
1161
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
1162
        basic.append(rs)
1163

    
1164
        if self._is_orig() and self._my_version() < 251:
1165
            rs = RadioSetting("voice", "Voice",
1166
                              RadioSettingValueBoolean(_settings.voice))
1167
            advanced.append(rs)
1168
        else:
1169
            rs = RadioSetting("voice", "Voice",
1170
                              RadioSettingValueList(
1171
                                  VOICE_LIST, VOICE_LIST[_settings.voice]))
1172
            advanced.append(rs)
1173

    
1174
        rs = RadioSetting("screv", "Scan Resume",
1175
                          RadioSettingValueList(
1176
                              RESUME_LIST, RESUME_LIST[_settings.screv]))
1177
        advanced.append(rs)
1178

    
1179
        if self.MODEL != "UV-6":
1180
            rs = RadioSetting("mdfa", "Display Mode (A)",
1181
                              RadioSettingValueList(
1182
                                  MODE_LIST, MODE_LIST[_settings.mdfa]))
1183
            basic.append(rs)
1184

    
1185
            rs = RadioSetting("mdfb", "Display Mode (B)",
1186
                              RadioSettingValueList(
1187
                                  MODE_LIST, MODE_LIST[_settings.mdfb]))
1188
            basic.append(rs)
1189

    
1190
        rs = RadioSetting("bcl", "Busy Channel Lockout",
1191
                          RadioSettingValueBoolean(_settings.bcl))
1192
        advanced.append(rs)
1193

    
1194
        if self.MODEL != "UV-6":
1195
            rs = RadioSetting("autolk", "Automatic Key Lock",
1196
                              RadioSettingValueBoolean(_settings.autolk))
1197
            advanced.append(rs)
1198

    
1199
        rs = RadioSetting("fmradio", "Broadcast FM Radio",
1200
                          RadioSettingValueBoolean(_settings.fmradio))
1201
        advanced.append(rs)
1202

    
1203
        if self.MODEL != "UV-6":
1204
            rs = RadioSetting("wtled", "Standby LED Color",
1205
                              RadioSettingValueList(
1206
                                  COLOR_LIST, COLOR_LIST[_settings.wtled]))
1207
            basic.append(rs)
1208

    
1209
            rs = RadioSetting("rxled", "RX LED Color",
1210
                              RadioSettingValueList(
1211
                                  COLOR_LIST, COLOR_LIST[_settings.rxled]))
1212
            basic.append(rs)
1213

    
1214
            rs = RadioSetting("txled", "TX LED Color",
1215
                              RadioSettingValueList(
1216
                                  COLOR_LIST, COLOR_LIST[_settings.txled]))
1217
            basic.append(rs)
1218

    
1219
        if self.MODEL == "UV-82":
1220
            rs = RadioSetting("roger", "Roger Beep (TX)",
1221
                              RadioSettingValueBoolean(_settings.roger))
1222
            basic.append(rs)
1223
            rs = RadioSetting("rogerrx", "Roger Beep (RX)",
1224
                              RadioSettingValueList(
1225
                                  ROGERRX_LIST,
1226
                                  ROGERRX_LIST[_settings.rogerrx]))
1227
            basic.append(rs)
1228
        else:
1229
            rs = RadioSetting("roger", "Roger Beep",
1230
                              RadioSettingValueBoolean(_settings.roger))
1231
            basic.append(rs)
1232

    
1233
        rs = RadioSetting("ste", "Squelch Tail Eliminate (HT to HT)",
1234
                          RadioSettingValueBoolean(_settings.ste))
1235
        advanced.append(rs)
1236

    
1237
        rs = RadioSetting("rpste", "Squelch Tail Eliminate (repeater)",
1238
                          RadioSettingValueList(
1239
                              RPSTE_LIST, RPSTE_LIST[_settings.rpste]))
1240
        advanced.append(rs)
1241

    
1242
        rs = RadioSetting("rptrl", "STE Repeater Delay",
1243
                          RadioSettingValueList(
1244
                              STEDELAY_LIST, STEDELAY_LIST[_settings.rptrl]))
1245
        advanced.append(rs)
1246

    
1247
        if self.MODEL != "UV-6":
1248
            rs = RadioSetting("reset", "RESET Menu",
1249
                              RadioSettingValueBoolean(_settings.reset))
1250
            advanced.append(rs)
1251

    
1252
            rs = RadioSetting("menu", "All Menus",
1253
                              RadioSettingValueBoolean(_settings.menu))
1254
            advanced.append(rs)
1255

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

    
1262
        if self.MODEL == "UV-82":
1263
            # this is a UV-82C only feature
1264
            rs = RadioSetting("vfomrlock", "VFO/MR Switching (UV-82C only)",
1265
                              RadioSettingValueBoolean(_settings.vfomrlock))
1266
            advanced.append(rs)
1267

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

    
1275
        if self.MODEL == "UV-82":
1276
            # this is an UV-82C only feature
1277
            rs = RadioSetting("singleptt", "Single PTT (UV-82C only)",
1278
                              RadioSettingValueBoolean(_settings.singleptt))
1279
            advanced.append(rs)
1280

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

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

    
1294
        if len(self._mmap.get_packed()) == 0x1808:
1295
            # Old image, without aux block
1296
            return group
1297

    
1298
        other = RadioSettingGroup("other", "Other Settings")
1299
        group.append(other)
1300

    
1301
        def _filter(name):
1302
            filtered = ""
1303
            for char in str(name):
1304
                if char in chirp_common.CHARSET_ASCII:
1305
                    filtered += char
1306
                else:
1307
                    filtered += " "
1308
            return filtered
1309

    
1310
        _msg = self._memobj.firmware_msg
1311
        val = RadioSettingValueString(0, 7, _filter(_msg.line1))
1312
        val.set_mutable(False)
1313
        rs = RadioSetting("firmware_msg.line1", "Firmware Message 1", val)
1314
        other.append(rs)
1315

    
1316
        val = RadioSettingValueString(0, 7, _filter(_msg.line2))
1317
        val.set_mutable(False)
1318
        rs = RadioSetting("firmware_msg.line2", "Firmware Message 2", val)
1319
        other.append(rs)
1320

    
1321
        if self.MODEL != "UV-6":
1322
            _msg = self._memobj.sixpoweron_msg
1323
            rs = RadioSetting("sixpoweron_msg.line1", "6+Power-On Message 1",
1324
                              RadioSettingValueString(
1325
                                  0, 7, _filter(_msg.line1)))
1326
            other.append(rs)
1327
            rs = RadioSetting("sixpoweron_msg.line2", "6+Power-On Message 2",
1328
                              RadioSettingValueString(
1329
                                  0, 7, _filter(_msg.line2)))
1330
            other.append(rs)
1331

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

    
1342
            rs = RadioSetting("ponmsg", "Power-On Message",
1343
                              RadioSettingValueList(
1344
                                  PONMSG_LIST, PONMSG_LIST[_settings.ponmsg]))
1345
            other.append(rs)
1346

    
1347
            #if self._is_orig():
1348
            #    limit = "limits_old"
1349
            #else:
1350
            #    limit = "limits_new"
1351

    
1352
            #vhf_limit = getattr(self._memobj, limit).vhf
1353
            #rs = RadioSetting("%s.vhf.lower" % limit, "VHF Lower Limit (MHz)",
1354
            #                  RadioSettingValueInteger(1, 1000,
1355
            #                                           vhf_limit.lower))
1356
            #other.append(rs)
1357

    
1358
            #rs = RadioSetting("%s.vhf.upper" % limit, "VHF Upper Limit (MHz)",
1359
            #                  RadioSettingValueInteger(1, 1000,
1360
            #                                           vhf_limit.upper))
1361
            #other.append(rs)
1362

    
1363
            #rs = RadioSetting("%s.vhf.enable" % limit, "VHF TX Enabled",
1364
            #                  RadioSettingValueBoolean(vhf_limit.enable))
1365
            #other.append(rs)
1366

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

    
1380
        if self.MODEL != "UV-6":
1381
            workmode = RadioSettingGroup("workmode", "Work Mode Settings")
1382
            group.append(workmode)
1383

    
1384
            rs = RadioSetting("displayab", "Display",
1385
                              RadioSettingValueList(
1386
                                  AB_LIST, AB_LIST[_settings.displayab]))
1387
            workmode.append(rs)
1388

    
1389
            rs = RadioSetting("workmode", "VFO/MR Mode",
1390
                              RadioSettingValueList(
1391
                                  WORKMODE_LIST,
1392
                                  WORKMODE_LIST[_settings.workmode]))
1393
            workmode.append(rs)
1394

    
1395
            rs = RadioSetting("keylock", "Keypad Lock",
1396
                              RadioSettingValueBoolean(_settings.keylock))
1397
            workmode.append(rs)
1398

    
1399
            rs = RadioSetting("wmchannel.mrcha", "MR A Channel",
1400
                              RadioSettingValueInteger(0, 127,
1401
                                                       _wmchannel.mrcha))
1402
            workmode.append(rs)
1403

    
1404
            rs = RadioSetting("wmchannel.mrchb", "MR B Channel",
1405
                              RadioSettingValueInteger(0, 127,
1406
                                                       _wmchannel.mrchb))
1407
            workmode.append(rs)
1408

    
1409
            def convert_bytes_to_freq(bytes):
1410
                real_freq = 0
1411
                for byte in bytes:
1412
                    real_freq = (real_freq * 10) + byte
1413
                return chirp_common.format_freq(real_freq * 10)
1414

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

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

    
1429
            val1a = RadioSettingValueString(0, 10,
1430
                                            convert_bytes_to_freq(_vfoa.freq))
1431
            val1a.set_validate_callback(my_validate)
1432
            rs = RadioSetting("vfoa.freq", "VFO A Frequency", val1a)
1433
            rs.set_apply_callback(apply_freq, _vfoa)
1434
            workmode.append(rs)
1435

    
1436
            val1b = RadioSettingValueString(0, 10,
1437
                                            convert_bytes_to_freq(_vfob.freq))
1438
            val1b.set_validate_callback(my_validate)
1439
            rs = RadioSetting("vfob.freq", "VFO B Frequency", val1b)
1440
            rs.set_apply_callback(apply_freq, _vfob)
1441
            workmode.append(rs)
1442

    
1443
            rs = RadioSetting("vfoa.sftd", "VFO A Shift",
1444
                              RadioSettingValueList(
1445
                                  SHIFTD_LIST, SHIFTD_LIST[_vfoa.sftd]))
1446
            workmode.append(rs)
1447

    
1448
            rs = RadioSetting("vfob.sftd", "VFO B Shift",
1449
                              RadioSettingValueList(
1450
                                  SHIFTD_LIST, SHIFTD_LIST[_vfob.sftd]))
1451
            workmode.append(rs)
1452

    
1453
            def convert_bytes_to_offset(bytes):
1454
                real_offset = 0
1455
                for byte in bytes:
1456
                    real_offset = (real_offset * 10) + byte
1457
                return chirp_common.format_freq(real_offset * 10000)
1458

    
1459
            def apply_offset(setting, obj):
1460
                value = chirp_common.parse_freq(str(setting.value)) / 10000
1461
                for i in range(3, -1, -1):
1462
                    obj.offset[i] = value % 10
1463
                    value /= 10
1464

    
1465
            val1a = RadioSettingValueString(
1466
                0, 10, convert_bytes_to_offset(_vfoa.offset))
1467
            rs = RadioSetting("vfoa.offset",
1468
                              "VFO A Offset (0.00-69.95)", val1a)
1469
            rs.set_apply_callback(apply_offset, _vfoa)
1470
            workmode.append(rs)
1471

    
1472
            val1b = RadioSettingValueString(
1473
                0, 10, convert_bytes_to_offset(_vfob.offset))
1474
            rs = RadioSetting("vfob.offset",
1475
                              "VFO B Offset (0.00-69.95)", val1b)
1476
            rs.set_apply_callback(apply_offset, _vfob)
1477
            workmode.append(rs)
1478

    
1479
            if self.MODEL in ("KT-980HP", "BF-F8HP", "UV-82HP"):
1480
                rs = RadioSetting("vfoa.txpower3", "VFO A Power",
1481
                                  RadioSettingValueList(
1482
                                      TXPOWER3_LIST,
1483
                                      TXPOWER3_LIST[_vfoa.txpower3]))
1484
                workmode.append(rs)
1485

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

    
1498
                rs = RadioSetting("vfob.txpower", "VFO B Power",
1499
                                  RadioSettingValueList(
1500
                                      TXPOWER_LIST,
1501
                                      TXPOWER_LIST[_vfob.txpower]))
1502
                workmode.append(rs)
1503

    
1504
            rs = RadioSetting("vfoa.widenarr", "VFO A Bandwidth",
1505
                              RadioSettingValueList(
1506
                                  BANDWIDTH_LIST,
1507
                                  BANDWIDTH_LIST[_vfoa.widenarr]))
1508
            workmode.append(rs)
1509

    
1510
            rs = RadioSetting("vfob.widenarr", "VFO B Bandwidth",
1511
                              RadioSettingValueList(
1512
                                  BANDWIDTH_LIST,
1513
                                  BANDWIDTH_LIST[_vfob.widenarr]))
1514
            workmode.append(rs)
1515

    
1516
            rs = RadioSetting("vfoa.scode", "VFO A PTT-ID",
1517
                              RadioSettingValueList(
1518
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfoa.scode]))
1519
            workmode.append(rs)
1520

    
1521
            rs = RadioSetting("vfob.scode", "VFO B PTT-ID",
1522
                              RadioSettingValueList(
1523
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfob.scode]))
1524
            workmode.append(rs)
1525

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

    
1545
        fm_preset = RadioSettingGroup("fm_preset", "FM Radio Preset")
1546
        group.append(fm_preset)
1547

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

    
1558
        dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
1559
        group.append(dtmf)
1560
        dtmfchars = "0123456789 *#ABCD"
1561

    
1562
        for i in range(0, 15):
1563
            _codeobj = self._memobj.pttid[i].code
1564
            _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1565
            val = RadioSettingValueString(0, 5, _code, False)
1566
            val.set_charset(dtmfchars)
1567
            rs = RadioSetting("pttid/%i.code" % i,
1568
                              "PTT ID Code %i" % (i + 1), val)
1569

    
1570
            def apply_code(setting, obj):
1571
                code = []
1572
                for j in range(0, 5):
1573
                    try:
1574
                        code.append(dtmfchars.index(str(setting.value)[j]))
1575
                    except IndexError:
1576
                        code.append(0xFF)
1577
                obj.code = code
1578
            rs.set_apply_callback(apply_code, self._memobj.pttid[i])
1579
            dtmf.append(rs)
1580

    
1581
        _codeobj = self._memobj.ani.code
1582
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1583
        val = RadioSettingValueString(0, 5, _code, False)
1584
        val.set_charset(dtmfchars)
1585
        rs = RadioSetting("ani.code", "ANI Code", val)
1586

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

    
1598
        rs = RadioSetting("ani.aniid", "ANI ID",
1599
                          RadioSettingValueList(PTTID_LIST,
1600
                                                PTTID_LIST[_ani.aniid]))
1601
        dtmf.append(rs)
1602

    
1603
        _codeobj = self._memobj.ani.alarmcode
1604
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1605
        val = RadioSettingValueString(0, 3, _code, False)
1606
        val.set_charset(dtmfchars)
1607
        rs = RadioSetting("ani.alarmcode", "Alarm Code", val)
1608

    
1609
        def apply_code(setting, obj):
1610
            alarmcode = []
1611
            for j in range(0, 3):
1612
                try:
1613
                    alarmcode.append(dtmfchars.index(str(setting.value)[j]))
1614
                except IndexError:
1615
                    alarmcode.append(0xFF)
1616
            obj.alarmcode = alarmcode
1617
        rs.set_apply_callback(apply_code, _ani)
1618
        dtmf.append(rs)
1619

    
1620
        rs = RadioSetting("dtmfst", "DTMF Sidetone",
1621
                          RadioSettingValueList(DTMFST_LIST,
1622
                                                DTMFST_LIST[_settings.dtmfst]))
1623
        dtmf.append(rs)
1624

    
1625
        if _ani.dtmfon > 0xC3:
1626
            val = 0x00
1627
        else:
1628
            val = _ani.dtmfon
1629
        rs = RadioSetting("ani.dtmfon", "DTMF Speed (on)",
1630
                          RadioSettingValueList(DTMFSPEED_LIST,
1631
                                                DTMFSPEED_LIST[val]))
1632
        dtmf.append(rs)
1633

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

    
1643
        rs = RadioSetting("pttlt", "PTT ID Delay",
1644
                          RadioSettingValueInteger(0, 50, _settings.pttlt))
1645
        dtmf.append(rs)
1646

    
1647
        #if not self._is_orig():
1648
        #    service = RadioSettingGroup("service", "Service Settings")
1649
        #    group.append(service)
1650

    
1651
        #    for band in ["vhf", "uhf"]:
1652
        #        for index in range(0, 10):
1653
        #            key = "squelch_new.%s.sql%i" % (band, index)
1654
        #            if band == "vhf":
1655
        #                _obj = self._memobj.squelch_new.vhf
1656
        #            elif band == "uhf":
1657
        #                _obj = self._memobj.squelch_new.uhf
1658
        #            name = "%s Squelch %i" % (band.upper(), index)
1659
        #            rs = RadioSetting(key, name,
1660
        #                              RadioSettingValueInteger(
1661
        #                                  0, 123,
1662
        #                                  getattr(_obj, "sql%i" % (index))))
1663
        #            service.append(rs)
1664

    
1665
        return group
1666

    
1667
    def get_settings(self):
1668
        try:
1669
            return self._get_settings()
1670
        except:
1671
            import traceback
1672
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1673
            return None
1674

    
1675
    def set_settings(self, settings):
1676
        _settings = self._memobj.settings
1677
        for element in settings:
1678
            if not isinstance(element, RadioSetting):
1679
                if element.get_name() == "fm_preset":
1680
                    self._set_fm_preset(element)
1681
                else:
1682
                    self.set_settings(element)
1683
                    continue
1684
            else:
1685
                try:
1686
                    name = element.get_name()
1687
                    if "." in name:
1688
                        bits = name.split(".")
1689
                        obj = self._memobj
1690
                        for bit in bits[:-1]:
1691
                            if "/" in bit:
1692
                                bit, index = bit.split("/", 1)
1693
                                index = int(index)
1694
                                obj = getattr(obj, bit)[index]
1695
                            else:
1696
                                obj = getattr(obj, bit)
1697
                        setting = bits[-1]
1698
                    else:
1699
                        obj = _settings
1700
                        setting = element.get_name()
1701

    
1702
                    if element.has_apply_callback():
1703
                        LOG.debug("Using apply callback")
1704
                        element.run_apply_callback()
1705
                    elif element.value.get_mutable():
1706
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1707
                        setattr(obj, setting, element.value)
1708
                except Exception, e:
1709
                    LOG.debug(element.get_name())
1710
                    raise
1711

    
1712
    def _set_fm_preset(self, settings):
1713
        for element in settings:
1714
            try:
1715
                val = element.value
1716
                if self._memobj.fm_presets <= 108.0 * 10 - 650:
1717
                    value = int(val.get_value() * 10 - 650)
1718
                else:
1719
                    value = int(val.get_value() * 10)
1720
                LOG.debug("Setting fm_presets = %s" % (value))
1721
                self._memobj.fm_presets = value
1722
            except Exception, e:
1723
                LOG.debug(element.get_name())
1724
                raise
1725

    
1726

    
1727
class UV5XAlias(chirp_common.Alias):
1728
    VENDOR = "Baofeng"
1729
    MODEL = "UV-5X"
1730

    
1731

    
1732
class RT5RAlias(chirp_common.Alias):
1733
    VENDOR = "Retevis"
1734
    MODEL = "RT-5R"
1735

    
1736

    
1737
class RT5RVAlias(chirp_common.Alias):
1738
    VENDOR = "Retevis"
1739
    MODEL = "RT-5RV"
1740

    
1741

    
1742
class RT5Alias(chirp_common.Alias):
1743
    VENDOR = "Retevis"
1744
    MODEL = "RT5"
1745

    
1746

    
1747
class RT5_TPAlias(chirp_common.Alias):
1748
    VENDOR = "Retevis"
1749
    MODEL = "RT5(tri-power)"
1750

    
1751

    
1752
class RH5RAlias(chirp_common.Alias):
1753
    VENDOR = "Rugged"
1754
    MODEL = "RH5R"
1755

    
1756

    
1757
@directory.register
1758
class BaofengUV5RGeneric(BaofengUV5R):
1759
    ALIASES = [UV5XAlias, RT5RAlias, RT5RVAlias, RT5Alias, RH5RAlias]
1760

    
1761

    
1762
@directory.register
1763
class BaofengF11Radio(BaofengUV5R):
1764
    VENDOR = "Baofeng"
1765
    MODEL = "F-11"
1766
    _basetype = BASETYPE_F11
1767
    _idents = [UV5R_MODEL_F11]
1768

    
1769
    def _is_orig(self):
1770
        # Override this for F11 to always return False
1771
        return False
1772

    
1773

    
1774
@directory.register
1775
class BaofengUV82Radio(BaofengUV5R):
1776
    MODEL = "UV-82"
1777
    _basetype = BASETYPE_UV82
1778
    _idents = [UV5R_MODEL_UV82]
1779
    _vhf_range = (130000000, 176000000)
1780
    _uhf_range = (400000000, 521000000)
1781
    _valid_chars = chirp_common.CHARSET_ASCII
1782

    
1783
    def _is_orig(self):
1784
        # Override this for UV82 to always return False
1785
        return False
1786

    
1787

    
1788
@directory.register
1789
class BaofengUV6Radio(BaofengUV5R):
1790

    
1791
    """Baofeng UV-6/UV-7"""
1792
    VENDOR = "Baofeng"
1793
    MODEL = "UV-6"
1794
    _basetype = BASETYPE_UV6
1795
    _idents = [UV5R_MODEL_UV6,
1796
               UV5R_MODEL_UV6_ORIG
1797
               ]
1798

    
1799
    def get_features(self):
1800
        rf = BaofengUV5R.get_features(self)
1801
        rf.memory_bounds = (1, 128)
1802
        return rf
1803

    
1804
    def _get_mem(self, number):
1805
        return self._memobj.memory[number - 1]
1806

    
1807
    def _get_nam(self, number):
1808
        return self._memobj.names[number - 1]
1809

    
1810
    def _set_mem(self, number):
1811
        return self._memobj.memory[number - 1]
1812

    
1813
    def _set_nam(self, number):
1814
        return self._memobj.names[number - 1]
1815

    
1816
    def _is_orig(self):
1817
        # Override this for UV6 to always return False
1818
        return False
1819

    
1820

    
1821
@directory.register
1822
class IntekKT980Radio(BaofengUV5R):
1823
    VENDOR = "Intek"
1824
    MODEL = "KT-980HP"
1825
    _basetype = BASETYPE_KT980HP
1826
    _idents = [UV5R_MODEL_291]
1827
    _vhf_range = (130000000, 180000000)
1828
    _uhf_range = (400000000, 521000000)
1829

    
1830
    def get_features(self):
1831
        rf = BaofengUV5R.get_features(self)
1832
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1833
        return rf
1834

    
1835
    def _is_orig(self):
1836
        # Override this for KT980HP to always return False
1837
        return False
1838

    
1839

    
1840
@directory.register
1841
class BaofengBFF8HPRadio(BaofengUV5R):
1842
    VENDOR = "Baofeng"
1843
    MODEL = "BF-F8HP"
1844
    ALIASES = [RT5_TPAlias]
1845
    _basetype = BASETYPE_F8HP
1846
    _idents = [UV5R_MODEL_291,
1847
               UV5R_MODEL_A58
1848
               ]
1849
    _vhf_range = (130000000, 180000000)
1850
    _uhf_range = (400000000, 521000000)
1851

    
1852
    def get_features(self):
1853
        rf = BaofengUV5R.get_features(self)
1854
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1855
        return rf
1856

    
1857
    def _is_orig(self):
1858
        # Override this for BFF8HP to always return False
1859
        return False
1860

    
1861

    
1862
@directory.register
1863
class BaofengUV82HPRadio(BaofengUV5R):
1864
    VENDOR = "Baofeng"
1865
    MODEL = "UV-82HP"
1866
    _basetype = BASETYPE_UV82HP
1867
    _idents = [UV5R_MODEL_UV82]
1868
    _vhf_range = (136000000, 175000000)
1869
    _uhf_range = (400000000, 521000000)
1870

    
1871
    def get_features(self):
1872
        rf = BaofengUV5R.get_features(self)
1873
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1874
        return rf
1875

    
1876
    def _is_orig(self):
1877
        # Override this for UV82HP to always return False
1878
        return False