Project

General

Profile

Bug #3987 » uv5r(3987).py

Jim Unroe, 09/19/2016 02:28 AM

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

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

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

    
29
LOG = logging.getLogger(__name__)
30

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

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

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

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

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

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

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

    
200
#seekto 0x0F56;
201
u16 fm_presets;
202

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

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

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

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

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

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

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

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

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

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

    
277
"""
278

    
279
# 0x1EC0 - 0x2000
280

    
281
vhf_220_radio = "\x02"
282

    
283
BASETYPE_UV5R = ["BFS", "BFB", "N5R-2", "N5R2", "N5RV", "BTS", "D5R2"]
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
    ident = ""
428
    for i in range(1, 13):
429
        response = serial.read(1)
430
        # discard any bytes containing "\x01" and keep the rest
431
        ####if response != "\x01":
432
        ident += response
433
        # stop reading once the last byte ("\xdd") is encountered
434
        if response == "\xdd":
435
            break
436

    
437
    # check if response is OK
438
    if len(ident) != 8 or not ident.startswith("\xaa"):
439
        # bad response
440
        msg = "Unexpected response, got this:"
441
        msg += util.hexprint(ident)
442
        LOG.debug(msg)
443
        raise errors.RadioError("Unexpected response from radio.")
444

    
445
    # DEBUG
446
    LOG.info("Valid response, got this:")
447
    LOG.debug(util.hexprint(ident))
448

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

    
454
    return ident
455

    
456

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

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

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

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

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

    
484
    radio.pipe.write("\x06")
485
    time.sleep(0.05)
486

    
487
    return chunk
488

    
489

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

    
501

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

    
516

    
517
def _do_download(radio):
518
    data = _ident_radio(radio)
519

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

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

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

    
540

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

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

    
550

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

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

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

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

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

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

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

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

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

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

    
600
UV5R_DTCS = sorted(chirp_common.DTCS_CODES + [645])
601

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

    
605

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

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

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

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

    
671
        normal_bands = [self._vhf_range, self._uhf_range]
672
        rax_bands = [self._vhf_range, self._220_range]
673

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

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

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

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

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

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

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

    
728
    def _get_mem(self, number):
729
        return self._memobj.memory[number]
730

    
731
    def _get_nam(self, number):
732
        return self._memobj.names[number]
733

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

    
738
        mem = chirp_common.Memory()
739
        mem.number = number
740

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

    
745
        mem.freq = int(_mem.rxfreq) * 10
746

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

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

    
766
        dtcs_pol = ["N", "N"]
767

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

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

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

    
810
        mem.dtcs_polarity = "".join(dtcs_pol)
811

    
812
        if not _mem.scan:
813
            mem.skip = "S"
814

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

    
826
        mem.mode = _mem.wide and "FM" or "NFM"
827

    
828
        mem.extra = RadioSettingGroup("Extra", "extra")
829

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

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

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

    
844
        return mem
845

    
846
    def _set_mem(self, number):
847
        return self._memobj.memory[number]
848

    
849
    def _set_nam(self, number):
850
        return self._memobj.names[number]
851

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

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

    
861
        _mem.set_raw("\x00" * 16)
862

    
863
        _mem.rxfreq = mem.freq / 10
864

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

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

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

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

    
918
        _mem.scan = mem.skip != "S"
919
        _mem.wide = mem.mode == "FM"
920

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

    
930
        for setting in mem.extra:
931
            setattr(_mem, setting.get_name(), setting.value)
932

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

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

    
953
        raise Exception("Unrecognized firmware version string")
954

    
955
    def _my_upper_band(self):
956
        band_tag = _upper_band_from_image(self)
957
        return band_tag
958

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

    
970
        group = RadioSettings(basic, advanced)
971

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1174
        other = RadioSettingGroup("other", "Other Settings")
1175
        group.append(other)
1176

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1421
        fm_preset = RadioSettingGroup("fm_preset", "FM Radio Preset")
1422
        group.append(fm_preset)
1423

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1541
        return group
1542

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

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

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

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

    
1602

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

    
1607

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

    
1612

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

    
1617

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

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

    
1629

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

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

    
1642

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

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

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

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

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

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

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

    
1674

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

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

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

    
1693

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

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

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

    
1714

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

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

    
1729
    def _is_orig(self):
1730
        # Override this for UV82HP to always return False
1731
        return False
(2-2/5)