Project

General

Profile

New Model #9910 ยป uv82hp_UPPER-lower_case_names_#1.py

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

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

    
196
#seekto 0x0F56;
197
u16 fm_presets;
198

    
199
#seekto 0x1008;
200
struct {
201
  char name[7];
202
  u8 unknown2[9];
203
} names[128];
204

    
205
#seekto 0x1818;
206
struct {
207
  char line1[7];
208
  char line2[7];
209
} sixpoweron_msg;
210

    
211
#seekto 0x%04X;
212
struct {
213
  char line1[7];
214
  char line2[7];
215
} poweron_msg;
216

    
217
#seekto 0x1838;
218
struct {
219
  char line1[7];
220
  char line2[7];
221
} firmware_msg;
222

    
223
struct limit {
224
  u8 enable;
225
  bbcd lower[2];
226
  bbcd upper[2];
227
};
228

    
229
#seekto 0x1908;
230
struct {
231
  struct limit vhf;
232
  struct limit uhf;
233
} limits_new;
234

    
235
#seekto 0x1910;
236
struct {
237
  u8 unknown1[2];
238
  struct limit vhf;
239
  u8 unknown2;
240
  u8 unknown3[8];
241
  u8 unknown4[2];
242
  struct limit uhf;
243
} limits_old;
244

    
245
struct squelch {
246
  u8 sql0;
247
  u8 sql1;
248
  u8 sql2;
249
  u8 sql3;
250
  u8 sql4;
251
  u8 sql5;
252
  u8 sql6;
253
  u8 sql7;
254
  u8 sql8;
255
  u8 sql9;
256
};
257

    
258
#seekto 0x18A8;
259
struct {
260
  struct squelch vhf;
261
  u8 unknown1[6];
262
  u8 unknown2[16];
263
  struct squelch uhf;
264
} squelch_new;
265

    
266
#seekto 0x18E8;
267
struct {
268
  struct squelch vhf;
269
  u8 unknown[6];
270
  struct squelch uhf;
271
} squelch_old;
272

    
273
"""
274

    
275
# 0x1EC0 - 0x2000
276

    
277
vhf_220_radio = "\x02"
278

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

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

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

    
357
GMRS_FREQS1 = [462.5625, 462.5875, 462.6125, 462.6375, 462.6625,
358
               462.6875, 462.7125]
359
GMRS_FREQS2 = [467.5625, 467.5875, 467.6125, 467.6375, 467.6625,
360
               467.6875, 467.7125]
361
GMRS_FREQS3 = [462.5500, 462.5750, 462.6000, 462.6250, 462.6500,
362
               462.6750, 462.7000, 462.7250]
363
GMRS_FREQS = GMRS_FREQS1 + GMRS_FREQS2 + GMRS_FREQS3 * 2
364

    
365

    
366
def _do_status(radio, block):
367
    status = chirp_common.Status()
368
    status.msg = "Cloning"
369
    status.cur = block
370
    status.max = radio.get_memsize()
371
    radio.status_fn(status)
372

    
373
UV5R_MODEL_ORIG = "\x50\xBB\xFF\x01\x25\x98\x4D"
374
UV5R_MODEL_291 = "\x50\xBB\xFF\x20\x12\x07\x25"
375
UV5R_MODEL_F11 = "\x50\xBB\xFF\x13\xA1\x11\xDD"
376
UV5R_MODEL_UV82 = "\x50\xBB\xFF\x20\x13\x01\x05"
377
UV5R_MODEL_UV6 = "\x50\xBB\xFF\x20\x12\x08\x23"
378
UV5R_MODEL_UV6_ORIG = "\x50\xBB\xFF\x12\x03\x98\x4D"
379
UV5R_MODEL_A58 = "\x50\xBB\xFF\x20\x14\x04\x13"
380
UV5R_MODEL_UV5G = "\x50\xBB\xFF\x20\x12\x06\x25"
381

    
382

    
383
def _upper_band_from_data(data):
384
    return data[0x03:0x04]
385

    
386

    
387
def _upper_band_from_image(radio):
388
    return _upper_band_from_data(radio.get_mmap())
389

    
390

    
391
def _firmware_version_from_data(data, version_start, version_stop):
392
    version_tag = data[version_start:version_stop]
393
    return version_tag
394

    
395

    
396
def _firmware_version_from_image(radio):
397
    version = _firmware_version_from_data(radio.get_mmap(),
398
                                          radio._fw_ver_file_start,
399
                                          radio._fw_ver_file_stop)
400
    LOG.debug("_firmware_version_from_image: " + util.hexprint(version))
401
    return version
402

    
403

    
404
def _do_ident(radio, magic, secondack=True):
405
    serial = radio.pipe
406
    serial.timeout = 1
407

    
408
    LOG.info("Sending Magic: %s" % util.hexprint(magic))
409
    for byte in magic:
410
        serial.write(byte)
411
        time.sleep(0.01)
412
    ack = serial.read(1)
413

    
414
    if ack != "\x06":
415
        if ack:
416
            LOG.debug(repr(ack))
417
        raise errors.RadioError("Radio did not respond")
418

    
419
    serial.write("\x02")
420

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

    
432
    # Ok, get the response
433
    response = ""
434
    for i in range(1, 13):
435
        byte = serial.read(1)
436
        response += byte
437
        # stop reading once the last byte ("\xdd") is encountered
438
        if byte == "\xdd":
439
            break
440

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

    
457
    if secondack:
458
        serial.write("\x06")
459
        ack = serial.read(1)
460
        if ack != "\x06":
461
            raise errors.RadioError("Radio refused clone")
462

    
463
    return ident
464

    
465

    
466
def _read_block(radio, start, size, first_command=False):
467
    msg = struct.pack(">BHB", ord("S"), start, size)
468
    radio.pipe.write(msg)
469

    
470
    if first_command is False:
471
        ack = radio.pipe.read(1)
472
        if ack != "\x06":
473
            raise errors.RadioError(
474
                "Radio refused to send second block 0x%04x" % start)
475

    
476
    answer = radio.pipe.read(4)
477
    if len(answer) != 4:
478
        raise errors.RadioError("Radio refused to send block 0x%04x" % start)
479

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

    
486
    chunk = radio.pipe.read(0x40)
487
    if not chunk:
488
        raise errors.RadioError("Radio did not send block 0x%04x" % start)
489
    elif len(chunk) != size:
490
        LOG.error("Chunk length was 0x%04i" % len(chunk))
491
        raise errors.RadioError("Radio sent incomplete block 0x%04x" % start)
492

    
493
    radio.pipe.write("\x06")
494
    time.sleep(0.05)
495

    
496
    return chunk
497

    
498

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

    
510

    
511
IDENT_BLACKLIST = {
512
    "\x50\x0D\x0C\x20\x16\x03\x28": "Radio identifies as BTECH UV-5X3",
513
    "\x50\xBB\xFF\x20\x12\x06\x25": "Radio identifies as Radioddity UV-5G",
514
}
515

    
516

    
517
def _ident_radio(radio):
518
    for magic in radio._idents:
519
        error = None
520
        try:
521
            data = _do_ident(radio, magic)
522
            return data
523
        except errors.RadioError, e:
524
            LOG.error("uv5r._ident_radio: %s", e)
525
            error = e
526
            time.sleep(2)
527

    
528
    for magic, reason in IDENT_BLACKLIST.items():
529
        try:
530
            _do_ident(radio, magic, secondack=False)
531
        except errors.RadioError as e:
532
            # No match, try the next one
533
            continue
534

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

    
543
    if error:
544
        raise error
545
    raise errors.RadioError("Radio did not respond")
546

    
547

    
548
def _do_download(radio):
549
    data = _ident_radio(radio)
550

    
551
    radio_version = _get_radio_firmware_version(radio)
552
    LOG.info("Radio Version is %s" % repr(radio_version))
553

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

    
585
    # Main block
586
    LOG.debug("downloading main block...")
587
    for i in range(0, 0x1800, 0x40):
588
        data += _read_block(radio, i, 0x40, False)
589
        _do_status(radio, i)
590
    _do_status(radio, radio.get_memsize())
591
    LOG.debug("done.")
592
    if radio._aux_block:
593
        LOG.debug("downloading aux block...")
594
        # Auxiliary block starts at 0x1ECO (?)
595
        for i in range(0x1EC0, 0x2000, 0x40):
596
            data += _read_block(radio, i, 0x40, False)
597

    
598
    if append_model:
599
        data += radio.MODEL.ljust(8)
600

    
601
    LOG.debug("done.")
602
    return memmap.MemoryMap(data)
603

    
604

    
605
def _send_block(radio, addr, data):
606
    msg = struct.pack(">BHB", ord("X"), addr, len(data))
607
    radio.pipe.write(msg + data)
608
    time.sleep(0.05)
609

    
610
    ack = radio.pipe.read(1)
611
    if ack != "\x06":
612
        raise errors.RadioError("Radio refused to accept block 0x%04x" % addr)
613

    
614

    
615
def _do_upload(radio):
616
    ident = _ident_radio(radio)
617
    radio_upper_band = ident[3:4]
618
    image_upper_band = _upper_band_from_image(radio)
619

    
620
    if image_upper_band == vhf_220_radio or radio_upper_band == vhf_220_radio:
621
        if image_upper_band != radio_upper_band:
622
            raise errors.RadioError("Image not supported by radio")
623

    
624
    image_version = _firmware_version_from_image(radio)
625
    radio_version = _get_radio_firmware_version(radio)
626
    LOG.info("Image Version is %s" % repr(image_version))
627
    LOG.info("Radio Version is %s" % repr(radio_version))
628

    
629
    # default ranges
630
    _ranges_main_default = [
631
        (0x0008, 0x0CF8),
632
        (0x0D08, 0x0DF8),
633
        (0x0E08, 0x1808)
634
        ]
635
    _ranges_aux_default = [
636
        (0x1EC0, 0x1EF0),
637
        ]
638

    
639
    # extra aux ranges
640
    _ranges_aux_extra = [
641
        (0x1F60, 0x1F70),
642
        (0x1F80, 0x1F90),
643
        (0x1FC0, 0x1FD0)
644
        ]
645

    
646
    if image_version == radio_version:
647
        image_matched_radio = True
648
        if image_version.startswith("HN5RV"):
649
            ranges_main = _ranges_main_default
650
            ranges_aux = _ranges_aux_default + _ranges_aux_extra
651
        elif image_version == 0xFF * 7:
652
            ranges_main = _ranges_main_default
653
            ranges_aux = _ranges_aux_default + _ranges_aux_extra
654
        else:
655
            ranges_main = radio._ranges_main
656
            ranges_aux = radio._ranges_aux
657
    elif any(type in radio_version for type in radio._basetype):
658
        image_matched_radio = False
659
        ranges_main = _ranges_main_default
660
        ranges_aux = _ranges_aux_default
661
    else:
662
        msg = ("The upload was stopped because the firmware "
663
               "version of the image (%s) does not match that "
664
               "of the radio (%s).")
665
        raise errors.RadioError(msg % (image_version, radio_version))
666

    
667
    if not radio._aux_block:
668
        image_matched_radio = True
669

    
670
    # Main block
671
    for start_addr, end_addr in ranges_main:
672
        for i in range(start_addr, end_addr, 0x10):
673
            _send_block(radio, i - 0x08, radio.get_mmap()[i:i + 0x10])
674
            _do_status(radio, i)
675
        _do_status(radio, radio.get_memsize())
676

    
677
    if len(radio.get_mmap().get_packed()) == 0x1808:
678
        LOG.info("Old image, not writing aux block")
679
        return  # Old image, no aux block
680

    
681
    # Auxiliary block at radio address 0x1EC0, our offset 0x1808
682
    for start_addr, end_addr in ranges_aux:
683
        for i in range(start_addr, end_addr, 0x10):
684
            addr = 0x1808 + (i - 0x1EC0)
685
            _send_block(radio, i, radio.get_mmap()[addr:addr + 0x10])
686

    
687
    if not image_matched_radio:
688
        msg = ("Upload finished, but the 'Other Settings' "
689
               "could not be sent because the firmware "
690
               "version of the image (%s) does not match "
691
               "that of the radio (%s).")
692
        raise errors.RadioError(msg % (image_version, radio_version))
693

    
694
UV5R_POWER_LEVELS = [chirp_common.PowerLevel("High", watts=4.00),
695
                     chirp_common.PowerLevel("Low",  watts=1.00)]
696

    
697
UV5R_POWER_LEVELS3 = [chirp_common.PowerLevel("High", watts=8.00),
698
                      chirp_common.PowerLevel("Med",  watts=4.00),
699
                      chirp_common.PowerLevel("Low",  watts=1.00)]
700

    
701
UV5R_DTCS = sorted(chirp_common.DTCS_CODES + [645])
702

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

    
706

    
707
def model_match(cls, data):
708
    """Match the opened/downloaded image to the correct version"""
709

    
710
    if len(data) == 0x1950:
711
        rid = data[0x1948:0x1950]
712
        return rid.startswith(cls.MODEL)
713
    elif len(data) == 0x1948:
714
        rid = data[cls._fw_ver_file_start:cls._fw_ver_file_stop]
715
        if any(type in rid for type in cls._basetype):
716
            return True
717
    else:
718
        return False
719

    
720

    
721
class BaofengUV5R(chirp_common.CloneModeRadio):
722

    
723
    """Baofeng UV-5R"""
724
    VENDOR = "Baofeng"
725
    MODEL = "UV-5R"
726
    BAUD_RATE = 9600
727

    
728
    _memsize = 0x1808
729
    _basetype = BASETYPE_UV5R
730
    _idents = [UV5R_MODEL_291,
731
               UV5R_MODEL_ORIG
732
               ]
733
    _vhf_range = (136000000, 174000000)
734
    _220_range = (220000000, 260000000)
735
    _uhf_range = (400000000, 520000000)
736
    _aux_block = True
737
    _tri_power = False
738
    _gmrs = False
739
    _mem_params = (0x1828  # poweron_msg offset
740
                   )
741
    # offset of fw version in image file
742
    _fw_ver_file_start = 0x1838
743
    _fw_ver_file_stop = 0x1846
744

    
745
    _ranges_main = [
746
                    (0x0008, 0x1808),
747
                   ]
748
    _ranges_aux = [
749
                   (0x1EC0, 0x2000),
750
                  ]
751
    _valid_chars = UV5R_CHARSET
752

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

    
779
    def get_features(self):
780
        rf = chirp_common.RadioFeatures()
781
        rf.has_settings = True
782
        rf.has_bank = False
783
        rf.has_cross = True
784
        rf.has_rx_dtcs = True
785
        rf.has_tuning_step = False
786
        rf.can_odd_split = True
787
        rf.valid_name_length = 7
788
        rf.valid_characters = self._valid_chars
789
        rf.valid_skips = ["", "S"]
790
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
791
        rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone",
792
                                "->Tone", "->DTCS", "DTCS->", "DTCS->DTCS"]
793
        rf.valid_power_levels = UV5R_POWER_LEVELS
794
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
795
        rf.valid_modes = ["FM", "NFM"]
796
        rf.valid_tuning_steps = STEPS
797
        rf.valid_dtcs_codes = UV5R_DTCS
798

    
799
        normal_bands = [self._vhf_range, self._uhf_range]
800
        rax_bands = [self._vhf_range, self._220_range]
801

    
802
        if self._mmap is None:
803
            rf.valid_bands = [normal_bands[0], rax_bands[1], normal_bands[1]]
804
        elif not self._is_orig() and self._my_upper_band() == vhf_220_radio:
805
            rf.valid_bands = rax_bands
806
        else:
807
            rf.valid_bands = normal_bands
808
        rf.memory_bounds = (0, 127)
809
        return rf
810

    
811
    @classmethod
812
    def match_model(cls, filedata, filename):
813
        match_size = False
814
        match_model = False
815
        if len(filedata) in [0x1808, 0x1948, 0x1950]:
816
            match_size = True
817
        match_model = model_match(cls, filedata)
818

    
819
        if match_size and match_model:
820
            return True
821
        else:
822
            return False
823

    
824
    def process_mmap(self):
825
        self._memobj = bitwise.parse(MEM_FORMAT % self._mem_params, self._mmap)
826

    
827
    def validate_memory(self, mem):
828
        msgs = chirp_common.CloneModeRadio.validate_memory(self, mem)
829

    
830
        _msg_duplex2 = 'Memory location only supports "(None)" or "off"'
831
        _msg_duplex3 = 'Memory location only supports "(None)", "+" or "off"'
832

    
833
        if self._gmrs:
834
            if mem.number < 1 or mem.number > 30:
835
                if float(mem.freq) / 1000000 in GMRS_FREQS1:
836
                    if mem.duplex not in ['', 'off']:
837
                        # warn user wrong Duplex
838
                        msgs.append(chirp_common.ValidationError(_msg_duplex2))
839

    
840
                if float(mem.freq) / 1000000 in GMRS_FREQS2:
841
                    if mem.duplex not in ['', 'off']:
842
                        # warn user wrong Duplex
843
                        msgs.append(chirp_common.ValidationError(_msg_duplex2))
844

    
845
                if float(mem.freq) / 1000000 in GMRS_FREQS3:
846
                    if mem.duplex not in ['', '+', 'off']:
847
                        # warn user wrong Duplex
848
                        msgs.append(chirp_common.ValidationError(_msg_duplex3))
849

    
850
        return msgs
851

    
852
    def sync_in(self):
853
        try:
854
            self._mmap = _do_download(self)
855
        except errors.RadioError:
856
            raise
857
        except Exception, e:
858
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
859
        self.process_mmap()
860

    
861
    def sync_out(self):
862
        try:
863
            _do_upload(self)
864
        except errors.RadioError:
865
            raise
866
        except Exception, e:
867
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
868

    
869
    def get_raw_memory(self, number):
870
        return repr(self._memobj.memory[number])
871

    
872
    def _is_txinh(self, _mem):
873
        raw_tx = ""
874
        for i in range(0, 4):
875
            raw_tx += _mem.txfreq[i].get_raw()
876
        return raw_tx == "\xFF\xFF\xFF\xFF"
877

    
878
    def _get_mem(self, number):
879
        return self._memobj.memory[number]
880

    
881
    def _get_nam(self, number):
882
        return self._memobj.names[number]
883

    
884
    def get_memory(self, number):
885
        _mem = self._get_mem(number)
886
        _nam = self._get_nam(number)
887

    
888
        mem = chirp_common.Memory()
889
        mem.number = number
890

    
891
        if _mem.get_raw()[0] == "\xff":
892
            mem.empty = True
893
            return mem
894

    
895
        mem.freq = int(_mem.rxfreq) * 10
896

    
897
        if self._is_txinh(_mem):
898
            mem.duplex = "off"
899
            mem.offset = 0
900
        elif int(_mem.rxfreq) == int(_mem.txfreq):
901
            mem.duplex = ""
902
            mem.offset = 0
903
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 70000000:
904
            mem.duplex = "split"
905
            mem.offset = int(_mem.txfreq) * 10
906
        else:
907
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
908
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
909

    
910
        for char in _nam.name:
911
            if str(char) == "\xFF":
912
                char = " "  # The UV-5R software may have 0xFF mid-name
913
            mem.name += str(char)
914
        mem.name = mem.name.rstrip()
915

    
916
        dtcs_pol = ["N", "N"]
917

    
918
        if _mem.txtone in [0, 0xFFFF]:
919
            txmode = ""
920
        elif _mem.txtone >= 0x0258:
921
            txmode = "Tone"
922
            mem.rtone = int(_mem.txtone) / 10.0
923
        elif _mem.txtone <= 0x0258:
924
            txmode = "DTCS"
925
            if _mem.txtone > 0x69:
926
                index = _mem.txtone - 0x6A
927
                dtcs_pol[0] = "R"
928
            else:
929
                index = _mem.txtone - 1
930
            mem.dtcs = UV5R_DTCS[index]
931
        else:
932
            LOG.warn("Bug: txtone is %04x" % _mem.txtone)
933

    
934
        if _mem.rxtone in [0, 0xFFFF]:
935
            rxmode = ""
936
        elif _mem.rxtone >= 0x0258:
937
            rxmode = "Tone"
938
            mem.ctone = int(_mem.rxtone) / 10.0
939
        elif _mem.rxtone <= 0x0258:
940
            rxmode = "DTCS"
941
            if _mem.rxtone >= 0x6A:
942
                index = _mem.rxtone - 0x6A
943
                dtcs_pol[1] = "R"
944
            else:
945
                index = _mem.rxtone - 1
946
            mem.rx_dtcs = UV5R_DTCS[index]
947
        else:
948
            LOG.warn("Bug: rxtone is %04x" % _mem.rxtone)
949

    
950
        if txmode == "Tone" and not rxmode:
951
            mem.tmode = "Tone"
952
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
953
            mem.tmode = "TSQL"
954
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
955
            mem.tmode = "DTCS"
956
        elif rxmode or txmode:
957
            mem.tmode = "Cross"
958
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
959

    
960
        mem.dtcs_polarity = "".join(dtcs_pol)
961

    
962
        if not _mem.scan:
963
            mem.skip = "S"
964

    
965
        if self._tri_power:
966
            levels = UV5R_POWER_LEVELS3
967
        else:
968
            levels = UV5R_POWER_LEVELS
969
        try:
970
            mem.power = levels[_mem.lowpower]
971
        except IndexError:
972
            LOG.error("Radio reported invalid power level %s (in %s)" %
973
                      (_mem.lowpower, levels))
974
            mem.power = levels[0]
975

    
976
        mem.mode = _mem.wide and "FM" or "NFM"
977

    
978
        mem.extra = RadioSettingGroup("Extra", "extra")
979

    
980
        rs = RadioSetting("bcl", "BCL",
981
                          RadioSettingValueBoolean(_mem.bcl))
982
        mem.extra.append(rs)
983

    
984
        rs = RadioSetting("pttid", "PTT ID",
985
                          RadioSettingValueList(PTTID_LIST,
986
                                                PTTID_LIST[_mem.pttid]))
987
        mem.extra.append(rs)
988

    
989
        rs = RadioSetting("scode", "PTT ID Code",
990
                          RadioSettingValueList(PTTIDCODE_LIST,
991
                                                PTTIDCODE_LIST[_mem.scode]))
992
        mem.extra.append(rs)
993

    
994
        return mem
995

    
996
    def _set_mem(self, number):
997
        return self._memobj.memory[number]
998

    
999
    def _set_nam(self, number):
1000
        return self._memobj.names[number]
1001

    
1002
    def set_memory(self, mem):
1003
        _mem = self._get_mem(mem.number)
1004
        _nam = self._get_nam(mem.number)
1005

    
1006
        if mem.empty:
1007
            _mem.set_raw("\xff" * 16)
1008
            _nam.set_raw("\xff" * 16)
1009
            return
1010

    
1011
        was_empty = False
1012
        # same method as used in get_memory to find
1013
        # out whether a raw memory is empty
1014
        if _mem.get_raw()[0] == "\xff":
1015
            was_empty = True
1016
            LOG.debug("UV5R: this mem was empty")
1017
        else:
1018
            # memorize old extra-values before erasing the whole memory
1019
            # used to solve issue 4121
1020
            LOG.debug("mem was not empty, memorize extra-settings")
1021
            prev_bcl = _mem.bcl.get_value()
1022
            prev_scode = _mem.scode.get_value()
1023
            prev_pttid = _mem.pttid.get_value()
1024

    
1025
        _mem.set_raw("\x00" * 16)
1026

    
1027
        if self._gmrs:
1028
            if mem.number >= 1 and mem.number <= 30:
1029
                GMRS_FREQ = int(GMRS_FREQS[mem.number - 1] * 1000000)
1030
                mem.freq = GMRS_FREQ
1031
                if mem.number <= 22:
1032
                    mem.duplex = ''
1033
                    mem.offset = 0
1034
                    if mem.number >= 8 and mem.number <= 14:
1035
                        mem.mode = "NFM"
1036
                        mem.power = UV5R_POWER_LEVELS[1]
1037
                if mem.number > 22:
1038
                    mem.duplex = '+'
1039
                    mem.offset = 5000000
1040
            elif float(mem.freq) / 1000000 in GMRS_FREQS:
1041
                if float(mem.freq) / 1000000 in GMRS_FREQS2:
1042
                    mem.offset = 0
1043
                    mem.mode = "NFM"
1044
                    mem.power = UV5R_POWER_LEVELS[1]
1045
                if float(mem.freq) / 1000000 in GMRS_FREQS3:
1046
                    if mem.duplex == '+':
1047
                        mem.offset = 5000000
1048
                    else:
1049
                        mem.offset = 0
1050
            else:
1051
                mem.duplex = 'off'
1052
                mem.offset = 0
1053

    
1054
        _mem.rxfreq = mem.freq / 10
1055

    
1056
        if mem.duplex == "off":
1057
            for i in range(0, 4):
1058
                _mem.txfreq[i].set_raw("\xFF")
1059
        elif mem.duplex == "split":
1060
            _mem.txfreq = mem.offset / 10
1061
        elif mem.duplex == "+":
1062
            _mem.txfreq = (mem.freq + mem.offset) / 10
1063
        elif mem.duplex == "-":
1064
            _mem.txfreq = (mem.freq - mem.offset) / 10
1065
        else:
1066
            _mem.txfreq = mem.freq / 10
1067

    
1068
        _namelength = self.get_features().valid_name_length
1069
        for i in range(_namelength):
1070
            try:
1071
                _nam.name[i] = mem.name[i]
1072
            except IndexError:
1073
                _nam.name[i] = "\xFF"
1074

    
1075
        rxmode = txmode = ""
1076
        if mem.tmode == "Tone":
1077
            _mem.txtone = int(mem.rtone * 10)
1078
            _mem.rxtone = 0
1079
        elif mem.tmode == "TSQL":
1080
            _mem.txtone = int(mem.ctone * 10)
1081
            _mem.rxtone = int(mem.ctone * 10)
1082
        elif mem.tmode == "DTCS":
1083
            rxmode = txmode = "DTCS"
1084
            _mem.txtone = UV5R_DTCS.index(mem.dtcs) + 1
1085
            _mem.rxtone = UV5R_DTCS.index(mem.dtcs) + 1
1086
        elif mem.tmode == "Cross":
1087
            txmode, rxmode = mem.cross_mode.split("->", 1)
1088
            if txmode == "Tone":
1089
                _mem.txtone = int(mem.rtone * 10)
1090
            elif txmode == "DTCS":
1091
                _mem.txtone = UV5R_DTCS.index(mem.dtcs) + 1
1092
            else:
1093
                _mem.txtone = 0
1094
            if rxmode == "Tone":
1095
                _mem.rxtone = int(mem.ctone * 10)
1096
            elif rxmode == "DTCS":
1097
                _mem.rxtone = UV5R_DTCS.index(mem.rx_dtcs) + 1
1098
            else:
1099
                _mem.rxtone = 0
1100
        else:
1101
            _mem.rxtone = 0
1102
            _mem.txtone = 0
1103

    
1104
        if txmode == "DTCS" and mem.dtcs_polarity[0] == "R":
1105
            _mem.txtone += 0x69
1106
        if rxmode == "DTCS" and mem.dtcs_polarity[1] == "R":
1107
            _mem.rxtone += 0x69
1108

    
1109
        _mem.scan = mem.skip != "S"
1110
        _mem.wide = mem.mode == "FM"
1111

    
1112
        if mem.power:
1113
            if self._tri_power:
1114
                levels = [str(l) for l in UV5R_POWER_LEVELS3]
1115
                _mem.lowpower = levels.index(str(mem.power))
1116
            else:
1117
                _mem.lowpower = UV5R_POWER_LEVELS.index(mem.power)
1118
        else:
1119
            _mem.lowpower = 0
1120

    
1121
        if not was_empty:
1122
            # restoring old extra-settings (issue 4121
1123
            _mem.bcl.set_value(prev_bcl)
1124
            _mem.scode.set_value(prev_scode)
1125
            _mem.pttid.set_value(prev_pttid)
1126

    
1127
        for setting in mem.extra:
1128
            setattr(_mem, setting.get_name(), setting.value)
1129

    
1130
    def _is_orig(self):
1131
        version_tag = _firmware_version_from_image(self)
1132
        LOG.debug("@_is_orig, version_tag: %s", util.hexprint(version_tag))
1133
        try:
1134
            if 'BFB' in version_tag:
1135
                idx = version_tag.index("BFB") + 3
1136
                version = int(version_tag[idx:idx + 3])
1137
                return version < 291
1138
            return False
1139
        except:
1140
            pass
1141
        raise errors.RadioError("Unable to parse version string %s" %
1142
                                version_tag)
1143

    
1144
    def _my_version(self):
1145
        version_tag = _firmware_version_from_image(self)
1146
        if 'BFB' in version_tag:
1147
            idx = version_tag.index("BFB") + 3
1148
            return int(version_tag[idx:idx + 3])
1149

    
1150
        raise Exception("Unrecognized firmware version string")
1151

    
1152
    def _my_upper_band(self):
1153
        band_tag = _upper_band_from_image(self)
1154
        return band_tag
1155

    
1156
    def _get_settings(self):
1157
        _ani = self._memobj.ani
1158
        _fm_presets = self._memobj.fm_presets
1159
        _settings = self._memobj.settings
1160
        _squelch = self._memobj.squelch_new
1161
        _vfoa = self._memobj.vfoa
1162
        _vfob = self._memobj.vfob
1163
        _wmchannel = self._memobj.wmchannel
1164
        basic = RadioSettingGroup("basic", "Basic Settings")
1165
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
1166

    
1167
        group = RadioSettings(basic, advanced)
1168

    
1169
        rs = RadioSetting("squelch", "Carrier Squelch Level",
1170
                          RadioSettingValueInteger(0, 9, _settings.squelch))
1171
        basic.append(rs)
1172

    
1173
        rs = RadioSetting("save", "Battery Saver",
1174
                          RadioSettingValueList(
1175
                              SAVE_LIST, SAVE_LIST[_settings.save]))
1176
        basic.append(rs)
1177

    
1178
        rs = RadioSetting("vox", "VOX Sensitivity",
1179
                          RadioSettingValueList(
1180
                              VOX_LIST, VOX_LIST[_settings.vox]))
1181
        advanced.append(rs)
1182

    
1183
        if self.MODEL == "UV-6":
1184
            # NOTE: The UV-6 calls this byte voxenable, but the UV-5R calls it
1185
            # autolk. Since this is a minor difference, it will be referred to
1186
            # by the wrong name for the UV-6.
1187
            rs = RadioSetting("autolk", "Vox",
1188
                              RadioSettingValueBoolean(_settings.autolk))
1189
            advanced.append(rs)
1190

    
1191
        if self.MODEL != "UV-6":
1192
            rs = RadioSetting("abr", "Backlight Timeout",
1193
                              RadioSettingValueInteger(0, 24, _settings.abr))
1194
            basic.append(rs)
1195

    
1196
        rs = RadioSetting("tdr", "Dual Watch",
1197
                          RadioSettingValueBoolean(_settings.tdr))
1198
        advanced.append(rs)
1199

    
1200
        if self.MODEL == "UV-6":
1201
            rs = RadioSetting("tdrch", "Dual Watch Channel",
1202
                              RadioSettingValueList(
1203
                                  TDRCH_LIST, TDRCH_LIST[_settings.tdrch]))
1204
            advanced.append(rs)
1205

    
1206
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1207
                              RadioSettingValueBoolean(_settings.tdrab))
1208
            advanced.append(rs)
1209
        else:
1210
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1211
                              RadioSettingValueList(
1212
                                  TDRAB_LIST, TDRAB_LIST[_settings.tdrab]))
1213
            advanced.append(rs)
1214

    
1215
        if self.MODEL == "UV-6":
1216
            rs = RadioSetting("alarm", "Alarm Sound",
1217
                              RadioSettingValueBoolean(_settings.alarm))
1218
            advanced.append(rs)
1219

    
1220
        if _settings.almod > 0x02:
1221
            val = 0x01
1222
        else:
1223
            val = _settings.almod
1224
        rs = RadioSetting("almod", "Alarm Mode",
1225
                          RadioSettingValueList(
1226
                              ALMOD_LIST, ALMOD_LIST[val]))
1227
        advanced.append(rs)
1228

    
1229
        rs = RadioSetting("beep", "Beep",
1230
                          RadioSettingValueBoolean(_settings.beep))
1231
        basic.append(rs)
1232

    
1233
        rs = RadioSetting("timeout", "Timeout Timer",
1234
                          RadioSettingValueList(
1235
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
1236
        basic.append(rs)
1237

    
1238
        if ((self._is_orig() and self._my_version() < 251) or
1239
                (self.MODEL in ["TI-F8+", "TS-T9+"])):
1240
            rs = RadioSetting("voice", "Voice",
1241
                              RadioSettingValueBoolean(_settings.voice))
1242
            advanced.append(rs)
1243
        else:
1244
            rs = RadioSetting("voice", "Voice",
1245
                              RadioSettingValueList(
1246
                                  VOICE_LIST, VOICE_LIST[_settings.voice]))
1247
            advanced.append(rs)
1248

    
1249
        rs = RadioSetting("screv", "Scan Resume",
1250
                          RadioSettingValueList(
1251
                              RESUME_LIST, RESUME_LIST[_settings.screv]))
1252
        advanced.append(rs)
1253

    
1254
        if self.MODEL != "UV-6":
1255
            rs = RadioSetting("mdfa", "Display Mode (A)",
1256
                              RadioSettingValueList(
1257
                                  MODE_LIST, MODE_LIST[_settings.mdfa]))
1258
            basic.append(rs)
1259

    
1260
            rs = RadioSetting("mdfb", "Display Mode (B)",
1261
                              RadioSettingValueList(
1262
                                  MODE_LIST, MODE_LIST[_settings.mdfb]))
1263
            basic.append(rs)
1264

    
1265
        rs = RadioSetting("bcl", "Busy Channel Lockout",
1266
                          RadioSettingValueBoolean(_settings.bcl))
1267
        advanced.append(rs)
1268

    
1269
        if self.MODEL != "UV-6":
1270
            rs = RadioSetting("autolk", "Automatic Key Lock",
1271
                              RadioSettingValueBoolean(_settings.autolk))
1272
            advanced.append(rs)
1273

    
1274
        rs = RadioSetting("fmradio", "Broadcast FM Radio",
1275
                          RadioSettingValueBoolean(_settings.fmradio))
1276
        advanced.append(rs)
1277

    
1278
        if self.MODEL != "UV-6":
1279
            rs = RadioSetting("wtled", "Standby LED Color",
1280
                              RadioSettingValueList(
1281
                                  COLOR_LIST, COLOR_LIST[_settings.wtled]))
1282
            basic.append(rs)
1283

    
1284
            rs = RadioSetting("rxled", "RX LED Color",
1285
                              RadioSettingValueList(
1286
                                  COLOR_LIST, COLOR_LIST[_settings.rxled]))
1287
            basic.append(rs)
1288

    
1289
            rs = RadioSetting("txled", "TX LED Color",
1290
                              RadioSettingValueList(
1291
                                  COLOR_LIST, COLOR_LIST[_settings.txled]))
1292
            basic.append(rs)
1293

    
1294
        if isinstance(self, BaofengUV82Radio):
1295
            rs = RadioSetting("roger", "Roger Beep (TX)",
1296
                              RadioSettingValueBoolean(_settings.roger))
1297
            basic.append(rs)
1298
            rs = RadioSetting("rogerrx", "Roger Beep (RX)",
1299
                              RadioSettingValueList(
1300
                                  ROGERRX_LIST,
1301
                                  ROGERRX_LIST[_settings.rogerrx]))
1302
            basic.append(rs)
1303
        else:
1304
            rs = RadioSetting("roger", "Roger Beep",
1305
                              RadioSettingValueBoolean(_settings.roger))
1306
            basic.append(rs)
1307

    
1308
        rs = RadioSetting("ste", "Squelch Tail Eliminate (HT to HT)",
1309
                          RadioSettingValueBoolean(_settings.ste))
1310
        advanced.append(rs)
1311

    
1312
        rs = RadioSetting("rpste", "Squelch Tail Eliminate (repeater)",
1313
                          RadioSettingValueList(
1314
                              RPSTE_LIST, RPSTE_LIST[_settings.rpste]))
1315
        advanced.append(rs)
1316

    
1317
        rs = RadioSetting("rptrl", "STE Repeater Delay",
1318
                          RadioSettingValueList(
1319
                              STEDELAY_LIST, STEDELAY_LIST[_settings.rptrl]))
1320
        advanced.append(rs)
1321

    
1322
        if self.MODEL != "UV-6":
1323
            rs = RadioSetting("reset", "RESET Menu",
1324
                              RadioSettingValueBoolean(_settings.reset))
1325
            advanced.append(rs)
1326

    
1327
            rs = RadioSetting("menu", "All Menus",
1328
                              RadioSettingValueBoolean(_settings.menu))
1329
            advanced.append(rs)
1330

    
1331
        if self.MODEL == "F-11":
1332
            # this is an F-11 only feature
1333
            rs = RadioSetting("vfomrlock", "VFO/MR Button",
1334
                              RadioSettingValueBoolean(_settings.vfomrlock))
1335
            advanced.append(rs)
1336

    
1337
        if isinstance(self, BaofengUV82Radio):
1338
            # this is a UV-82C only feature
1339
            rs = RadioSetting("vfomrlock", "VFO/MR Switching (UV-82C only)",
1340
                              RadioSettingValueBoolean(_settings.vfomrlock))
1341
            advanced.append(rs)
1342

    
1343
        if self.MODEL == "UV-82HP":
1344
            # this is a UV-82HP only feature
1345
            rs = RadioSetting(
1346
                "vfomrlock", "VFO/MR Switching (BTech UV-82HP only)",
1347
                RadioSettingValueBoolean(_settings.vfomrlock))
1348
            advanced.append(rs)
1349

    
1350
        if isinstance(self, BaofengUV82Radio):
1351
            # this is an UV-82C only feature
1352
            rs = RadioSetting("singleptt", "Single PTT (UV-82C only)",
1353
                              RadioSettingValueBoolean(_settings.singleptt))
1354
            advanced.append(rs)
1355

    
1356
        if self.MODEL == "UV-82HP":
1357
            # this is an UV-82HP only feature
1358
            rs = RadioSetting("singleptt", "Single PTT (BTech UV-82HP only)",
1359
                              RadioSettingValueBoolean(_settings.singleptt))
1360
            advanced.append(rs)
1361

    
1362
        if self.MODEL == "UV-82HP":
1363
            # this is an UV-82HP only feature
1364
            rs = RadioSetting(
1365
                "tdrch", "Tone Burst Frequency (BTech UV-82HP only)",
1366
                RadioSettingValueList(RTONE_LIST, RTONE_LIST[_settings.tdrch]))
1367
            advanced.append(rs)
1368

    
1369
        if len(self._mmap.get_packed()) == 0x1808:
1370
            # Old image, without aux block
1371
            return group
1372

    
1373
        if self.MODEL != "UV-6":
1374
            other = RadioSettingGroup("other", "Other Settings")
1375
            group.append(other)
1376

    
1377
            def _filter(name):
1378
                filtered = ""
1379
                for char in str(name):
1380
                    if char in chirp_common.CHARSET_ASCII:
1381
                        filtered += char
1382
                    else:
1383
                        filtered += " "
1384
                return filtered
1385

    
1386
            _msg = self._memobj.firmware_msg
1387
            val = RadioSettingValueString(0, 7, _filter(_msg.line1))
1388
            val.set_mutable(False)
1389
            rs = RadioSetting("firmware_msg.line1", "Firmware Message 1", val)
1390
            other.append(rs)
1391

    
1392
            val = RadioSettingValueString(0, 7, _filter(_msg.line2))
1393
            val.set_mutable(False)
1394
            rs = RadioSetting("firmware_msg.line2", "Firmware Message 2", val)
1395
            other.append(rs)
1396

    
1397
            _msg = self._memobj.sixpoweron_msg
1398
            rs = RadioSetting("sixpoweron_msg.line1", "6+Power-On Message 1",
1399
                              RadioSettingValueString(
1400
                                  0, 7, _filter(_msg.line1)))
1401
            other.append(rs)
1402
            rs = RadioSetting("sixpoweron_msg.line2", "6+Power-On Message 2",
1403
                              RadioSettingValueString(
1404
                                  0, 7, _filter(_msg.line2)))
1405
            other.append(rs)
1406

    
1407
            _msg = self._memobj.poweron_msg
1408
            rs = RadioSetting("poweron_msg.line1", "Power-On Message 1",
1409
                              RadioSettingValueString(
1410
                                  0, 7, _filter(_msg.line1)))
1411
            other.append(rs)
1412
            rs = RadioSetting("poweron_msg.line2", "Power-On Message 2",
1413
                              RadioSettingValueString(
1414
                                  0, 7, _filter(_msg.line2)))
1415
            other.append(rs)
1416

    
1417
            rs = RadioSetting("ponmsg", "Power-On Message",
1418
                              RadioSettingValueList(
1419
                                  PONMSG_LIST, PONMSG_LIST[_settings.ponmsg]))
1420
            other.append(rs)
1421

    
1422
            if self._is_orig():
1423
                limit = "limits_old"
1424
            else:
1425
                limit = "limits_new"
1426

    
1427
            vhf_limit = getattr(self._memobj, limit).vhf
1428
            rs = RadioSetting("%s.vhf.lower" % limit, "VHF Lower Limit (MHz)",
1429
                              RadioSettingValueInteger(1, 1000,
1430
                                                       vhf_limit.lower))
1431
            other.append(rs)
1432

    
1433
            rs = RadioSetting("%s.vhf.upper" % limit, "VHF Upper Limit (MHz)",
1434
                              RadioSettingValueInteger(1, 1000,
1435
                                                       vhf_limit.upper))
1436
            other.append(rs)
1437

    
1438
            rs = RadioSetting("%s.vhf.enable" % limit, "VHF TX Enabled",
1439
                              RadioSettingValueBoolean(vhf_limit.enable))
1440
            other.append(rs)
1441

    
1442
            uhf_limit = getattr(self._memobj, limit).uhf
1443
            rs = RadioSetting("%s.uhf.lower" % limit, "UHF Lower Limit (MHz)",
1444
                              RadioSettingValueInteger(1, 1000,
1445
                                                       uhf_limit.lower))
1446
            other.append(rs)
1447
            rs = RadioSetting("%s.uhf.upper" % limit, "UHF Upper Limit (MHz)",
1448
                              RadioSettingValueInteger(1, 1000,
1449
                                                       uhf_limit.upper))
1450
            other.append(rs)
1451
            rs = RadioSetting("%s.uhf.enable" % limit, "UHF TX Enabled",
1452
                              RadioSettingValueBoolean(uhf_limit.enable))
1453
            other.append(rs)
1454

    
1455
        if self.MODEL != "UV-6":
1456
            workmode = RadioSettingGroup("workmode", "Work Mode Settings")
1457
            group.append(workmode)
1458

    
1459
            rs = RadioSetting("displayab", "Display",
1460
                              RadioSettingValueList(
1461
                                  AB_LIST, AB_LIST[_settings.displayab]))
1462
            workmode.append(rs)
1463

    
1464
            rs = RadioSetting("workmode", "VFO/MR Mode",
1465
                              RadioSettingValueList(
1466
                                  WORKMODE_LIST,
1467
                                  WORKMODE_LIST[_settings.workmode]))
1468
            workmode.append(rs)
1469

    
1470
            rs = RadioSetting("keylock", "Keypad Lock",
1471
                              RadioSettingValueBoolean(_settings.keylock))
1472
            workmode.append(rs)
1473

    
1474
            rs = RadioSetting("wmchannel.mrcha", "MR A Channel",
1475
                              RadioSettingValueInteger(0, 127,
1476
                                                       _wmchannel.mrcha))
1477
            workmode.append(rs)
1478

    
1479
            rs = RadioSetting("wmchannel.mrchb", "MR B Channel",
1480
                              RadioSettingValueInteger(0, 127,
1481
                                                       _wmchannel.mrchb))
1482
            workmode.append(rs)
1483

    
1484
            def convert_bytes_to_freq(bytes):
1485
                real_freq = 0
1486
                for byte in bytes:
1487
                    real_freq = (real_freq * 10) + byte
1488
                return chirp_common.format_freq(real_freq * 10)
1489

    
1490
            def my_validate(value):
1491
                value = chirp_common.parse_freq(value)
1492
                if 17400000 <= value and value < 40000000:
1493
                    msg = ("Can't be between 174.00000-400.00000")
1494
                    raise InvalidValueError(msg)
1495
                return chirp_common.format_freq(value)
1496

    
1497
            def apply_freq(setting, obj):
1498
                value = chirp_common.parse_freq(str(setting.value)) / 10
1499
                obj.band = value >= 40000000
1500
                for i in range(7, -1, -1):
1501
                    obj.freq[i] = value % 10
1502
                    value /= 10
1503

    
1504
            val1a = RadioSettingValueString(0, 10,
1505
                                            convert_bytes_to_freq(_vfoa.freq))
1506
            val1a.set_validate_callback(my_validate)
1507
            rs = RadioSetting("vfoa.freq", "VFO A Frequency", val1a)
1508
            rs.set_apply_callback(apply_freq, _vfoa)
1509
            workmode.append(rs)
1510

    
1511
            val1b = RadioSettingValueString(0, 10,
1512
                                            convert_bytes_to_freq(_vfob.freq))
1513
            val1b.set_validate_callback(my_validate)
1514
            rs = RadioSetting("vfob.freq", "VFO B Frequency", val1b)
1515
            rs.set_apply_callback(apply_freq, _vfob)
1516
            workmode.append(rs)
1517

    
1518
            rs = RadioSetting("vfoa.sftd", "VFO A Shift",
1519
                              RadioSettingValueList(
1520
                                  SHIFTD_LIST, SHIFTD_LIST[_vfoa.sftd]))
1521
            workmode.append(rs)
1522

    
1523
            rs = RadioSetting("vfob.sftd", "VFO B Shift",
1524
                              RadioSettingValueList(
1525
                                  SHIFTD_LIST, SHIFTD_LIST[_vfob.sftd]))
1526
            workmode.append(rs)
1527

    
1528
            def convert_bytes_to_offset(bytes):
1529
                real_offset = 0
1530
                for byte in bytes:
1531
                    real_offset = (real_offset * 10) + byte
1532
                return chirp_common.format_freq(real_offset * 1000)
1533

    
1534
            def apply_offset(setting, obj):
1535
                value = chirp_common.parse_freq(str(setting.value)) / 1000
1536
                for i in range(5, -1, -1):
1537
                    obj.offset[i] = value % 10
1538
                    value /= 10
1539

    
1540
            val1a = RadioSettingValueString(
1541
                0, 10, convert_bytes_to_offset(_vfoa.offset))
1542
            rs = RadioSetting("vfoa.offset",
1543
                              "VFO A Offset (0.0-999.999)", val1a)
1544
            rs.set_apply_callback(apply_offset, _vfoa)
1545
            workmode.append(rs)
1546

    
1547
            val1b = RadioSettingValueString(
1548
                0, 10, convert_bytes_to_offset(_vfob.offset))
1549
            rs = RadioSetting("vfob.offset",
1550
                              "VFO B Offset (0.0-999.999)", val1b)
1551
            rs.set_apply_callback(apply_offset, _vfob)
1552
            workmode.append(rs)
1553

    
1554
            if self._tri_power:
1555
                if _vfoa.txpower3 > 0x02:
1556
                    val = 0x00
1557
                else:
1558
                    val = _vfoa.txpower3
1559
                rs = RadioSetting("vfoa.txpower3", "VFO A Power",
1560
                                  RadioSettingValueList(
1561
                                      TXPOWER3_LIST,
1562
                                      TXPOWER3_LIST[val]))
1563
                workmode.append(rs)
1564

    
1565
                if _vfob.txpower3 > 0x02:
1566
                    val = 0x00
1567
                else:
1568
                    val = _vfob.txpower3
1569
                rs = RadioSetting("vfob.txpower3", "VFO B Power",
1570
                                  RadioSettingValueList(
1571
                                      TXPOWER3_LIST,
1572
                                      TXPOWER3_LIST[val]))
1573
                workmode.append(rs)
1574
            else:
1575
                rs = RadioSetting("vfoa.txpower", "VFO A Power",
1576
                                  RadioSettingValueList(
1577
                                      TXPOWER_LIST,
1578
                                      TXPOWER_LIST[_vfoa.txpower]))
1579
                workmode.append(rs)
1580

    
1581
                rs = RadioSetting("vfob.txpower", "VFO B Power",
1582
                                  RadioSettingValueList(
1583
                                      TXPOWER_LIST,
1584
                                      TXPOWER_LIST[_vfob.txpower]))
1585
                workmode.append(rs)
1586

    
1587
            rs = RadioSetting("vfoa.widenarr", "VFO A Bandwidth",
1588
                              RadioSettingValueList(
1589
                                  BANDWIDTH_LIST,
1590
                                  BANDWIDTH_LIST[_vfoa.widenarr]))
1591
            workmode.append(rs)
1592

    
1593
            rs = RadioSetting("vfob.widenarr", "VFO B Bandwidth",
1594
                              RadioSettingValueList(
1595
                                  BANDWIDTH_LIST,
1596
                                  BANDWIDTH_LIST[_vfob.widenarr]))
1597
            workmode.append(rs)
1598

    
1599
            rs = RadioSetting("vfoa.scode", "VFO A PTT-ID",
1600
                              RadioSettingValueList(
1601
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfoa.scode]))
1602
            workmode.append(rs)
1603

    
1604
            rs = RadioSetting("vfob.scode", "VFO B PTT-ID",
1605
                              RadioSettingValueList(
1606
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfob.scode]))
1607
            workmode.append(rs)
1608

    
1609
            if not self._is_orig():
1610
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1611
                                  RadioSettingValueList(
1612
                                      STEP291_LIST, STEP291_LIST[_vfoa.step]))
1613
                workmode.append(rs)
1614
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1615
                                  RadioSettingValueList(
1616
                                      STEP291_LIST, STEP291_LIST[_vfob.step]))
1617
                workmode.append(rs)
1618
            else:
1619
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1620
                                  RadioSettingValueList(
1621
                                      STEP_LIST, STEP_LIST[_vfoa.step]))
1622
                workmode.append(rs)
1623
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1624
                                  RadioSettingValueList(
1625
                                      STEP_LIST, STEP_LIST[_vfob.step]))
1626
                workmode.append(rs)
1627

    
1628
        fm_preset = RadioSettingGroup("fm_preset", "FM Radio Preset")
1629
        group.append(fm_preset)
1630

    
1631
        if _fm_presets <= 108.0 * 10 - 650:
1632
            preset = _fm_presets / 10.0 + 65
1633
        elif _fm_presets >= 65.0 * 10 and _fm_presets <= 108.0 * 10:
1634
            preset = _fm_presets / 10.0
1635
        else:
1636
            preset = 76.0
1637
        rs = RadioSetting("fm_presets", "FM Preset(MHz)",
1638
                          RadioSettingValueFloat(65, 108.0, preset, 0.1, 1))
1639
        fm_preset.append(rs)
1640

    
1641
        dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
1642
        group.append(dtmf)
1643

    
1644
        if str(self._memobj.firmware_msg.line1) == "HN5RV01":
1645
            dtmfchars = "0123456789ABCD*#"
1646
        else:
1647
            dtmfchars = "0123456789 *#ABCD"
1648

    
1649
        for i in range(0, 15):
1650
            _codeobj = self._memobj.pttid[i].code
1651
            _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1652
            val = RadioSettingValueString(0, 5, _code, False)
1653
            val.set_charset(dtmfchars)
1654
            rs = RadioSetting("pttid/%i.code" % i,
1655
                              "PTT ID Code %i" % (i + 1), val)
1656

    
1657
            def apply_code(setting, obj):
1658
                code = []
1659
                for j in range(0, 5):
1660
                    try:
1661
                        code.append(dtmfchars.index(str(setting.value)[j]))
1662
                    except IndexError:
1663
                        code.append(0xFF)
1664
                obj.code = code
1665
            rs.set_apply_callback(apply_code, self._memobj.pttid[i])
1666
            dtmf.append(rs)
1667

    
1668
        dtmfcharsani = "0123456789"
1669

    
1670
        _codeobj = self._memobj.ani.code
1671
        _code = "".join([dtmfcharsani[x] for x in _codeobj if int(x) < 0x1F])
1672
        val = RadioSettingValueString(0, 5, _code, False)
1673
        val.set_charset(dtmfcharsani)
1674
        rs = RadioSetting("ani.code", "ANI Code", val)
1675

    
1676
        def apply_code(setting, obj):
1677
            code = []
1678
            for j in range(0, 5):
1679
                try:
1680
                    code.append(dtmfchars.index(str(setting.value)[j]))
1681
                except IndexError:
1682
                    code.append(0xFF)
1683
            obj.code = code
1684
        rs.set_apply_callback(apply_code, _ani)
1685
        dtmf.append(rs)
1686

    
1687
        rs = RadioSetting("ani.aniid", "ANI ID",
1688
                          RadioSettingValueList(PTTID_LIST,
1689
                                                PTTID_LIST[_ani.aniid]))
1690
        dtmf.append(rs)
1691

    
1692
        _codeobj = self._memobj.ani.alarmcode
1693
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1694
        val = RadioSettingValueString(0, 3, _code, False)
1695
        val.set_charset(dtmfchars)
1696
        rs = RadioSetting("ani.alarmcode", "Alarm Code", val)
1697

    
1698
        def apply_code(setting, obj):
1699
            alarmcode = []
1700
            for j in range(0, 3):
1701
                try:
1702
                    alarmcode.append(dtmfchars.index(str(setting.value)[j]))
1703
                except IndexError:
1704
                    alarmcode.append(0xFF)
1705
            obj.alarmcode = alarmcode
1706
        rs.set_apply_callback(apply_code, _ani)
1707
        dtmf.append(rs)
1708

    
1709
        rs = RadioSetting("dtmfst", "DTMF Sidetone",
1710
                          RadioSettingValueList(DTMFST_LIST,
1711
                                                DTMFST_LIST[_settings.dtmfst]))
1712
        dtmf.append(rs)
1713

    
1714
        if _ani.dtmfon > 0xC3:
1715
            val = 0x00
1716
        else:
1717
            val = _ani.dtmfon
1718
        rs = RadioSetting("ani.dtmfon", "DTMF Speed (on)",
1719
                          RadioSettingValueList(DTMFSPEED_LIST,
1720
                                                DTMFSPEED_LIST[val]))
1721
        dtmf.append(rs)
1722

    
1723
        if _ani.dtmfoff > 0xC3:
1724
            val = 0x00
1725
        else:
1726
            val = _ani.dtmfoff
1727
        rs = RadioSetting("ani.dtmfoff", "DTMF Speed (off)",
1728
                          RadioSettingValueList(DTMFSPEED_LIST,
1729
                                                DTMFSPEED_LIST[val]))
1730
        dtmf.append(rs)
1731

    
1732
        rs = RadioSetting("pttlt", "PTT ID Delay",
1733
                          RadioSettingValueInteger(0, 50, _settings.pttlt))
1734
        dtmf.append(rs)
1735

    
1736
        if not self._is_orig() and self._aux_block:
1737
            service = RadioSettingGroup("service", "Service Settings")
1738
            group.append(service)
1739

    
1740
            for band in ["vhf", "uhf"]:
1741
                for index in range(0, 10):
1742
                    key = "squelch_new.%s.sql%i" % (band, index)
1743
                    if band == "vhf":
1744
                        _obj = self._memobj.squelch_new.vhf
1745
                    elif band == "uhf":
1746
                        _obj = self._memobj.squelch_new.uhf
1747
                    name = "%s Squelch %i" % (band.upper(), index)
1748
                    rs = RadioSetting(key, name,
1749
                                      RadioSettingValueInteger(
1750
                                          0, 123,
1751
                                          getattr(_obj, "sql%i" % (index))))
1752
                    service.append(rs)
1753

    
1754
        return group
1755

    
1756
    def get_settings(self):
1757
        try:
1758
            return self._get_settings()
1759
        except:
1760
            import traceback
1761
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1762
            return None
1763

    
1764
    def set_settings(self, settings):
1765
        _settings = self._memobj.settings
1766
        for element in settings:
1767
            if not isinstance(element, RadioSetting):
1768
                if element.get_name() == "fm_preset":
1769
                    self._set_fm_preset(element)
1770
                else:
1771
                    self.set_settings(element)
1772
                    continue
1773
            else:
1774
                try:
1775
                    name = element.get_name()
1776
                    if "." in name:
1777
                        bits = name.split(".")
1778
                        obj = self._memobj
1779
                        for bit in bits[:-1]:
1780
                            if "/" in bit:
1781
                                bit, index = bit.split("/", 1)
1782
                                index = int(index)
1783
                                obj = getattr(obj, bit)[index]
1784
                            else:
1785
                                obj = getattr(obj, bit)
1786
                        setting = bits[-1]
1787
                    else:
1788
                        obj = _settings
1789
                        setting = element.get_name()
1790

    
1791
                    if element.has_apply_callback():
1792
                        LOG.debug("Using apply callback")
1793
                        element.run_apply_callback()
1794
                    elif element.value.get_mutable():
1795
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1796
                        setattr(obj, setting, element.value)
1797
                except Exception, e:
1798
                    LOG.debug(element.get_name())
1799
                    raise
1800

    
1801
    def _set_fm_preset(self, settings):
1802
        for element in settings:
1803
            try:
1804
                val = element.value
1805
                if self._memobj.fm_presets <= 108.0 * 10 - 650:
1806
                    value = int(val.get_value() * 10 - 650)
1807
                else:
1808
                    value = int(val.get_value() * 10)
1809
                LOG.debug("Setting fm_presets = %s" % (value))
1810
                self._memobj.fm_presets = value
1811
            except Exception, e:
1812
                LOG.debug(element.get_name())
1813
                raise
1814

    
1815

    
1816
class UV5XAlias(chirp_common.Alias):
1817
    VENDOR = "Baofeng"
1818
    MODEL = "UV-5X"
1819

    
1820

    
1821
class RT5RAlias(chirp_common.Alias):
1822
    VENDOR = "Retevis"
1823
    MODEL = "RT5R"
1824

    
1825

    
1826
class RT5RVAlias(chirp_common.Alias):
1827
    VENDOR = "Retevis"
1828
    MODEL = "RT5RV"
1829

    
1830

    
1831
class RT5Alias(chirp_common.Alias):
1832
    VENDOR = "Retevis"
1833
    MODEL = "RT5"
1834

    
1835

    
1836
class RT5_TPAlias(chirp_common.Alias):
1837
    VENDOR = "Retevis"
1838
    MODEL = "RT5(tri-power)"
1839

    
1840

    
1841
class RH5RAlias(chirp_common.Alias):
1842
    VENDOR = "Rugged"
1843
    MODEL = "RH5R"
1844

    
1845

    
1846
class ROUV5REXAlias(chirp_common.Alias):
1847
    VENDOR = "Radioddity"
1848
    MODEL = "UV-5R EX"
1849

    
1850

    
1851
class A5RAlias(chirp_common.Alias):
1852
    VENDOR = "Ansoko"
1853
    MODEL = "A-5R"
1854

    
1855

    
1856
@directory.register
1857
class BaofengUV5RGeneric(BaofengUV5R):
1858
    ALIASES = [UV5XAlias, RT5RAlias, RT5RVAlias, RT5Alias, RH5RAlias,
1859
               ROUV5REXAlias, A5RAlias]
1860

    
1861

    
1862
@directory.register
1863
class BaofengF11Radio(BaofengUV5R):
1864
    VENDOR = "Baofeng"
1865
    MODEL = "F-11"
1866
    _basetype = BASETYPE_F11
1867
    _idents = [UV5R_MODEL_F11]
1868

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

    
1873

    
1874
@directory.register
1875
class BaofengUV82Radio(BaofengUV5R):
1876
    MODEL = "UV-82"
1877
    _basetype = BASETYPE_UV82
1878
    _idents = [UV5R_MODEL_UV82]
1879
    _vhf_range = (130000000, 176000000)
1880
    _uhf_range = (400000000, 521000000)
1881
    _valid_chars = chirp_common.CHARSET_ASCII
1882

    
1883
    def _is_orig(self):
1884
        # Override this for UV82 to always return False
1885
        return False
1886

    
1887

    
1888
@directory.register
1889
class Radioddity82X3Radio(BaofengUV82Radio):
1890
    VENDOR = "Radioddity"
1891
    MODEL = "UV-82X3"
1892
    _basetype = BASETYPE_UV82X3
1893

    
1894
    def get_features(self):
1895
        rf = BaofengUV5R.get_features(self)
1896
        rf.valid_bands = [self._vhf_range,
1897
                          (200000000, 260000000),
1898
                          self._uhf_range]
1899
        return rf
1900

    
1901

    
1902
@directory.register
1903
class BaofengUV6Radio(BaofengUV5R):
1904

    
1905
    """Baofeng UV-6/UV-7"""
1906
    VENDOR = "Baofeng"
1907
    MODEL = "UV-6"
1908
    _basetype = BASETYPE_UV6
1909
    _idents = [UV5R_MODEL_UV6,
1910
               UV5R_MODEL_UV6_ORIG
1911
               ]
1912
    _aux_block = False
1913

    
1914
    def get_features(self):
1915
        rf = BaofengUV5R.get_features(self)
1916
        rf.memory_bounds = (1, 128)
1917
        return rf
1918

    
1919
    def _get_mem(self, number):
1920
        return self._memobj.memory[number - 1]
1921

    
1922
    def _get_nam(self, number):
1923
        return self._memobj.names[number - 1]
1924

    
1925
    def _set_mem(self, number):
1926
        return self._memobj.memory[number - 1]
1927

    
1928
    def _set_nam(self, number):
1929
        return self._memobj.names[number - 1]
1930

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

    
1935

    
1936
@directory.register
1937
class IntekKT980Radio(BaofengUV5R):
1938
    VENDOR = "Intek"
1939
    MODEL = "KT-980HP"
1940
    _basetype = BASETYPE_KT980HP
1941
    _idents = [UV5R_MODEL_291]
1942
    _vhf_range = (130000000, 180000000)
1943
    _uhf_range = (400000000, 521000000)
1944
    _tri_power = True
1945

    
1946
    def get_features(self):
1947
        rf = BaofengUV5R.get_features(self)
1948
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1949
        return rf
1950

    
1951
    def _is_orig(self):
1952
        # Override this for KT980HP to always return False
1953
        return False
1954

    
1955

    
1956
class ROGA5SAlias(chirp_common.Alias):
1957
    VENDOR = "Radioddity"
1958
    MODEL = "GA-5S"
1959

    
1960

    
1961
class UV5XPAlias(chirp_common.Alias):
1962
    VENDOR = "Baofeng"
1963
    MODEL = "UV-5XP"
1964

    
1965

    
1966
class TSTIF8Alias(chirp_common.Alias):
1967
    VENDOR = "TechSide"
1968
    MODEL = "TI-F8+"
1969

    
1970

    
1971
class TenwayUV5RPro(chirp_common.Alias):
1972
    VENDOR = 'Tenway'
1973
    MODEL = 'UV-5R Pro'
1974

    
1975

    
1976
class TSTST9Alias(chirp_common.Alias):
1977
    VENDOR = "TechSide"
1978
    MODEL = "TS-T9+"
1979

    
1980

    
1981
class TDUV5RRadio(chirp_common.Alias):
1982
    VENDOR = "TIDRADIO"
1983
    MODEL = "TD-UV5R TriPower"
1984

    
1985

    
1986
@directory.register
1987
class BaofengBFF8HPRadio(BaofengUV5R):
1988
    VENDOR = "Baofeng"
1989
    MODEL = "BF-F8HP"
1990
    ALIASES = [RT5_TPAlias, ROGA5SAlias, UV5XPAlias, TSTIF8Alias,
1991
               TenwayUV5RPro, TSTST9Alias, TDUV5RRadio]
1992
    _basetype = BASETYPE_F8HP
1993
    _idents = [UV5R_MODEL_291,
1994
               UV5R_MODEL_A58
1995
               ]
1996
    _vhf_range = (130000000, 180000000)
1997
    _uhf_range = (400000000, 521000000)
1998
    _tri_power = True
1999

    
2000
    def get_features(self):
2001
        rf = BaofengUV5R.get_features(self)
2002
        rf.valid_power_levels = UV5R_POWER_LEVELS3
2003
        return rf
2004

    
2005
    def _is_orig(self):
2006
        # Override this for BFF8HP to always return False
2007
        return False
2008

    
2009

    
2010
class TenwayUV82Pro(chirp_common.Alias):
2011
    VENDOR = 'Tenway'
2012
    MODEL = 'UV-82 Pro'
2013

    
2014

    
2015
@directory.register
2016
class BaofengUV82HPRadio(BaofengUV5R):
2017
    VENDOR = "Baofeng"
2018
    MODEL = "UV-82HP"
2019
    ALIASES = [TenwayUV82Pro]
2020
    _basetype = BASETYPE_UV82HP
2021
    _idents = [UV5R_MODEL_UV82]
2022
    _vhf_range = (136000000, 175000000)
2023
    _uhf_range = (400000000, 521000000)
2024
    _valid_chars = chirp_common.CHARSET_ALPHANUMERIC + \
2025
        "!@#$%^&*()+-=[]:\";'<>?,./"
2026
    _tri_power = True
2027

    
2028
    def get_features(self):
2029
        rf = BaofengUV5R.get_features(self)
2030
        rf.valid_power_levels = UV5R_POWER_LEVELS3
2031
        return rf
2032

    
2033
    def _is_orig(self):
2034
        # Override this for UV82HP to always return False
2035
        return False
2036

    
2037

    
2038
@directory.register
2039
class RadioddityUV5RX3Radio(BaofengUV5R):
2040
    VENDOR = "Radioddity"
2041
    MODEL = "UV-5RX3"
2042

    
2043
    def get_features(self):
2044
        rf = BaofengUV5R.get_features(self)
2045
        rf.valid_bands = [self._vhf_range,
2046
                          (200000000, 260000000),
2047
                          self._uhf_range]
2048
        return rf
2049

    
2050
    @classmethod
2051
    def match_model(cls, filename, filedata):
2052
        return False
2053

    
2054

    
2055
@directory.register
2056
class RadioddityGT5RRadio(BaofengUV5R):
2057
    VENDOR = 'Baofeng'
2058
    MODEL = 'GT-5R'
2059

    
2060
    vhftx = [144000000, 148000000]
2061
    uhftx = [420000000, 450000000]
2062

    
2063
    def set_memory(self, mem):
2064
        # If memory is outside the TX limits, the radio will refuse
2065
        # transmit. Radioddity asked for us to enforce this behavior
2066
        # in chirp for consistency.
2067
        if not (mem.freq >= self.vhftx[0] and mem.freq < self.vhftx[1]) and \
2068
           not (mem.freq >= self.uhftx[0] and mem.freq < self.uhftx[1]):
2069
            LOG.info('Memory frequency outside TX limits of radio; '
2070
                     'forcing duplex=off')
2071
            mem.duplex = 'off'
2072
            mem.offset = 0
2073
        BaofengUV5R.set_memory(self, mem)
2074

    
2075
    @classmethod
2076
    def match_model(cls, filename, filedata):
2077
        return False
2078

    
2079

    
2080
@directory.register
2081
class RadioddityUV5GRadio(BaofengUV5R):
2082
    VENDOR = 'Radioddity'
2083
    MODEL = 'UV-5G'
2084

    
2085
    _basetype = BASETYPE_UV5R
2086
    _idents = [UV5R_MODEL_UV5G]
2087
    _gmrs = True
2088

    
2089
    @classmethod
2090
    def match_model(cls, filename, filedata):
2091
        return False
    (1-1/1)