uv5r.py

UV-5R driver with corrected variable assignment - Jim Unroe, 09/23/2016 02:47 pm

Download (56.9 kB)

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

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

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

    
29
LOG = logging.getLogger(__name__)
30

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

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

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

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

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

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

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

    
200
#seekto 0x0F56;
201
u16 fm_presets;
202

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

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

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

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

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

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

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

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

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

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

    
277
"""
278

    
279
# 0x1EC0 - 0x2000
280

    
281
vhf_220_radio = "\x02"
282

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

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

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

    
360

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

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

    
376

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

    
380

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

    
384

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

    
389

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

    
397

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

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

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

    
413
    serial.write("\x02")
414

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

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

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

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

    
456
    return ident
457

    
458

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

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

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

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

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

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

    
489
    return chunk
490

    
491

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

    
503

    
504
def _ident_radio(radio):
505
    for magic in radio._idents:
506
        error = None
507
        try:
508
            data = _do_ident(radio, magic)
509
            return data
510
        except errors.RadioError, e:
511
            LOG.error(e)
512
            error = e
513
            time.sleep(2)
514
    if error:
515
        raise error
516
    raise errors.RadioError("Radio did not respond")
517

    
518

    
519
def _do_download(radio):
520
    data = _ident_radio(radio)
521

    
522
    radio_version = _get_radio_firmware_version(radio)
523
    LOG.info("Radio Version is %s" % repr(radio_version))
524

    
525
    if not any(type in radio_version for type in radio._basetype):
526
        raise errors.RadioError("Incorrect 'Model' selected.")
527

    
528
    # Main block
529
    LOG.debug("downloading main block...")
530
    for i in range(0, 0x1800, 0x40):
531
        data += _read_block(radio, i, 0x40, False)
532
        _do_status(radio, i)
533
    _do_status(radio, radio.get_memsize())
534
    LOG.debug("done.")
535
    LOG.debug("downloading aux block...")
536
    # Auxiliary block starts at 0x1ECO (?)
537
    for i in range(0x1EC0, 0x2000, 0x40):
538
        data += _read_block(radio, i, 0x40, False)
539
    LOG.debug("done.")
540
    return memmap.MemoryMap(data)
541

    
542

    
543
def _send_block(radio, addr, data):
544
    msg = struct.pack(">BHB", ord("X"), addr, len(data))
545
    radio.pipe.write(msg + data)
546
    time.sleep(0.05)
547

    
548
    ack = radio.pipe.read(1)
549
    if ack != "\x06":
550
        raise errors.RadioError("Radio refused to accept block 0x%04x" % addr)
551

    
552

    
553
def _do_upload(radio):
554
    ident = _ident_radio(radio)
555
    radio_upper_band = ident[3:4]
556
    image_upper_band = _upper_band_from_image(radio)
557

    
558
    if image_upper_band == vhf_220_radio or radio_upper_band == vhf_220_radio:
559
        if image_upper_band != radio_upper_band:
560
            raise errors.RadioError("Image not supported by radio")
561

    
562
    image_version = _firmware_version_from_image(radio)
563
    radio_version = _get_radio_firmware_version(radio)
564
    LOG.info("Image Version is %s" % repr(image_version))
565
    LOG.info("Radio Version is %s" % repr(radio_version))
566

    
567
    if image_version != radio_version:
568
        msg = ("The upload was stopped because the firmware "
569
               "version of the image (%s) does not match that "
570
               "of the radio (%s).")
571
        raise errors.RadioError(msg % (image_version, radio_version))
572

    
573
    # Main block
574
    for i in range(0x08, 0x1808, 0x10):
575
        _send_block(radio, i - 0x08, radio.get_mmap()[i:i + 0x10])
576
        _do_status(radio, i)
577
    _do_status(radio, radio.get_memsize())
578

    
579
    if len(radio.get_mmap().get_packed()) == 0x1808:
580
        LOG.info("Old image, not writing aux block")
581
        return  # Old image, no aux block
582

    
583
    if image_version != radio_version:
584
        msg = ("Upload finished, but the 'Other Settings' "
585
               "could not be sent because the firmware "
586
               "version of the image (%s) does not match "
587
               "that of the radio (%s).")
588
        raise errors.RadioError(msg % (image_version, radio_version))
589

    
590
    # Auxiliary block at radio address 0x1EC0, our offset 0x1808
591
    for i in range(0x1EC0, 0x2000, 0x10):
592
        addr = 0x1808 + (i - 0x1EC0)
593
        _send_block(radio, i, radio.get_mmap()[addr:addr + 0x10])
594

    
595
UV5R_POWER_LEVELS = [chirp_common.PowerLevel("High", watts=4.00),
596
                     chirp_common.PowerLevel("Low",  watts=1.00)]
597

    
598
UV5R_POWER_LEVELS3 = [chirp_common.PowerLevel("High", watts=8.00),
599
                      chirp_common.PowerLevel("Med",  watts=4.00),
600
                      chirp_common.PowerLevel("Low",  watts=1.00)]
601

    
602
UV5R_DTCS = sorted(chirp_common.DTCS_CODES + [645])
603

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

    
607

    
608
class BaofengUV5R(chirp_common.CloneModeRadio,
609
                  chirp_common.ExperimentalRadio):
610
    """Baofeng UV-5R"""
611
    VENDOR = "Baofeng"
612
    MODEL = "UV-5R"
613
    BAUD_RATE = 9600
614

    
615
    _memsize = 0x1808
616
    _basetype = BASETYPE_UV5R
617
    _idents = [UV5R_MODEL_291,
618
               UV5R_MODEL_ORIG
619
               ]
620
    _vhf_range = (136000000, 174000000)
621
    _220_range = (220000000, 260000000)
622
    _uhf_range = (400000000, 520000000)
623
    _mem_params = (0x1828  # poweron_msg offset
624
                   )
625
    # offset of fw version in image file
626
    _fw_ver_file_start = 0x1838
627
    _fw_ver_file_stop = 0x1846
628

    
629
    @classmethod
630
    def get_prompts(cls):
631
        rp = chirp_common.RadioPrompts()
632
        rp.experimental = \
633
            ('Due to the fact that the manufacturer continues to '
634
             'release new versions of the firmware with obscure and '
635
             'hard-to-track changes, this driver may not work with '
636
             'your device. Thus far and to the best knowledge of the '
637
             'author, no UV-5R radios have been harmed by using CHIRP. '
638
             'However, proceed at your own risk!')
639
        rp.pre_download = _(dedent("""\
640
            1. Turn radio off.
641
            2. Connect cable to mic/spkr connector.
642
            3. Make sure connector is firmly connected.
643
            4. Turn radio on (volume may need to be set at 100%).
644
            5. Ensure that the radio is tuned to channel with no activity.
645
            6. Click OK to download image from device."""))
646
        rp.pre_upload = _(dedent("""\
647
            1. Turn radio off.
648
            2. Connect cable to mic/spkr connector.
649
            3. Make sure connector is firmly connected.
650
            4. Turn radio on (volume may need to be set at 100%).
651
            5. Ensure that the radio is tuned to channel with no activity.
652
            6. Click OK to upload image to device."""))
653
        return rp
654

    
655
    def get_features(self):
656
        rf = chirp_common.RadioFeatures()
657
        rf.has_settings = True
658
        rf.has_bank = False
659
        rf.has_cross = True
660
        rf.has_rx_dtcs = True
661
        rf.has_tuning_step = False
662
        rf.can_odd_split = True
663
        rf.valid_name_length = 7
664
        rf.valid_characters = UV5R_CHARSET
665
        rf.valid_skips = ["", "S"]
666
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
667
        rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone",
668
                                "->Tone", "->DTCS", "DTCS->", "DTCS->DTCS"]
669
        rf.valid_power_levels = UV5R_POWER_LEVELS
670
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
671
        rf.valid_modes = ["FM", "NFM"]
672

    
673
        normal_bands = [self._vhf_range, self._uhf_range]
674
        rax_bands = [self._vhf_range, self._220_range]
675

    
676
        if self._mmap is None:
677
            rf.valid_bands = [normal_bands[0], rax_bands[1], normal_bands[1]]
678
        elif not self._is_orig() and self._my_upper_band() == vhf_220_radio:
679
            rf.valid_bands = rax_bands
680
        else:
681
            rf.valid_bands = normal_bands
682
        rf.memory_bounds = (0, 127)
683
        return rf
684

    
685
    @classmethod
686
    def match_model(cls, filedata, filename):
687
        match_size = False
688
        match_model = False
689
        if len(filedata) in [0x1808, 0x1948]:
690
            match_size = True
691
        fwdata = _firmware_version_from_data(filedata,
692
                                             cls._fw_ver_file_start,
693
                                             cls._fw_ver_file_stop)
694
        if any(type in fwdata for type in cls._basetype):
695
            match_model = True
696
        if match_size and match_model:
697
            return True
698
        else:
699
            return False
700

    
701
    def process_mmap(self):
702
        self._memobj = bitwise.parse(MEM_FORMAT % self._mem_params, self._mmap)
703

    
704
    def sync_in(self):
705
        try:
706
            self._mmap = _do_download(self)
707
        except errors.RadioError:
708
            raise
709
        except Exception, e:
710
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
711
        self.process_mmap()
712

    
713
    def sync_out(self):
714
        try:
715
            _do_upload(self)
716
        except errors.RadioError:
717
            raise
718
        except Exception, e:
719
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
720

    
721
    def get_raw_memory(self, number):
722
        return repr(self._memobj.memory[number])
723

    
724
    def _is_txinh(self, _mem):
725
        raw_tx = ""
726
        for i in range(0, 4):
727
            raw_tx += _mem.txfreq[i].get_raw()
728
        return raw_tx == "\xFF\xFF\xFF\xFF"
729

    
730
    def _get_mem(self, number):
731
        return self._memobj.memory[number]
732

    
733
    def _get_nam(self, number):
734
        return self._memobj.names[number]
735

    
736
    def get_memory(self, number):
737
        _mem = self._get_mem(number)
738
        _nam = self._get_nam(number)
739

    
740
        mem = chirp_common.Memory()
741
        mem.number = number
742

    
743
        if _mem.get_raw()[0] == "\xff":
744
            mem.empty = True
745
            return mem
746

    
747
        mem.freq = int(_mem.rxfreq) * 10
748

    
749
        if self._is_txinh(_mem):
750
            mem.duplex = "off"
751
            mem.offset = 0
752
        elif int(_mem.rxfreq) == int(_mem.txfreq):
753
            mem.duplex = ""
754
            mem.offset = 0
755
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 70000000:
756
            mem.duplex = "split"
757
            mem.offset = int(_mem.txfreq) * 10
758
        else:
759
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
760
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
761

    
762
        for char in _nam.name:
763
            if str(char) == "\xFF":
764
                char = " "  # The UV-5R software may have 0xFF mid-name
765
            mem.name += str(char)
766
        mem.name = mem.name.rstrip()
767

    
768
        dtcs_pol = ["N", "N"]
769

    
770
        if _mem.txtone in [0, 0xFFFF]:
771
            txmode = ""
772
        elif _mem.txtone >= 0x0258:
773
            txmode = "Tone"
774
            mem.rtone = int(_mem.txtone) / 10.0
775
        elif _mem.txtone <= 0x0258:
776
            txmode = "DTCS"
777
            if _mem.txtone > 0x69:
778
                index = _mem.txtone - 0x6A
779
                dtcs_pol[0] = "R"
780
            else:
781
                index = _mem.txtone - 1
782
            mem.dtcs = UV5R_DTCS[index]
783
        else:
784
            LOG.warn("Bug: txtone is %04x" % _mem.txtone)
785

    
786
        if _mem.rxtone in [0, 0xFFFF]:
787
            rxmode = ""
788
        elif _mem.rxtone >= 0x0258:
789
            rxmode = "Tone"
790
            mem.ctone = int(_mem.rxtone) / 10.0
791
        elif _mem.rxtone <= 0x0258:
792
            rxmode = "DTCS"
793
            if _mem.rxtone >= 0x6A:
794
                index = _mem.rxtone - 0x6A
795
                dtcs_pol[1] = "R"
796
            else:
797
                index = _mem.rxtone - 1
798
            mem.rx_dtcs = UV5R_DTCS[index]
799
        else:
800
            LOG.warn("Bug: rxtone is %04x" % _mem.rxtone)
801

    
802
        if txmode == "Tone" and not rxmode:
803
            mem.tmode = "Tone"
804
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
805
            mem.tmode = "TSQL"
806
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
807
            mem.tmode = "DTCS"
808
        elif rxmode or txmode:
809
            mem.tmode = "Cross"
810
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
811

    
812
        mem.dtcs_polarity = "".join(dtcs_pol)
813

    
814
        if not _mem.scan:
815
            mem.skip = "S"
816

    
817
        if self.MODEL in ("KT-980HP", "BF-F8HP", "UV-82HP"):
818
            levels = UV5R_POWER_LEVELS3
819
        else:
820
            levels = UV5R_POWER_LEVELS
821
        try:
822
            mem.power = levels[_mem.lowpower]
823
        except IndexError:
824
            LOG.error("Radio reported invalid power level %s (in %s)" %
825
                      (_mem.power, levels))
826
            mem.power = levels[0]
827

    
828
        mem.mode = _mem.wide and "FM" or "NFM"
829

    
830
        mem.extra = RadioSettingGroup("Extra", "extra")
831

    
832
        rs = RadioSetting("bcl", "BCL",
833
                          RadioSettingValueBoolean(_mem.bcl))
834
        mem.extra.append(rs)
835

    
836
        rs = RadioSetting("pttid", "PTT ID",
837
                          RadioSettingValueList(PTTID_LIST,
838
                                                PTTID_LIST[_mem.pttid]))
839
        mem.extra.append(rs)
840

    
841
        rs = RadioSetting("scode", "PTT ID Code",
842
                          RadioSettingValueList(PTTIDCODE_LIST,
843
                                                PTTIDCODE_LIST[_mem.scode]))
844
        mem.extra.append(rs)
845

    
846
        return mem
847

    
848
    def _set_mem(self, number):
849
        return self._memobj.memory[number]
850

    
851
    def _set_nam(self, number):
852
        return self._memobj.names[number]
853

    
854
    def set_memory(self, mem):
855
        _mem = self._get_mem(mem.number)
856
        _nam = self._get_nam(mem.number)
857

    
858
        if mem.empty:
859
            _mem.set_raw("\xff" * 16)
860
            _nam.set_raw("\xff" * 16)
861
            return
862

    
863
        _mem.set_raw("\x00" * 16)
864

    
865
        _mem.rxfreq = mem.freq / 10
866

    
867
        if mem.duplex == "off":
868
            for i in range(0, 4):
869
                _mem.txfreq[i].set_raw("\xFF")
870
        elif mem.duplex == "split":
871
            _mem.txfreq = mem.offset / 10
872
        elif mem.duplex == "+":
873
            _mem.txfreq = (mem.freq + mem.offset) / 10
874
        elif mem.duplex == "-":
875
            _mem.txfreq = (mem.freq - mem.offset) / 10
876
        else:
877
            _mem.txfreq = mem.freq / 10
878

    
879
        _namelength = self.get_features().valid_name_length
880
        for i in range(_namelength):
881
            try:
882
                _nam.name[i] = mem.name[i]
883
            except IndexError:
884
                _nam.name[i] = "\xFF"
885

    
886
        rxmode = txmode = ""
887
        if mem.tmode == "Tone":
888
            _mem.txtone = int(mem.rtone * 10)
889
            _mem.rxtone = 0
890
        elif mem.tmode == "TSQL":
891
            _mem.txtone = int(mem.ctone * 10)
892
            _mem.rxtone = int(mem.ctone * 10)
893
        elif mem.tmode == "DTCS":
894
            rxmode = txmode = "DTCS"
895
            _mem.txtone = UV5R_DTCS.index(mem.dtcs) + 1
896
            _mem.rxtone = UV5R_DTCS.index(mem.dtcs) + 1
897
        elif mem.tmode == "Cross":
898
            txmode, rxmode = mem.cross_mode.split("->", 1)
899
            if txmode == "Tone":
900
                _mem.txtone = int(mem.rtone * 10)
901
            elif txmode == "DTCS":
902
                _mem.txtone = UV5R_DTCS.index(mem.dtcs) + 1
903
            else:
904
                _mem.txtone = 0
905
            if rxmode == "Tone":
906
                _mem.rxtone = int(mem.ctone * 10)
907
            elif rxmode == "DTCS":
908
                _mem.rxtone = UV5R_DTCS.index(mem.rx_dtcs) + 1
909
            else:
910
                _mem.rxtone = 0
911
        else:
912
            _mem.rxtone = 0
913
            _mem.txtone = 0
914

    
915
        if txmode == "DTCS" and mem.dtcs_polarity[0] == "R":
916
            _mem.txtone += 0x69
917
        if rxmode == "DTCS" and mem.dtcs_polarity[1] == "R":
918
            _mem.rxtone += 0x69
919

    
920
        _mem.scan = mem.skip != "S"
921
        _mem.wide = mem.mode == "FM"
922

    
923
        if mem.power:
924
            if self.MODEL in ("KT-980HP", "BF-F8HP", "UV-82HP"):
925
                levels = [str(l) for l in UV5R_POWER_LEVELS3]
926
                _mem.lowpower = levels.index(str(mem.power))
927
            else:
928
                _mem.lowpower = UV5R_POWER_LEVELS.index(mem.power)
929
        else:
930
            _mem.lowpower = 0
931

    
932
        for setting in mem.extra:
933
            setattr(_mem, setting.get_name(), setting.value)
934

    
935
    def _is_orig(self):
936
        version_tag = _firmware_version_from_image(self)
937
        LOG.debug("@_is_orig, version_tag: %s", util.hexprint(version_tag))
938
        try:
939
            if 'BFB' in version_tag:
940
                idx = version_tag.index("BFB") + 3
941
                version = int(version_tag[idx:idx + 3])
942
                return version < 291
943
            return False
944
        except:
945
            pass
946
        raise errors.RadioError("Unable to parse version string %s" %
947
                                version_tag)
948

    
949
    def _my_version(self):
950
        version_tag = _firmware_version_from_image(self)
951
        if 'BFB' in version_tag:
952
            idx = version_tag.index("BFB") + 3
953
            return int(version_tag[idx:idx + 3])
954

    
955
        raise Exception("Unrecognized firmware version string")
956

    
957
    def _my_upper_band(self):
958
        band_tag = _upper_band_from_image(self)
959
        return band_tag
960

    
961
    def _get_settings(self):
962
        _ani = self._memobj.ani
963
        _fm_presets = self._memobj.fm_presets
964
        _settings = self._memobj.settings
965
        _squelch = self._memobj.squelch_new
966
        _vfoa = self._memobj.vfoa
967
        _vfob = self._memobj.vfob
968
        _wmchannel = self._memobj.wmchannel
969
        basic = RadioSettingGroup("basic", "Basic Settings")
970
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
971

    
972
        group = RadioSettings(basic, advanced)
973

    
974
        rs = RadioSetting("squelch", "Carrier Squelch Level",
975
                          RadioSettingValueInteger(0, 9, _settings.squelch))
976
        basic.append(rs)
977

    
978
        rs = RadioSetting("save", "Battery Saver",
979
                          RadioSettingValueList(
980
                              SAVE_LIST, SAVE_LIST[_settings.save]))
981
        basic.append(rs)
982

    
983
        rs = RadioSetting("vox", "VOX Sensitivity",
984
                          RadioSettingValueList(
985
                              VOX_LIST, VOX_LIST[_settings.vox]))
986
        advanced.append(rs)
987

    
988
        if self.MODEL == "UV-6":
989
            # NOTE: The UV-6 calls this byte voxenable, but the UV-5R calls it
990
            # autolk. Since this is a minor difference, it will be referred to
991
            # by the wrong name for the UV-6.
992
            rs = RadioSetting("autolk", "Vox",
993
                              RadioSettingValueBoolean(_settings.autolk))
994
            advanced.append(rs)
995

    
996
        if self.MODEL != "UV-6":
997
            rs = RadioSetting("abr", "Backlight Timeout",
998
                              RadioSettingValueInteger(0, 24, _settings.abr))
999
            basic.append(rs)
1000

    
1001
        rs = RadioSetting("tdr", "Dual Watch",
1002
                          RadioSettingValueBoolean(_settings.tdr))
1003
        advanced.append(rs)
1004

    
1005
        if self.MODEL == "UV-6":
1006
            rs = RadioSetting("tdrch", "Dual Watch Channel",
1007
                              RadioSettingValueList(
1008
                                  TDRCH_LIST, TDRCH_LIST[_settings.tdrch]))
1009
            advanced.append(rs)
1010

    
1011
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1012
                              RadioSettingValueBoolean(_settings.tdrab))
1013
            advanced.append(rs)
1014
        else:
1015
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1016
                              RadioSettingValueList(
1017
                                  TDRAB_LIST, TDRAB_LIST[_settings.tdrab]))
1018
            advanced.append(rs)
1019

    
1020
        if self.MODEL == "UV-6":
1021
            rs = RadioSetting("alarm", "Alarm Sound",
1022
                              RadioSettingValueBoolean(_settings.alarm))
1023
            advanced.append(rs)
1024

    
1025
        if _settings.almod > 0x02:
1026
            val = 0x01
1027
        else:
1028
            val = _settings.almod
1029
        rs = RadioSetting("almod", "Alarm Mode",
1030
                          RadioSettingValueList(
1031
                              ALMOD_LIST, ALMOD_LIST[val]))
1032
        advanced.append(rs)
1033

    
1034
        rs = RadioSetting("beep", "Beep",
1035
                          RadioSettingValueBoolean(_settings.beep))
1036
        basic.append(rs)
1037

    
1038
        rs = RadioSetting("timeout", "Timeout Timer",
1039
                          RadioSettingValueList(
1040
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
1041
        basic.append(rs)
1042

    
1043
        if self._is_orig() and self._my_version() < 251:
1044
            rs = RadioSetting("voice", "Voice",
1045
                              RadioSettingValueBoolean(_settings.voice))
1046
            advanced.append(rs)
1047
        else:
1048
            rs = RadioSetting("voice", "Voice",
1049
                              RadioSettingValueList(
1050
                                  VOICE_LIST, VOICE_LIST[_settings.voice]))
1051
            advanced.append(rs)
1052

    
1053
        rs = RadioSetting("screv", "Scan Resume",
1054
                          RadioSettingValueList(
1055
                              RESUME_LIST, RESUME_LIST[_settings.screv]))
1056
        advanced.append(rs)
1057

    
1058
        if self.MODEL != "UV-6":
1059
            rs = RadioSetting("mdfa", "Display Mode (A)",
1060
                              RadioSettingValueList(
1061
                                  MODE_LIST, MODE_LIST[_settings.mdfa]))
1062
            basic.append(rs)
1063

    
1064
            rs = RadioSetting("mdfb", "Display Mode (B)",
1065
                              RadioSettingValueList(
1066
                                  MODE_LIST, MODE_LIST[_settings.mdfb]))
1067
            basic.append(rs)
1068

    
1069
        rs = RadioSetting("bcl", "Busy Channel Lockout",
1070
                          RadioSettingValueBoolean(_settings.bcl))
1071
        advanced.append(rs)
1072

    
1073
        if self.MODEL != "UV-6":
1074
            rs = RadioSetting("autolk", "Automatic Key Lock",
1075
                              RadioSettingValueBoolean(_settings.autolk))
1076
            advanced.append(rs)
1077

    
1078
        rs = RadioSetting("fmradio", "Broadcast FM Radio",
1079
                          RadioSettingValueBoolean(_settings.fmradio))
1080
        advanced.append(rs)
1081

    
1082
        if self.MODEL != "UV-6":
1083
            rs = RadioSetting("wtled", "Standby LED Color",
1084
                              RadioSettingValueList(
1085
                                  COLOR_LIST, COLOR_LIST[_settings.wtled]))
1086
            basic.append(rs)
1087

    
1088
            rs = RadioSetting("rxled", "RX LED Color",
1089
                              RadioSettingValueList(
1090
                                  COLOR_LIST, COLOR_LIST[_settings.rxled]))
1091
            basic.append(rs)
1092

    
1093
            rs = RadioSetting("txled", "TX LED Color",
1094
                              RadioSettingValueList(
1095
                                  COLOR_LIST, COLOR_LIST[_settings.txled]))
1096
            basic.append(rs)
1097

    
1098
        if self.MODEL == "UV-82":
1099
            rs = RadioSetting("roger", "Roger Beep (TX)",
1100
                              RadioSettingValueBoolean(_settings.roger))
1101
            basic.append(rs)
1102
            rs = RadioSetting("rogerrx", "Roger Beep (RX)",
1103
                              RadioSettingValueList(
1104
                                  ROGERRX_LIST,
1105
                                  ROGERRX_LIST[_settings.rogerrx]))
1106
            basic.append(rs)
1107
        else:
1108
            rs = RadioSetting("roger", "Roger Beep",
1109
                              RadioSettingValueBoolean(_settings.roger))
1110
            basic.append(rs)
1111

    
1112
        rs = RadioSetting("ste", "Squelch Tail Eliminate (HT to HT)",
1113
                          RadioSettingValueBoolean(_settings.ste))
1114
        advanced.append(rs)
1115

    
1116
        rs = RadioSetting("rpste", "Squelch Tail Eliminate (repeater)",
1117
                          RadioSettingValueList(
1118
                              RPSTE_LIST, RPSTE_LIST[_settings.rpste]))
1119
        advanced.append(rs)
1120

    
1121
        rs = RadioSetting("rptrl", "STE Repeater Delay",
1122
                          RadioSettingValueList(
1123
                              STEDELAY_LIST, STEDELAY_LIST[_settings.rptrl]))
1124
        advanced.append(rs)
1125

    
1126
        if self.MODEL != "UV-6":
1127
            rs = RadioSetting("reset", "RESET Menu",
1128
                              RadioSettingValueBoolean(_settings.reset))
1129
            advanced.append(rs)
1130

    
1131
            rs = RadioSetting("menu", "All Menus",
1132
                              RadioSettingValueBoolean(_settings.menu))
1133
            advanced.append(rs)
1134

    
1135
        if self.MODEL == "F-11":
1136
            # this is an F-11 only feature
1137
            rs = RadioSetting("vfomrlock", "VFO/MR Button",
1138
                              RadioSettingValueBoolean(_settings.vfomrlock))
1139
            advanced.append(rs)
1140

    
1141
        if self.MODEL == "UV-82":
1142
            # this is a UV-82C only feature
1143
            rs = RadioSetting("vfomrlock", "VFO/MR Switching (UV-82C only)",
1144
                              RadioSettingValueBoolean(_settings.vfomrlock))
1145
            advanced.append(rs)
1146

    
1147
        if self.MODEL == "UV-82HP":
1148
            # this is a UV-82HP only feature
1149
            rs = RadioSetting("vfomrlock", "VFO/MR Switching",
1150
                              RadioSettingValueBoolean(_settings.vfomrlock))
1151
            advanced.append(rs)
1152

    
1153
        if self.MODEL == "UV-82":
1154
            # this is an UV-82C only feature
1155
            rs = RadioSetting("singleptt", "Single PTT (UV-82C only)",
1156
                              RadioSettingValueBoolean(_settings.singleptt))
1157
            advanced.append(rs)
1158

    
1159
        if self.MODEL == "UV-82HP":
1160
            # this is an UV-82HP only feature
1161
            rs = RadioSetting("singleptt", "Single PTT",
1162
                              RadioSettingValueBoolean(_settings.singleptt))
1163
            advanced.append(rs)
1164

    
1165
        if self.MODEL == "UV-82HP":
1166
            # this is an UV-82HP only feature
1167
            rs = RadioSetting("tdrch", "Tone Burst Frequency",
1168
                              RadioSettingValueList(
1169
                                  RTONE_LIST, RTONE_LIST[_settings.tdrch]))
1170
            advanced.append(rs)
1171

    
1172
        if len(self._mmap.get_packed()) == 0x1808:
1173
            # Old image, without aux block
1174
            return group
1175

    
1176
        other = RadioSettingGroup("other", "Other Settings")
1177
        group.append(other)
1178

    
1179
        def _filter(name):
1180
            filtered = ""
1181
            for char in str(name):
1182
                if char in chirp_common.CHARSET_ASCII:
1183
                    filtered += char
1184
                else:
1185
                    filtered += " "
1186
            return filtered
1187

    
1188
        _msg = self._memobj.firmware_msg
1189
        val = RadioSettingValueString(0, 7, _filter(_msg.line1))
1190
        val.set_mutable(False)
1191
        rs = RadioSetting("firmware_msg.line1", "Firmware Message 1", val)
1192
        other.append(rs)
1193

    
1194
        val = RadioSettingValueString(0, 7, _filter(_msg.line2))
1195
        val.set_mutable(False)
1196
        rs = RadioSetting("firmware_msg.line2", "Firmware Message 2", val)
1197
        other.append(rs)
1198

    
1199
        if self.MODEL != "UV-6":
1200
            _msg = self._memobj.sixpoweron_msg
1201
            rs = RadioSetting("sixpoweron_msg.line1", "6+Power-On Message 1",
1202
                              RadioSettingValueString(
1203
                                  0, 7, _filter(_msg.line1)))
1204
            other.append(rs)
1205
            rs = RadioSetting("sixpoweron_msg.line2", "6+Power-On Message 2",
1206
                              RadioSettingValueString(
1207
                                  0, 7, _filter(_msg.line2)))
1208
            other.append(rs)
1209

    
1210
            _msg = self._memobj.poweron_msg
1211
            rs = RadioSetting("poweron_msg.line1", "Power-On Message 1",
1212
                              RadioSettingValueString(
1213
                                  0, 7, _filter(_msg.line1)))
1214
            other.append(rs)
1215
            rs = RadioSetting("poweron_msg.line2", "Power-On Message 2",
1216
                              RadioSettingValueString(
1217
                                  0, 7, _filter(_msg.line2)))
1218
            other.append(rs)
1219

    
1220
            rs = RadioSetting("ponmsg", "Power-On Message",
1221
                              RadioSettingValueList(
1222
                                  PONMSG_LIST, PONMSG_LIST[_settings.ponmsg]))
1223
            other.append(rs)
1224

    
1225
            if self._is_orig():
1226
                limit = "limits_old"
1227
            else:
1228
                limit = "limits_new"
1229

    
1230
            vhf_limit = getattr(self._memobj, limit).vhf
1231
            rs = RadioSetting("%s.vhf.lower" % limit, "VHF Lower Limit (MHz)",
1232
                              RadioSettingValueInteger(1, 1000,
1233
                                                       vhf_limit.lower))
1234
            other.append(rs)
1235

    
1236
            rs = RadioSetting("%s.vhf.upper" % limit, "VHF Upper Limit (MHz)",
1237
                              RadioSettingValueInteger(1, 1000,
1238
                                                       vhf_limit.upper))
1239
            other.append(rs)
1240

    
1241
            rs = RadioSetting("%s.vhf.enable" % limit, "VHF TX Enabled",
1242
                              RadioSettingValueBoolean(vhf_limit.enable))
1243
            other.append(rs)
1244

    
1245
            uhf_limit = getattr(self._memobj, limit).uhf
1246
            rs = RadioSetting("%s.uhf.lower" % limit, "UHF Lower Limit (MHz)",
1247
                              RadioSettingValueInteger(1, 1000,
1248
                                                       uhf_limit.lower))
1249
            other.append(rs)
1250
            rs = RadioSetting("%s.uhf.upper" % limit, "UHF Upper Limit (MHz)",
1251
                              RadioSettingValueInteger(1, 1000,
1252
                                                       uhf_limit.upper))
1253
            other.append(rs)
1254
            rs = RadioSetting("%s.uhf.enable" % limit, "UHF TX Enabled",
1255
                              RadioSettingValueBoolean(uhf_limit.enable))
1256
            other.append(rs)
1257

    
1258
        if self.MODEL != "UV-6":
1259
            workmode = RadioSettingGroup("workmode", "Work Mode Settings")
1260
            group.append(workmode)
1261

    
1262
            rs = RadioSetting("displayab", "Display",
1263
                              RadioSettingValueList(
1264
                                  AB_LIST, AB_LIST[_settings.displayab]))
1265
            workmode.append(rs)
1266

    
1267
            rs = RadioSetting("workmode", "VFO/MR Mode",
1268
                              RadioSettingValueList(
1269
                                  WORKMODE_LIST,
1270
                                  WORKMODE_LIST[_settings.workmode]))
1271
            workmode.append(rs)
1272

    
1273
            rs = RadioSetting("keylock", "Keypad Lock",
1274
                              RadioSettingValueBoolean(_settings.keylock))
1275
            workmode.append(rs)
1276

    
1277
            rs = RadioSetting("wmchannel.mrcha", "MR A Channel",
1278
                              RadioSettingValueInteger(0, 127,
1279
                                                       _wmchannel.mrcha))
1280
            workmode.append(rs)
1281

    
1282
            rs = RadioSetting("wmchannel.mrchb", "MR B Channel",
1283
                              RadioSettingValueInteger(0, 127,
1284
                                                       _wmchannel.mrchb))
1285
            workmode.append(rs)
1286

    
1287
            def convert_bytes_to_freq(bytes):
1288
                real_freq = 0
1289
                for byte in bytes:
1290
                    real_freq = (real_freq * 10) + byte
1291
                return chirp_common.format_freq(real_freq * 10)
1292

    
1293
            def my_validate(value):
1294
                value = chirp_common.parse_freq(value)
1295
                if 17400000 <= value and value < 40000000:
1296
                    msg = ("Can't be between 174.00000-400.00000")
1297
                    raise InvalidValueError(msg)
1298
                return chirp_common.format_freq(value)
1299

    
1300
            def apply_freq(setting, obj):
1301
                value = chirp_common.parse_freq(str(setting.value)) / 10
1302
                obj.band = value >= 40000000
1303
                for i in range(7, -1, -1):
1304
                    obj.freq[i] = value % 10
1305
                    value /= 10
1306

    
1307
            val1a = RadioSettingValueString(0, 10,
1308
                                            convert_bytes_to_freq(_vfoa.freq))
1309
            val1a.set_validate_callback(my_validate)
1310
            rs = RadioSetting("vfoa.freq", "VFO A Frequency", val1a)
1311
            rs.set_apply_callback(apply_freq, _vfoa)
1312
            workmode.append(rs)
1313

    
1314
            val1b = RadioSettingValueString(0, 10,
1315
                                            convert_bytes_to_freq(_vfob.freq))
1316
            val1b.set_validate_callback(my_validate)
1317
            rs = RadioSetting("vfob.freq", "VFO B Frequency", val1b)
1318
            rs.set_apply_callback(apply_freq, _vfob)
1319
            workmode.append(rs)
1320

    
1321
            rs = RadioSetting("vfoa.sftd", "VFO A Shift",
1322
                              RadioSettingValueList(
1323
                                  SHIFTD_LIST, SHIFTD_LIST[_vfoa.sftd]))
1324
            workmode.append(rs)
1325

    
1326
            rs = RadioSetting("vfob.sftd", "VFO B Shift",
1327
                              RadioSettingValueList(
1328
                                  SHIFTD_LIST, SHIFTD_LIST[_vfob.sftd]))
1329
            workmode.append(rs)
1330

    
1331
            def convert_bytes_to_offset(bytes):
1332
                real_offset = 0
1333
                for byte in bytes:
1334
                    real_offset = (real_offset * 10) + byte
1335
                return chirp_common.format_freq(real_offset * 10000)
1336

    
1337
            def apply_offset(setting, obj):
1338
                value = chirp_common.parse_freq(str(setting.value)) / 10000
1339
                for i in range(3, -1, -1):
1340
                    obj.offset[i] = value % 10
1341
                    value /= 10
1342

    
1343
            val1a = RadioSettingValueString(
1344
                        0, 10, convert_bytes_to_offset(_vfoa.offset))
1345
            rs = RadioSetting("vfoa.offset",
1346
                              "VFO A Offset (0.00-69.95)", val1a)
1347
            rs.set_apply_callback(apply_offset, _vfoa)
1348
            workmode.append(rs)
1349

    
1350
            val1b = RadioSettingValueString(
1351
                        0, 10, convert_bytes_to_offset(_vfob.offset))
1352
            rs = RadioSetting("vfob.offset",
1353
                              "VFO B Offset (0.00-69.95)", val1b)
1354
            rs.set_apply_callback(apply_offset, _vfob)
1355
            workmode.append(rs)
1356

    
1357
            if self.MODEL in ("KT-980HP", "BF-F8HP", "UV-82HP"):
1358
                rs = RadioSetting("vfoa.txpower3", "VFO A Power",
1359
                                  RadioSettingValueList(
1360
                                      TXPOWER3_LIST,
1361
                                      TXPOWER3_LIST[_vfoa.txpower3]))
1362
                workmode.append(rs)
1363

    
1364
                rs = RadioSetting("vfob.txpower3", "VFO B Power",
1365
                                  RadioSettingValueList(
1366
                                      TXPOWER3_LIST,
1367
                                      TXPOWER3_LIST[_vfob.txpower3]))
1368
                workmode.append(rs)
1369
            else:
1370
                rs = RadioSetting("vfoa.txpower", "VFO A Power",
1371
                                  RadioSettingValueList(
1372
                                      TXPOWER_LIST,
1373
                                      TXPOWER_LIST[_vfoa.txpower]))
1374
                workmode.append(rs)
1375

    
1376
                rs = RadioSetting("vfob.txpower", "VFO B Power",
1377
                                  RadioSettingValueList(
1378
                                      TXPOWER_LIST,
1379
                                      TXPOWER_LIST[_vfob.txpower]))
1380
                workmode.append(rs)
1381

    
1382
            rs = RadioSetting("vfoa.widenarr", "VFO A Bandwidth",
1383
                              RadioSettingValueList(
1384
                                  BANDWIDTH_LIST,
1385
                                  BANDWIDTH_LIST[_vfoa.widenarr]))
1386
            workmode.append(rs)
1387

    
1388
            rs = RadioSetting("vfob.widenarr", "VFO B Bandwidth",
1389
                              RadioSettingValueList(
1390
                                  BANDWIDTH_LIST,
1391
                                  BANDWIDTH_LIST[_vfob.widenarr]))
1392
            workmode.append(rs)
1393

    
1394
            rs = RadioSetting("vfoa.scode", "VFO A PTT-ID",
1395
                              RadioSettingValueList(
1396
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfoa.scode]))
1397
            workmode.append(rs)
1398

    
1399
            rs = RadioSetting("vfob.scode", "VFO B PTT-ID",
1400
                              RadioSettingValueList(
1401
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfob.scode]))
1402
            workmode.append(rs)
1403

    
1404
            if not self._is_orig():
1405
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1406
                                  RadioSettingValueList(
1407
                                      STEP291_LIST, STEP291_LIST[_vfoa.step]))
1408
                workmode.append(rs)
1409
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1410
                                  RadioSettingValueList(
1411
                                      STEP291_LIST, STEP291_LIST[_vfob.step]))
1412
                workmode.append(rs)
1413
            else:
1414
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1415
                                  RadioSettingValueList(
1416
                                      STEP_LIST, STEP_LIST[_vfoa.step]))
1417
                workmode.append(rs)
1418
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1419
                                  RadioSettingValueList(
1420
                                      STEP_LIST, STEP_LIST[_vfob.step]))
1421
                workmode.append(rs)
1422

    
1423
        fm_preset = RadioSettingGroup("fm_preset", "FM Radio Preset")
1424
        group.append(fm_preset)
1425

    
1426
        if _fm_presets <= 108.0 * 10 - 650:
1427
            preset = _fm_presets / 10.0 + 65
1428
        elif _fm_presets >= 65.0 * 10 and _fm_presets <= 108.0 * 10:
1429
            preset = _fm_presets / 10.0
1430
        else:
1431
            preset = 76.0
1432
        rs = RadioSetting("fm_presets", "FM Preset(MHz)",
1433
                          RadioSettingValueFloat(65, 108.0, preset, 0.1, 1))
1434
        fm_preset.append(rs)
1435

    
1436
        dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
1437
        group.append(dtmf)
1438
        dtmfchars = "0123456789 *#ABCD"
1439

    
1440
        for i in range(0, 15):
1441
            _codeobj = self._memobj.pttid[i].code
1442
            _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1443
            val = RadioSettingValueString(0, 5, _code, False)
1444
            val.set_charset(dtmfchars)
1445
            rs = RadioSetting("pttid/%i.code" % i,
1446
                              "PTT ID Code %i" % (i + 1), val)
1447

    
1448
            def apply_code(setting, obj):
1449
                code = []
1450
                for j in range(0, 5):
1451
                    try:
1452
                        code.append(dtmfchars.index(str(setting.value)[j]))
1453
                    except IndexError:
1454
                        code.append(0xFF)
1455
                obj.code = code
1456
            rs.set_apply_callback(apply_code, self._memobj.pttid[i])
1457
            dtmf.append(rs)
1458

    
1459
        _codeobj = self._memobj.ani.code
1460
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1461
        val = RadioSettingValueString(0, 5, _code, False)
1462
        val.set_charset(dtmfchars)
1463
        rs = RadioSetting("ani.code", "ANI Code", val)
1464

    
1465
        def apply_code(setting, obj):
1466
            code = []
1467
            for j in range(0, 5):
1468
                try:
1469
                    code.append(dtmfchars.index(str(setting.value)[j]))
1470
                except IndexError:
1471
                    code.append(0xFF)
1472
            obj.code = code
1473
        rs.set_apply_callback(apply_code, _ani)
1474
        dtmf.append(rs)
1475

    
1476
        rs = RadioSetting("ani.aniid", "ANI ID",
1477
                          RadioSettingValueList(PTTID_LIST,
1478
                                                PTTID_LIST[_ani.aniid]))
1479
        dtmf.append(rs)
1480

    
1481
        _codeobj = self._memobj.ani.alarmcode
1482
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1483
        val = RadioSettingValueString(0, 3, _code, False)
1484
        val.set_charset(dtmfchars)
1485
        rs = RadioSetting("ani.alarmcode", "Alarm Code", val)
1486

    
1487
        def apply_code(setting, obj):
1488
            alarmcode = []
1489
            for j in range(0, 3):
1490
                try:
1491
                    alarmcode.append(dtmfchars.index(str(setting.value)[j]))
1492
                except IndexError:
1493
                    alarmcode.append(0xFF)
1494
            obj.alarmcode = alarmcode
1495
        rs.set_apply_callback(apply_code, _ani)
1496
        dtmf.append(rs)
1497

    
1498
        rs = RadioSetting("dtmfst", "DTMF Sidetone",
1499
                          RadioSettingValueList(DTMFST_LIST,
1500
                                                DTMFST_LIST[_settings.dtmfst]))
1501
        dtmf.append(rs)
1502

    
1503
        if _ani.dtmfon > 0xC3:
1504
            val = 0x00
1505
        else:
1506
            val = _ani.dtmfon
1507
        rs = RadioSetting("ani.dtmfon", "DTMF Speed (on)",
1508
                          RadioSettingValueList(DTMFSPEED_LIST,
1509
                                                DTMFSPEED_LIST[val]))
1510
        dtmf.append(rs)
1511

    
1512
        if _ani.dtmfoff > 0xC3:
1513
            val = 0x00
1514
        else:
1515
            val = _ani.dtmfoff
1516
        rs = RadioSetting("ani.dtmfoff", "DTMF Speed (off)",
1517
                          RadioSettingValueList(DTMFSPEED_LIST,
1518
                                                DTMFSPEED_LIST[val]))
1519
        dtmf.append(rs)
1520

    
1521
        rs = RadioSetting("pttlt", "PTT ID Delay",
1522
                          RadioSettingValueInteger(0, 30, _settings.pttlt))
1523
        dtmf.append(rs)
1524

    
1525
        if not self._is_orig():
1526
            service = RadioSettingGroup("service", "Service Settings")
1527
            group.append(service)
1528

    
1529
            for band in ["vhf", "uhf"]:
1530
                for index in range(0, 10):
1531
                    key = "squelch_new.%s.sql%i" % (band, index)
1532
                    if band == "vhf":
1533
                        _obj = self._memobj.squelch_new.vhf
1534
                    elif band == "uhf":
1535
                        _obj = self._memobj.squelch_new.uhf
1536
                    name = "%s Squelch %i" % (band.upper(), index)
1537
                    rs = RadioSetting(key, name,
1538
                                      RadioSettingValueInteger(
1539
                                          0, 123,
1540
                                          getattr(_obj, "sql%i" % (index))))
1541
                    service.append(rs)
1542

    
1543
        return group
1544

    
1545
    def get_settings(self):
1546
        try:
1547
            return self._get_settings()
1548
        except:
1549
            import traceback
1550
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1551
            return None
1552

    
1553
    def set_settings(self, settings):
1554
        _settings = self._memobj.settings
1555
        for element in settings:
1556
            if not isinstance(element, RadioSetting):
1557
                if element.get_name() == "fm_preset":
1558
                    self._set_fm_preset(element)
1559
                else:
1560
                    self.set_settings(element)
1561
                    continue
1562
            else:
1563
                try:
1564
                    name = element.get_name()
1565
                    if "." in name:
1566
                        bits = name.split(".")
1567
                        obj = self._memobj
1568
                        for bit in bits[:-1]:
1569
                            if "/" in bit:
1570
                                bit, index = bit.split("/", 1)
1571
                                index = int(index)
1572
                                obj = getattr(obj, bit)[index]
1573
                            else:
1574
                                obj = getattr(obj, bit)
1575
                        setting = bits[-1]
1576
                    else:
1577
                        obj = _settings
1578
                        setting = element.get_name()
1579

    
1580
                    if element.has_apply_callback():
1581
                        LOG.debug("Using apply callback")
1582
                        element.run_apply_callback()
1583
                    elif element.value.get_mutable():
1584
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1585
                        setattr(obj, setting, element.value)
1586
                except Exception, e:
1587
                    LOG.debug(element.get_name())
1588
                    raise
1589

    
1590
    def _set_fm_preset(self, settings):
1591
        for element in settings:
1592
            try:
1593
                val = element.value
1594
                if self._memobj.fm_presets <= 108.0 * 10 - 650:
1595
                    value = int(val.get_value() * 10 - 650)
1596
                else:
1597
                    value = int(val.get_value() * 10)
1598
                LOG.debug("Setting fm_presets = %s" % (value))
1599
                self._memobj.fm_presets = value
1600
            except Exception, e:
1601
                LOG.debug(element.get_name())
1602
                raise
1603

    
1604

    
1605
class UV5XAlias(chirp_common.Alias):
1606
    VENDOR = "Baofeng"
1607
    MODEL = "UV-5X"
1608

    
1609

    
1610
class RT5RAlias(chirp_common.Alias):
1611
    VENDOR = "Retevis"
1612
    MODEL = "RT-5R"
1613

    
1614

    
1615
@directory.register
1616
class BaofengUV5RGeneric(BaofengUV5R):
1617
    ALIASES = [UV5XAlias, RT5RAlias]
1618

    
1619

    
1620
@directory.register
1621
class BaofengF11Radio(BaofengUV5R):
1622
    VENDOR = "Baofeng"
1623
    MODEL = "F-11"
1624
    _basetype = BASETYPE_F11
1625
    _idents = [UV5R_MODEL_F11]
1626

    
1627
    def _is_orig(self):
1628
        # Override this for F11 to always return False
1629
        return False
1630

    
1631

    
1632
@directory.register
1633
class BaofengUV82Radio(BaofengUV5R):
1634
    MODEL = "UV-82"
1635
    _basetype = BASETYPE_UV82
1636
    _idents = [UV5R_MODEL_UV82]
1637
    _vhf_range = (130000000, 176000000)
1638
    _uhf_range = (400000000, 521000000)
1639

    
1640
    def _is_orig(self):
1641
        # Override this for UV82 to always return False
1642
        return False
1643

    
1644

    
1645
@directory.register
1646
class BaofengUV6Radio(BaofengUV5R):
1647
    """Baofeng UV-6/UV-7"""
1648
    VENDOR = "Baofeng"
1649
    MODEL = "UV-6"
1650
    _basetype = BASETYPE_UV6
1651
    _idents = [UV5R_MODEL_UV6,
1652
               UV5R_MODEL_UV6_ORIG
1653
               ]
1654

    
1655
    def get_features(self):
1656
        rf = BaofengUV5R.get_features(self)
1657
        rf.memory_bounds = (1, 128)
1658
        return rf
1659

    
1660
    def _get_mem(self, number):
1661
        return self._memobj.memory[number - 1]
1662

    
1663
    def _get_nam(self, number):
1664
        return self._memobj.names[number - 1]
1665

    
1666
    def _set_mem(self, number):
1667
        return self._memobj.memory[number - 1]
1668

    
1669
    def _set_nam(self, number):
1670
        return self._memobj.names[number - 1]
1671

    
1672
    def _is_orig(self):
1673
        # Override this for UV6 to always return False
1674
        return False
1675

    
1676

    
1677
@directory.register
1678
class IntekKT980Radio(BaofengUV5R):
1679
    VENDOR = "Intek"
1680
    MODEL = "KT-980HP"
1681
    _basetype = BASETYPE_KT980HP
1682
    _idents = [UV5R_MODEL_291]
1683
    _vhf_range = (130000000, 180000000)
1684
    _uhf_range = (400000000, 521000000)
1685

    
1686
    def get_features(self):
1687
        rf = BaofengUV5R.get_features(self)
1688
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1689
        return rf
1690

    
1691
    def _is_orig(self):
1692
        # Override this for KT980HP to always return False
1693
        return False
1694

    
1695

    
1696
@directory.register
1697
class BaofengBFF8HPRadio(BaofengUV5R):
1698
    VENDOR = "Baofeng"
1699
    MODEL = "BF-F8HP"
1700
    _basetype = BASETYPE_F8HP
1701
    _idents = [UV5R_MODEL_291,
1702
               UV5R_MODEL_A58
1703
               ]
1704
    _vhf_range = (130000000, 180000000)
1705
    _uhf_range = (400000000, 521000000)
1706

    
1707
    def get_features(self):
1708
        rf = BaofengUV5R.get_features(self)
1709
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1710
        return rf
1711

    
1712
    def _is_orig(self):
1713
        # Override this for BFF8HP to always return False
1714
        return False
1715

    
1716

    
1717
@directory.register
1718
class BaofengUV82HPRadio(BaofengUV5R):
1719
    VENDOR = "Baofeng"
1720
    MODEL = "UV-82HP"
1721
    _basetype = BASETYPE_UV82HP
1722
    _idents = [UV5R_MODEL_UV82]
1723
    _vhf_range = (136000000, 175000000)
1724
    _uhf_range = (400000000, 521000000)
1725

    
1726
    def get_features(self):
1727
        rf = BaofengUV5R.get_features(self)
1728
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1729
        return rf
1730

    
1731
    def _is_orig(self):
1732
        # Override this for UV82HP to always return False
1733
        return False