Project

General

Profile

Bug #10214 » uv5r_legacy_for_april.py

Jim Unroe, 01/04/2023 10:32 PM

 
1
# Copyright 2012 Dan Smith <dsmith@danplanet.com>
2
#
3
# This program is free software: you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation, either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
15

    
16
import struct
17
import time
18
import os
19
import logging
20

    
21
from chirp import chirp_common, errors, util, directory, memmap
22
from chirp import bitwise
23
from chirp.settings import RadioSetting, RadioSettingGroup, \
24
    RadioSettingValueInteger, RadioSettingValueList, \
25
    RadioSettingValueBoolean, RadioSettingValueString, \
26
    RadioSettingValueFloat, InvalidValueError, RadioSettings
27
from textwrap import dedent
28

    
29
LOG = logging.getLogger(__name__)
30

    
31
MEM_FORMAT = """
32
#seekto 0x0008;
33
struct {
34
  lbcd rxfreq[4];
35
  lbcd txfreq[4];
36
  ul16 rxtone;
37
  ul16 txtone;
38
  u8 unused1:3,
39
     isuhf:1,
40
     scode:4;
41
  u8 unknown1:7,
42
     txtoneicon:1;
43
  u8 mailicon:3,
44
     unknown2:3,
45
     lowpower:2;
46
  u8 unknown3:1,
47
     wide:1,
48
     unknown4:2,
49
     bcl:1,
50
     scan:1,
51
     pttid:2;
52
} memory[128];
53

    
54
#seekto 0x0B08;
55
struct {
56
  u8 code[5];
57
  u8 unused[11];
58
} pttid[15];
59

    
60
#seekto 0x0C88;
61
struct {
62
  u8 code222[3];
63
  u8 unused222[2];
64
  u8 code333[3];
65
  u8 unused333[2];
66
  u8 alarmcode[3];
67
  u8 unused119[2];
68
  u8 unknown1;
69
  u8 code555[3];
70
  u8 unused555[2];
71
  u8 code666[3];
72
  u8 unused666[2];
73
  u8 code777[3];
74
  u8 unused777[2];
75
  u8 unknown2;
76
  u8 code60606[5];
77
  u8 code70707[5];
78
  u8 code[5];
79
  u8 unused1:6,
80
     aniid:2;
81
  u8 unknown[2];
82
  u8 dtmfon;
83
  u8 dtmfoff;
84
} ani;
85

    
86
#seekto 0x0E28;
87
struct {
88
  u8 squelch;
89
  u8 step;
90
  u8 unknown1;
91
  u8 save;
92
  u8 vox;
93
  u8 unknown2;
94
  u8 abr;
95
  u8 tdr;
96
  u8 beep;
97
  u8 timeout;
98
  u8 unknown3[4];
99
  u8 voice;
100
  u8 unknown4;
101
  u8 dtmfst;
102
  u8 unknown5;
103
  u8 unknown12:6,
104
     screv:2;
105
  u8 pttid;
106
  u8 pttlt;
107
  u8 mdfa;
108
  u8 mdfb;
109
  u8 bcl;
110
  u8 autolk; // NOTE: The UV-6 calls this byte voxenable, but the UV-5R
111
             // calls it autolk. Since this is a minor difference, it will
112
             // be referred to by the wrong name for the UV-6.
113
  u8 sftd;
114
  u8 unknown6[3];
115
  u8 wtled;
116
  u8 rxled;
117
  u8 txled;
118
  u8 almod;
119
  u8 band;
120
  u8 tdrab;
121
  u8 ste;
122
  u8 rpste;
123
  u8 rptrl;
124
  u8 ponmsg;
125
  u8 roger;
126
  u8 rogerrx;
127
  u8 tdrch; // NOTE: The UV-82HP calls this byte rtone, but the UV-6
128
            // calls it tdrch. Since this is a minor difference, it will
129
            // be referred to by the wrong name for the UV-82HP.
130
  u8 displayab:1,
131
     unknown1:2,
132
     fmradio:1,
133
     alarm:1,
134
     unknown2:1,
135
     reset:1,
136
     menu:1;
137
  u8 unknown1:6,
138
     singleptt:1,
139
     vfomrlock:1;
140
  u8 workmode;
141
  u8 keylock;
142
} settings;
143

    
144
#seekto 0x0E7E;
145
struct {
146
  u8 unused1:1,
147
     mrcha:7;
148
  u8 unused2:1,
149
     mrchb:7;
150
} wmchannel;
151

    
152
#seekto 0x0F10;
153
struct {
154
  u8 freq[8];
155
  u8 offset[6];
156
  ul16 rxtone;
157
  ul16 txtone;
158
  u8 unused1:7,
159
     band:1;
160
  u8 unknown3;
161
  u8 unused2:2,
162
     sftd:2,
163
     scode:4;
164
  u8 unknown4;
165
  u8 unused3:1
166
     step:3,
167
     unused4:4;
168
  u8 txpower:1,
169
     widenarr:1,
170
     unknown5:4,
171
     txpower3:2;
172
} vfoa;
173

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

    
196
#seekto 0x0F56;
197
u16 fm_presets;
198

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

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

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

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

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

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

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

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

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

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

    
273
"""
274

    
275
# 0x1EC0 - 0x2000
276

    
277
vhf_220_radio = "\x02"
278

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

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

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

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

    
366

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

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

    
383

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

    
387

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

    
391

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

    
396

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

    
404

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

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

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

    
420
    serial.write("\x02")
421

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

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

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

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

    
464
    return ident
465

    
466

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

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

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

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

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

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

    
497
    return chunk
498

    
499

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

    
511

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

    
517

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

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

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

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

    
548

    
549
def _do_download(radio):
550
    raise errors.RadioError("Downloading is disabled.")
551
    data = _ident_radio(radio)
552

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

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

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

    
600
    if append_model:
601
        data += radio.MODEL.ljust(8)
602

    
603
    LOG.debug("done.")
604
    return memmap.MemoryMap(data)
605

    
606

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

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

    
616

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

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

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

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

    
641
    # extra aux ranges
642
    _ranges_aux_extra = [
643
        (0x1F60, 0x1F70),
644
        (0x1F80, 0x1F90),
645
        (0x1FC0, 0x1FE0)
646
        ]
647

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

    
662
    if not radio._aux_block:
663
        image_matched_radio = True
664

    
665
    ranges_main = radio._ranges_main  #  Only to be used to fix April's radio
666
    ranges_aux = radio._ranges_aux    #
667

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

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

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

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

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

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

    
699
UV5R_DTCS = sorted(chirp_common.DTCS_CODES + [645])
700

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

    
704

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

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

    
718

    
719
class BaofengUV5R(chirp_common.CloneModeRadio):
720

    
721
    """Baofeng UV-5R"""
722
    VENDOR = "Baofeng"
723
    MODEL = "UV-5R"
724
    BAUD_RATE = 9600
725

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

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

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

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

    
797
        normal_bands = [self._vhf_range, self._uhf_range]
798
        rax_bands = [self._vhf_range, self._220_range]
799

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

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

    
817
        if match_size and match_model:
818
            return True
819
        else:
820
            return False
821

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

    
825
    def validate_memory(self, mem):
826
        msgs = chirp_common.CloneModeRadio.validate_memory(self, mem)
827

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

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

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

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

    
848
        return msgs
849

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

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

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

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

    
876
    def _get_mem(self, number):
877
        return self._memobj.memory[number]
878

    
879
    def _get_nam(self, number):
880
        return self._memobj.names[number]
881

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

    
886
        mem = chirp_common.Memory()
887
        mem.number = number
888

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

    
893
        mem.freq = int(_mem.rxfreq) * 10
894

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

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

    
914
        dtcs_pol = ["N", "N"]
915

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

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

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

    
958
        mem.dtcs_polarity = "".join(dtcs_pol)
959

    
960
        if not _mem.scan:
961
            mem.skip = "S"
962

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

    
974
        mem.mode = _mem.wide and "FM" or "NFM"
975

    
976
        mem.extra = RadioSettingGroup("Extra", "extra")
977

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

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

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

    
992
        return mem
993

    
994
    def _set_mem(self, number):
995
        return self._memobj.memory[number]
996

    
997
    def _set_nam(self, number):
998
        return self._memobj.names[number]
999

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

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

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

    
1023
        _mem.set_raw("\x00" * 16)
1024

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

    
1052
        _mem.rxfreq = mem.freq / 10
1053

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

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

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

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

    
1107
        _mem.scan = mem.skip != "S"
1108
        _mem.wide = mem.mode == "FM"
1109

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

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

    
1125
        for setting in mem.extra:
1126
            setattr(_mem, setting.get_name(), setting.value)
1127

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

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

    
1148
        raise Exception("Unrecognized firmware version string")
1149

    
1150
    def _my_upper_band(self):
1151
        band_tag = _upper_band_from_image(self)
1152
        return band_tag
1153

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

    
1165
        group = RadioSettings(basic, advanced)
1166

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1626
        fm_preset = RadioSettingGroup("fm_preset", "FM Radio Preset")
1627
        group.append(fm_preset)
1628

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

    
1639
        dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
1640
        group.append(dtmf)
1641

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

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

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

    
1666
        dtmfcharsani = "0123456789"
1667

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

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

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

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

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

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

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

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

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

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

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

    
1752
        return group
1753

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

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

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

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

    
1813

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

    
1818

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

    
1823

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

    
1828

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

    
1833

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

    
1838

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

    
1843

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

    
1848

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

    
1853

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

    
1859

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

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

    
1871

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

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

    
1885

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

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

    
1899

    
1900
@directory.register
1901
class BaofengUV6Radio(BaofengUV5R):
1902

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

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

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

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

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

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

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

    
1933

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

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

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

    
1953

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

    
1958

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

    
1963

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

    
1968

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

    
1973

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

    
1978

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

    
1983

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

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

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

    
2007

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

    
2012

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

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

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

    
2035

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

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

    
2048
    @classmethod
2049
    def match_model(cls, filename, filedata):
2050
        return False
2051

    
2052

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

    
2058
    vhftx = [144000000, 148000000]
2059
    uhftx = [420000000, 450000000]
2060

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

    
2073
    @classmethod
2074
    def match_model(cls, filename, filedata):
2075
        return False
2076

    
2077

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

    
2083
    _basetype = BASETYPE_UV5R
2084
    _idents = [UV5R_MODEL_UV5G]
2085
    _gmrs = True
2086

    
2087
    @classmethod
2088
    def match_model(cls, filename, filedata):
2089
        return False
(6-6/6)