uv5r_test3.py

Jim Unroe, 07/02/2020 05:08 pm

Download (63.3 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", "B5R2"]
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", "N5RV"]
290
BASETYPE_UV82HP = ["N82-3", "N823", "N5R2"]
291
BASETYPE_UV82X3 = ["HN5RV01"]
292
BASETYPE_LIST = BASETYPE_UV5R + BASETYPE_F11 + BASETYPE_UV82 + \
293
    BASETYPE_BJ55 + BASETYPE_UV6 + BASETYPE_KT980HP + \
294
    BASETYPE_F8HP + BASETYPE_UV82HP + BASETYPE_UV82X3
295

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

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

    
361

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

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

    
377

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

    
381

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

    
385

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

    
390

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

    
398

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

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

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

    
414
    serial.write("\x02")
415

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

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

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

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

    
458
    return ident
459

    
460

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

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

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

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

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

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

    
491
    return chunk
492

    
493

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

    
505

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

    
510

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

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

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

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

    
541

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

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

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

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

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

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

    
590

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

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

    
600

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
689

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

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

    
703

    
704
class BaofengUV5R(chirp_common.CloneModeRadio,
705
                  chirp_common.ExperimentalRadio):
706

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
949
        return mem
950

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

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

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

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

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

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

    
982
        _mem.rxfreq = mem.freq / 10
983

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1095
        group = RadioSettings(basic, advanced)
1096

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1300
        other = RadioSettingGroup("other", "Other Settings")
1301
        group.append(other)
1302

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1547
        fm_preset = RadioSettingGroup("fm_preset", "FM Radio Preset")
1548
        group.append(fm_preset)
1549

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1649
        if not self._is_orig():
1650
            service = RadioSettingGroup("service", "Service Settings")
1651
            group.append(service)
1652

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

    
1667
        return group
1668

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

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

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

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

    
1728

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

    
1733

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

    
1738

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

    
1743

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

    
1748

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

    
1753

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

    
1758

    
1759
class ROUV5REXAlias(chirp_common.Alias):
1760
    VENDOR = "Radioddity"
1761
    MODEL = "UV-5R EX"
1762

    
1763

    
1764
class A5RAlias(chirp_common.Alias):
1765
    VENDOR = "Ansoko"
1766
    MODEL = "A-5R"
1767

    
1768

    
1769
class TenwayUV5RPro(chirp_common.Alias):
1770
    VENDOR = 'Tenway'
1771
    MODEL = 'UV-5R Pro'
1772

    
1773

    
1774
@directory.register
1775
class BaofengUV5RGeneric(BaofengUV5R):
1776
    ALIASES = [UV5XAlias, RT5RAlias, RT5RVAlias, RT5Alias, RH5RAlias,
1777
               ROUV5REXAlias, A5RAlias, TenwayUV5RPro]
1778

    
1779

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

    
1787
    def _is_orig(self):
1788
        # Override this for F11 to always return False
1789
        return False
1790

    
1791

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

    
1801
    def _is_orig(self):
1802
        # Override this for UV82 to always return False
1803
        return False
1804

    
1805

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

    
1812
    def get_features(self):
1813
        rf = BaofengUV5R.get_features(self)
1814
        rf.valid_bands = [self._vhf_range,
1815
                          (200000000, 260000000),
1816
                          self._uhf_range]
1817
        return rf
1818

    
1819

    
1820
@directory.register
1821
class BaofengUV6Radio(BaofengUV5R):
1822

    
1823
    """Baofeng UV-6/UV-7"""
1824
    VENDOR = "Baofeng"
1825
    MODEL = "UV-6"
1826
    _basetype = BASETYPE_UV6
1827
    _idents = [UV5R_MODEL_UV6,
1828
               UV5R_MODEL_UV6_ORIG
1829
               ]
1830

    
1831
    def get_features(self):
1832
        rf = BaofengUV5R.get_features(self)
1833
        rf.memory_bounds = (1, 128)
1834
        return rf
1835

    
1836
    def _get_mem(self, number):
1837
        return self._memobj.memory[number - 1]
1838

    
1839
    def _get_nam(self, number):
1840
        return self._memobj.names[number - 1]
1841

    
1842
    def _set_mem(self, number):
1843
        return self._memobj.memory[number - 1]
1844

    
1845
    def _set_nam(self, number):
1846
        return self._memobj.names[number - 1]
1847

    
1848
    def _is_orig(self):
1849
        # Override this for UV6 to always return False
1850
        return False
1851

    
1852

    
1853
@directory.register
1854
class IntekKT980Radio(BaofengUV5R):
1855
    VENDOR = "Intek"
1856
    MODEL = "KT-980HP"
1857
    _basetype = BASETYPE_KT980HP
1858
    _idents = [UV5R_MODEL_291]
1859
    _vhf_range = (130000000, 180000000)
1860
    _uhf_range = (400000000, 521000000)
1861

    
1862
    def get_features(self):
1863
        rf = BaofengUV5R.get_features(self)
1864
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1865
        return rf
1866

    
1867
    def _is_orig(self):
1868
        # Override this for KT980HP to always return False
1869
        return False
1870

    
1871

    
1872
class ROGA5SAlias(chirp_common.Alias):
1873
    VENDOR = "Radioddity"
1874
    MODEL = "GA-5S"
1875

    
1876

    
1877
@directory.register
1878
class BaofengBFF8HPRadio(BaofengUV5R):
1879
    VENDOR = "Baofeng"
1880
    MODEL = "BF-F8HP"
1881
    ALIASES = [RT5_TPAlias, ROGA5SAlias, UV5XPAlias]
1882
    _basetype = BASETYPE_F8HP
1883
    _idents = [UV5R_MODEL_291,
1884
               UV5R_MODEL_A58
1885
               ]
1886
    _vhf_range = (130000000, 180000000)
1887
    _uhf_range = (400000000, 521000000)
1888

    
1889
    def get_features(self):
1890
        rf = BaofengUV5R.get_features(self)
1891
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1892
        return rf
1893

    
1894
    def _is_orig(self):
1895
        # Override this for BFF8HP to always return False
1896
        return False
1897

    
1898

    
1899
@directory.register
1900
class BaofengUV-5XPRadio(BaofengUV5R):
1901
    VENDOR = "Baofeng"
1902
    MODEL = "UV-5XP"
1903
    _basetype = BASETYPE_F8HP
1904
    _idents = [UV5R_MODEL_291]
1905
    _vhf_range = (130000000, 180000000)
1906
    _uhf_range = (400000000, 521000000)
1907

    
1908
    def get_features(self):
1909
        rf = BaofengUV5R.get_features(self)
1910
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1911
        return rf
1912

    
1913
    def _is_orig(self):
1914
        # Override this for UV5XP to always return False
1915
        return False
1916

    
1917

    
1918
@directory.register
1919
class BaofengUV82HPRadio(BaofengUV5R):
1920
    VENDOR = "Baofeng"
1921
    MODEL = "UV-82HP"
1922
    _basetype = BASETYPE_UV82HP
1923
    _idents = [UV5R_MODEL_UV82]
1924
    _vhf_range = (136000000, 175000000)
1925
    _uhf_range = (400000000, 521000000)
1926

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

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

    
1936

    
1937
@directory.register
1938
class RadioddityUV5RX3Radio(BaofengUV5R):
1939
    VENDOR = "Radioddity"
1940
    MODEL = "UV-5RX3"
1941

    
1942
    def get_features(self):
1943
        rf = BaofengUV5R.get_features(self)
1944
        rf.valid_bands = [self._vhf_range,
1945
                          (200000000, 260000000),
1946
                          self._uhf_range]
1947
        return rf
1948

    
1949
    @classmethod
1950
    def match_model(cls, filename, filedata):
1951
        return False