Project

General

Profile

Bug #6567 » uv5r_uv-6_test5.py

Jim Unroe, 08/31/2020 05:06 AM

 
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
    if radio.MODEL != "UV-6":
581
        # Auxiliary block starts at 0x1ECO (?)
582
        for i in range(0x1EC0, 0x2000, 0x40):
583
            data += _read_block(radio, i, 0x40, False)
584

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

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

    
591

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

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

    
601

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

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

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

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

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

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

    
654
    if radio.MODEL == "UV-6":
655
        image_matched_radio = True
656

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

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

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

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

    
681
UV5R_POWER_LEVELS = [chirp_common.PowerLevel("High", watts=4.00),
682
                     chirp_common.PowerLevel("Low",  watts=1.00)]
683

    
684
UV5R_POWER_LEVELS3 = [chirp_common.PowerLevel("High", watts=8.00),
685
                      chirp_common.PowerLevel("Med",  watts=4.00),
686
                      chirp_common.PowerLevel("Low",  watts=1.00)]
687

    
688
UV5R_DTCS = sorted(chirp_common.DTCS_CODES + [645])
689

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

    
693

    
694
def model_match(cls, data):
695
    """Match the opened/downloaded image to the correct version"""
696

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

    
707

    
708
class BaofengUV5R(chirp_common.CloneModeRadio):
709

    
710
    """Baofeng UV-5R"""
711
    VENDOR = "Baofeng"
712
    MODEL = "UV-5R"
713
    BAUD_RATE = 9600
714

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

    
730
    _ranges_main = [
731
                    (0x0008, 0x1808),
732
                   ]
733
    _ranges_aux = [
734
                   (0x1EC0, 0x2000),
735
                  ]
736
    _valid_chars = UV5R_CHARSET
737

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

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

    
783
        normal_bands = [self._vhf_range, self._uhf_range]
784
        rax_bands = [self._vhf_range, self._220_range]
785

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

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

    
803
        if match_size and match_model:
804
            return True
805
        else:
806
            return False
807

    
808
    def process_mmap(self):
809
        self._memobj = bitwise.parse(MEM_FORMAT % self._mem_params, self._mmap)
810

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

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

    
828
    def get_raw_memory(self, number):
829
        return repr(self._memobj.memory[number])
830

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

    
837
    def _get_mem(self, number):
838
        return self._memobj.memory[number]
839

    
840
    def _get_nam(self, number):
841
        return self._memobj.names[number]
842

    
843
    def get_memory(self, number):
844
        _mem = self._get_mem(number)
845
        _nam = self._get_nam(number)
846

    
847
        mem = chirp_common.Memory()
848
        mem.number = number
849

    
850
        if _mem.get_raw()[0] == "\xff":
851
            mem.empty = True
852
            return mem
853

    
854
        mem.freq = int(_mem.rxfreq) * 10
855

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

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

    
875
        dtcs_pol = ["N", "N"]
876

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

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

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

    
919
        mem.dtcs_polarity = "".join(dtcs_pol)
920

    
921
        if not _mem.scan:
922
            mem.skip = "S"
923

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

    
935
        mem.mode = _mem.wide and "FM" or "NFM"
936

    
937
        mem.extra = RadioSettingGroup("Extra", "extra")
938

    
939
        rs = RadioSetting("bcl", "BCL",
940
                          RadioSettingValueBoolean(_mem.bcl))
941
        mem.extra.append(rs)
942

    
943
        rs = RadioSetting("pttid", "PTT ID",
944
                          RadioSettingValueList(PTTID_LIST,
945
                                                PTTID_LIST[_mem.pttid]))
946
        mem.extra.append(rs)
947

    
948
        rs = RadioSetting("scode", "PTT ID Code",
949
                          RadioSettingValueList(PTTIDCODE_LIST,
950
                                                PTTIDCODE_LIST[_mem.scode]))
951
        mem.extra.append(rs)
952

    
953
        return mem
954

    
955
    def _set_mem(self, number):
956
        return self._memobj.memory[number]
957

    
958
    def _set_nam(self, number):
959
        return self._memobj.names[number]
960

    
961
    def set_memory(self, mem):
962
        _mem = self._get_mem(mem.number)
963
        _nam = self._get_nam(mem.number)
964

    
965
        if mem.empty:
966
            _mem.set_raw("\xff" * 16)
967
            _nam.set_raw("\xff" * 16)
968
            return
969

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

    
984
        _mem.set_raw("\x00" * 16)
985

    
986
        _mem.rxfreq = mem.freq / 10
987

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

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

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

    
1036
        if txmode == "DTCS" and mem.dtcs_polarity[0] == "R":
1037
            _mem.txtone += 0x69
1038
        if rxmode == "DTCS" and mem.dtcs_polarity[1] == "R":
1039
            _mem.rxtone += 0x69
1040

    
1041
        _mem.scan = mem.skip != "S"
1042
        _mem.wide = mem.mode == "FM"
1043

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

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

    
1059
        for setting in mem.extra:
1060
            setattr(_mem, setting.get_name(), setting.value)
1061

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

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

    
1082
        raise Exception("Unrecognized firmware version string")
1083

    
1084
    def _my_upper_band(self):
1085
        band_tag = _upper_band_from_image(self)
1086
        return band_tag
1087

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

    
1099
        group = RadioSettings(basic, advanced)
1100

    
1101
        rs = RadioSetting("squelch", "Carrier Squelch Level",
1102
                          RadioSettingValueInteger(0, 9, _settings.squelch))
1103
        basic.append(rs)
1104

    
1105
        rs = RadioSetting("save", "Battery Saver",
1106
                          RadioSettingValueList(
1107
                              SAVE_LIST, SAVE_LIST[_settings.save]))
1108
        basic.append(rs)
1109

    
1110
        rs = RadioSetting("vox", "VOX Sensitivity",
1111
                          RadioSettingValueList(
1112
                              VOX_LIST, VOX_LIST[_settings.vox]))
1113
        advanced.append(rs)
1114

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

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

    
1128
        rs = RadioSetting("tdr", "Dual Watch",
1129
                          RadioSettingValueBoolean(_settings.tdr))
1130
        advanced.append(rs)
1131

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

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

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

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

    
1161
        rs = RadioSetting("beep", "Beep",
1162
                          RadioSettingValueBoolean(_settings.beep))
1163
        basic.append(rs)
1164

    
1165
        rs = RadioSetting("timeout", "Timeout Timer",
1166
                          RadioSettingValueList(
1167
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
1168
        basic.append(rs)
1169

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1281
        if isinstance(self, BaofengUV82Radio):
1282
            # this is an UV-82C only feature
1283
            rs = RadioSetting("singleptt", "Single PTT (UV-82C 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("singleptt", "Single PTT (BTech UV-82HP only)",
1290
                              RadioSettingValueBoolean(_settings.singleptt))
1291
            advanced.append(rs)
1292

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

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

    
1304
        other = RadioSettingGroup("other", "Other Settings")
1305
        group.append(other)
1306

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1459
            def convert_bytes_to_offset(bytes):
1460
                real_offset = 0
1461
                for byte in bytes:
1462
                    real_offset = (real_offset * 10) + byte
1463
                return chirp_common.format_freq(real_offset * 10000)
1464

    
1465
            def apply_offset(setting, obj):
1466
                value = chirp_common.parse_freq(str(setting.value)) / 10000
1467
                for i in range(3, -1, -1):
1468
                    obj.offset[i] = value % 10
1469
                    value /= 10
1470

    
1471
            val1a = RadioSettingValueString(
1472
                0, 10, convert_bytes_to_offset(_vfoa.offset))
1473
            rs = RadioSetting("vfoa.offset",
1474
                              "VFO A Offset (0.00-69.95)", val1a)
1475
            rs.set_apply_callback(apply_offset, _vfoa)
1476
            workmode.append(rs)
1477

    
1478
            val1b = RadioSettingValueString(
1479
                0, 10, convert_bytes_to_offset(_vfob.offset))
1480
            rs = RadioSetting("vfob.offset",
1481
                              "VFO B Offset (0.00-69.95)", val1b)
1482
            rs.set_apply_callback(apply_offset, _vfob)
1483
            workmode.append(rs)
1484

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

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

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

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

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

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

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

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

    
1551
        fm_preset = RadioSettingGroup("fm_preset", "FM Radio Preset")
1552
        group.append(fm_preset)
1553

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

    
1564
        dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
1565
        group.append(dtmf)
1566
        dtmfchars = "0123456789 *#ABCD"
1567

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

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

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

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

    
1604
        rs = RadioSetting("ani.aniid", "ANI ID",
1605
                          RadioSettingValueList(PTTID_LIST,
1606
                                                PTTID_LIST[_ani.aniid]))
1607
        dtmf.append(rs)
1608

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

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

    
1626
        rs = RadioSetting("dtmfst", "DTMF Sidetone",
1627
                          RadioSettingValueList(DTMFST_LIST,
1628
                                                DTMFST_LIST[_settings.dtmfst]))
1629
        dtmf.append(rs)
1630

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

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

    
1649
        rs = RadioSetting("pttlt", "PTT ID Delay",
1650
                          RadioSettingValueInteger(0, 50, _settings.pttlt))
1651
        dtmf.append(rs)
1652

    
1653
        #if not self._is_orig():
1654
        if not self._is_orig() and self.MODEL != "UV-6":
1655
            service = RadioSettingGroup("service", "Service Settings")
1656
            group.append(service)
1657

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

    
1672
        return group
1673

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

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

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

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

    
1733

    
1734
class UV5XAlias(chirp_common.Alias):
1735
    VENDOR = "Baofeng"
1736
    MODEL = "UV-5X"
1737

    
1738

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

    
1743

    
1744
class RT5RVAlias(chirp_common.Alias):
1745
    VENDOR = "Retevis"
1746
    MODEL = "RT-5RV"
1747

    
1748

    
1749
class RT5Alias(chirp_common.Alias):
1750
    VENDOR = "Retevis"
1751
    MODEL = "RT5"
1752

    
1753

    
1754
class RT5_TPAlias(chirp_common.Alias):
1755
    VENDOR = "Retevis"
1756
    MODEL = "RT5(tri-power)"
1757

    
1758

    
1759
class RH5RAlias(chirp_common.Alias):
1760
    VENDOR = "Rugged"
1761
    MODEL = "RH5R"
1762

    
1763

    
1764
class ROUV5REXAlias(chirp_common.Alias):
1765
    VENDOR = "Radioddity"
1766
    MODEL = "UV-5R EX"
1767

    
1768

    
1769
class A5RAlias(chirp_common.Alias):
1770
    VENDOR = "Ansoko"
1771
    MODEL = "A-5R"
1772

    
1773

    
1774
class TenwayUV5RPro(chirp_common.Alias):
1775
    VENDOR = 'Tenway'
1776
    MODEL = 'UV-5R Pro'
1777

    
1778

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

    
1784

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

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

    
1796

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

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

    
1810

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

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

    
1824

    
1825
@directory.register
1826
class BaofengUV6Radio(BaofengUV5R):
1827

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

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

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

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

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

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

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

    
1857

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

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

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

    
1877

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

    
1882

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

    
1887

    
1888
@directory.register
1889
class BaofengBFF8HPRadio(BaofengUV5R):
1890
    VENDOR = "Baofeng"
1891
    MODEL = "BF-F8HP"
1892
    ALIASES = [RT5_TPAlias, ROGA5SAlias, UV5XPAlias]
1893
    _basetype = BASETYPE_F8HP
1894
    _idents = [UV5R_MODEL_291,
1895
               UV5R_MODEL_A58
1896
               ]
1897
    _vhf_range = (130000000, 180000000)
1898
    _uhf_range = (400000000, 521000000)
1899
    _tri_power = True
1900

    
1901
    def get_features(self):
1902
        rf = BaofengUV5R.get_features(self)
1903
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1904
        return rf
1905

    
1906
    def _is_orig(self):
1907
        # Override this for BFF8HP to always return False
1908
        return False
1909

    
1910

    
1911
class TenwayUV82Pro(chirp_common.Alias):
1912
    VENDOR = 'Tenway'
1913
    MODEL = 'UV-82 Pro'
1914

    
1915

    
1916
@directory.register
1917
class BaofengUV82HPRadio(BaofengUV5R):
1918
    VENDOR = "Baofeng"
1919
    MODEL = "UV-82HP"
1920
    ALIASES = [TenwayUV82Pro]
1921
    _basetype = BASETYPE_UV82HP
1922
    _idents = [UV5R_MODEL_UV82]
1923
    _vhf_range = (136000000, 175000000)
1924
    _uhf_range = (400000000, 521000000)
1925
    _tri_power = True
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
class TDUV5RRadio(chirp_common.Alias):
1938
    VENDOR = "TIDRADIO"
1939
    MODEL = "TD-UV5R TriPower"
1940

    
1941

    
1942
@directory.register
1943
class RadioddityUV5RX3Radio(BaofengUV5R):
1944
    VENDOR = "Radioddity"
1945
    MODEL = "UV-5RX3"
1946
    ALIASES = [TDUV5RRadio]
1947

    
1948
    def get_features(self):
1949
        rf = BaofengUV5R.get_features(self)
1950
        rf.valid_bands = [self._vhf_range,
1951
                          (200000000, 260000000),
1952
                          self._uhf_range]
1953
        return rf
1954

    
1955
    @classmethod
1956
    def match_model(cls, filename, filedata):
1957
        return False
(6-6/7)