Project

General

Profile

New Model #4445 » uv5r(2).py

Steff *, 01/31/2017 03:43 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", "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", "N5RV", "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

    
611
    """Baofeng UV-5R"""
612
    VENDOR = "Baofeng"
613
    MODEL = "UV-5R"
614
    BAUD_RATE = 9600
615

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
847
        return mem
848

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

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

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

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

    
864
        was_empty = False
865
        # same method as used in get_memory to find
866
        # out whether a raw memory is empty
867
        if _mem.get_raw()[0] == "\xff":
868
            was_empty = True
869
            LOG.debug("UV5R: this mem was empty")
870
        else:
871
            # memorize old extra-values before erasing the whole memory
872
            # used to solve issue 4121
873
            LOG.debug("mem was not empty, memorize extra-settings")
874
            prev_bcl = _mem.bcl.get_value()
875
            prev_scode = _mem.scode.get_value()
876
            prev_pttid = _mem.pttid.get_value()
877

    
878
        _mem.set_raw("\x00" * 16)
879

    
880
        _mem.rxfreq = mem.freq / 10
881

    
882
        if mem.duplex == "off":
883
            for i in range(0, 4):
884
                _mem.txfreq[i].set_raw("\xFF")
885
        elif mem.duplex == "split":
886
            _mem.txfreq = mem.offset / 10
887
        elif mem.duplex == "+":
888
            _mem.txfreq = (mem.freq + mem.offset) / 10
889
        elif mem.duplex == "-":
890
            _mem.txfreq = (mem.freq - mem.offset) / 10
891
        else:
892
            _mem.txfreq = mem.freq / 10
893

    
894
        _namelength = self.get_features().valid_name_length
895
        for i in range(_namelength):
896
            try:
897
                _nam.name[i] = mem.name[i]
898
            except IndexError:
899
                _nam.name[i] = "\xFF"
900

    
901
        rxmode = txmode = ""
902
        if mem.tmode == "Tone":
903
            _mem.txtone = int(mem.rtone * 10)
904
            _mem.rxtone = 0
905
        elif mem.tmode == "TSQL":
906
            _mem.txtone = int(mem.ctone * 10)
907
            _mem.rxtone = int(mem.ctone * 10)
908
        elif mem.tmode == "DTCS":
909
            rxmode = txmode = "DTCS"
910
            _mem.txtone = UV5R_DTCS.index(mem.dtcs) + 1
911
            _mem.rxtone = UV5R_DTCS.index(mem.dtcs) + 1
912
        elif mem.tmode == "Cross":
913
            txmode, rxmode = mem.cross_mode.split("->", 1)
914
            if txmode == "Tone":
915
                _mem.txtone = int(mem.rtone * 10)
916
            elif txmode == "DTCS":
917
                _mem.txtone = UV5R_DTCS.index(mem.dtcs) + 1
918
            else:
919
                _mem.txtone = 0
920
            if rxmode == "Tone":
921
                _mem.rxtone = int(mem.ctone * 10)
922
            elif rxmode == "DTCS":
923
                _mem.rxtone = UV5R_DTCS.index(mem.rx_dtcs) + 1
924
            else:
925
                _mem.rxtone = 0
926
        else:
927
            _mem.rxtone = 0
928
            _mem.txtone = 0
929

    
930
        if txmode == "DTCS" and mem.dtcs_polarity[0] == "R":
931
            _mem.txtone += 0x69
932
        if rxmode == "DTCS" and mem.dtcs_polarity[1] == "R":
933
            _mem.rxtone += 0x69
934

    
935
        _mem.scan = mem.skip != "S"
936
        _mem.wide = mem.mode == "FM"
937

    
938
        if mem.power:
939
            if self.MODEL in ("KT-980HP", "BF-F8HP", "UV-82HP"):
940
                levels = [str(l) for l in UV5R_POWER_LEVELS3]
941
                _mem.lowpower = levels.index(str(mem.power))
942
            else:
943
                _mem.lowpower = UV5R_POWER_LEVELS.index(mem.power)
944
        else:
945
            _mem.lowpower = 0
946

    
947
        if not was_empty:
948
            # restoring old extra-settings (issue 4121
949
            _mem.bcl.set_value(prev_bcl)
950
            _mem.scode.set_value(prev_scode)
951
            _mem.pttid.set_value(prev_pttid)
952

    
953
        for setting in mem.extra:
954
            setattr(_mem, setting.get_name(), setting.value)
955

    
956
    def _is_orig(self):
957
        version_tag = _firmware_version_from_image(self)
958
        LOG.debug("@_is_orig, version_tag: %s", util.hexprint(version_tag))
959
        try:
960
            if 'BFB' in version_tag:
961
                idx = version_tag.index("BFB") + 3
962
                version = int(version_tag[idx:idx + 3])
963
                return version < 291
964
            return False
965
        except:
966
            pass
967
        raise errors.RadioError("Unable to parse version string %s" %
968
                                version_tag)
969

    
970
    def _my_version(self):
971
        version_tag = _firmware_version_from_image(self)
972
        if 'BFB' in version_tag:
973
            idx = version_tag.index("BFB") + 3
974
            return int(version_tag[idx:idx + 3])
975

    
976
        raise Exception("Unrecognized firmware version string")
977

    
978
    def _my_upper_band(self):
979
        band_tag = _upper_band_from_image(self)
980
        return band_tag
981

    
982
    def _get_settings(self):
983
        _ani = self._memobj.ani
984
        _fm_presets = self._memobj.fm_presets
985
        _settings = self._memobj.settings
986
        _squelch = self._memobj.squelch_new
987
        _vfoa = self._memobj.vfoa
988
        _vfob = self._memobj.vfob
989
        _wmchannel = self._memobj.wmchannel
990
        basic = RadioSettingGroup("basic", "Basic Settings")
991
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
992

    
993
        group = RadioSettings(basic, advanced)
994

    
995
        rs = RadioSetting("squelch", "Carrier Squelch Level",
996
                          RadioSettingValueInteger(0, 9, _settings.squelch))
997
        basic.append(rs)
998

    
999
        rs = RadioSetting("save", "Battery Saver",
1000
                          RadioSettingValueList(
1001
                              SAVE_LIST, SAVE_LIST[_settings.save]))
1002
        basic.append(rs)
1003

    
1004
        rs = RadioSetting("vox", "VOX Sensitivity",
1005
                          RadioSettingValueList(
1006
                              VOX_LIST, VOX_LIST[_settings.vox]))
1007
        advanced.append(rs)
1008

    
1009
        if self.MODEL == "UV-6":
1010
            # NOTE: The UV-6 calls this byte voxenable, but the UV-5R calls it
1011
            # autolk. Since this is a minor difference, it will be referred to
1012
            # by the wrong name for the UV-6.
1013
            rs = RadioSetting("autolk", "Vox",
1014
                              RadioSettingValueBoolean(_settings.autolk))
1015
            advanced.append(rs)
1016

    
1017
        if self.MODEL != "UV-6":
1018
            rs = RadioSetting("abr", "Backlight Timeout",
1019
                              RadioSettingValueInteger(0, 24, _settings.abr))
1020
            basic.append(rs)
1021

    
1022
        rs = RadioSetting("tdr", "Dual Watch",
1023
                          RadioSettingValueBoolean(_settings.tdr))
1024
        advanced.append(rs)
1025

    
1026
        if self.MODEL == "UV-6":
1027
            rs = RadioSetting("tdrch", "Dual Watch Channel",
1028
                              RadioSettingValueList(
1029
                                  TDRCH_LIST, TDRCH_LIST[_settings.tdrch]))
1030
            advanced.append(rs)
1031

    
1032
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1033
                              RadioSettingValueBoolean(_settings.tdrab))
1034
            advanced.append(rs)
1035
        else:
1036
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1037
                              RadioSettingValueList(
1038
                                  TDRAB_LIST, TDRAB_LIST[_settings.tdrab]))
1039
            advanced.append(rs)
1040

    
1041
        if self.MODEL == "UV-6":
1042
            rs = RadioSetting("alarm", "Alarm Sound",
1043
                              RadioSettingValueBoolean(_settings.alarm))
1044
            advanced.append(rs)
1045

    
1046
        if _settings.almod > 0x02:
1047
            val = 0x01
1048
        else:
1049
            val = _settings.almod
1050
        rs = RadioSetting("almod", "Alarm Mode",
1051
                          RadioSettingValueList(
1052
                              ALMOD_LIST, ALMOD_LIST[val]))
1053
        advanced.append(rs)
1054

    
1055
        rs = RadioSetting("beep", "Beep",
1056
                          RadioSettingValueBoolean(_settings.beep))
1057
        basic.append(rs)
1058

    
1059
        rs = RadioSetting("timeout", "Timeout Timer",
1060
                          RadioSettingValueList(
1061
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
1062
        basic.append(rs)
1063

    
1064
        if self._is_orig() and self._my_version() < 251:
1065
            rs = RadioSetting("voice", "Voice",
1066
                              RadioSettingValueBoolean(_settings.voice))
1067
            advanced.append(rs)
1068
        else:
1069
            rs = RadioSetting("voice", "Voice",
1070
                              RadioSettingValueList(
1071
                                  VOICE_LIST, VOICE_LIST[_settings.voice]))
1072
            advanced.append(rs)
1073

    
1074
        rs = RadioSetting("screv", "Scan Resume",
1075
                          RadioSettingValueList(
1076
                              RESUME_LIST, RESUME_LIST[_settings.screv]))
1077
        advanced.append(rs)
1078

    
1079
        if self.MODEL != "UV-6":
1080
            rs = RadioSetting("mdfa", "Display Mode (A)",
1081
                              RadioSettingValueList(
1082
                                  MODE_LIST, MODE_LIST[_settings.mdfa]))
1083
            basic.append(rs)
1084

    
1085
            rs = RadioSetting("mdfb", "Display Mode (B)",
1086
                              RadioSettingValueList(
1087
                                  MODE_LIST, MODE_LIST[_settings.mdfb]))
1088
            basic.append(rs)
1089

    
1090
        rs = RadioSetting("bcl", "Busy Channel Lockout",
1091
                          RadioSettingValueBoolean(_settings.bcl))
1092
        advanced.append(rs)
1093

    
1094
        if self.MODEL != "UV-6":
1095
            rs = RadioSetting("autolk", "Automatic Key Lock",
1096
                              RadioSettingValueBoolean(_settings.autolk))
1097
            advanced.append(rs)
1098

    
1099
        rs = RadioSetting("fmradio", "Broadcast FM Radio",
1100
                          RadioSettingValueBoolean(_settings.fmradio))
1101
        advanced.append(rs)
1102

    
1103
        if self.MODEL != "UV-6":
1104
            rs = RadioSetting("wtled", "Standby LED Color",
1105
                              RadioSettingValueList(
1106
                                  COLOR_LIST, COLOR_LIST[_settings.wtled]))
1107
            basic.append(rs)
1108

    
1109
            rs = RadioSetting("rxled", "RX LED Color",
1110
                              RadioSettingValueList(
1111
                                  COLOR_LIST, COLOR_LIST[_settings.rxled]))
1112
            basic.append(rs)
1113

    
1114
            rs = RadioSetting("txled", "TX LED Color",
1115
                              RadioSettingValueList(
1116
                                  COLOR_LIST, COLOR_LIST[_settings.txled]))
1117
            basic.append(rs)
1118

    
1119
        if self.MODEL == "UV-82":
1120
            rs = RadioSetting("roger", "Roger Beep (TX)",
1121
                              RadioSettingValueBoolean(_settings.roger))
1122
            basic.append(rs)
1123
            rs = RadioSetting("rogerrx", "Roger Beep (RX)",
1124
                              RadioSettingValueList(
1125
                                  ROGERRX_LIST,
1126
                                  ROGERRX_LIST[_settings.rogerrx]))
1127
            basic.append(rs)
1128
        else:
1129
            rs = RadioSetting("roger", "Roger Beep",
1130
                              RadioSettingValueBoolean(_settings.roger))
1131
            basic.append(rs)
1132

    
1133
        rs = RadioSetting("ste", "Squelch Tail Eliminate (HT to HT)",
1134
                          RadioSettingValueBoolean(_settings.ste))
1135
        advanced.append(rs)
1136

    
1137
        rs = RadioSetting("rpste", "Squelch Tail Eliminate (repeater)",
1138
                          RadioSettingValueList(
1139
                              RPSTE_LIST, RPSTE_LIST[_settings.rpste]))
1140
        advanced.append(rs)
1141

    
1142
        rs = RadioSetting("rptrl", "STE Repeater Delay",
1143
                          RadioSettingValueList(
1144
                              STEDELAY_LIST, STEDELAY_LIST[_settings.rptrl]))
1145
        advanced.append(rs)
1146

    
1147
        if self.MODEL != "UV-6":
1148
            rs = RadioSetting("reset", "RESET Menu",
1149
                              RadioSettingValueBoolean(_settings.reset))
1150
            advanced.append(rs)
1151

    
1152
            rs = RadioSetting("menu", "All Menus",
1153
                              RadioSettingValueBoolean(_settings.menu))
1154
            advanced.append(rs)
1155

    
1156
        if self.MODEL == "F-11":
1157
            # this is an F-11 only feature
1158
            rs = RadioSetting("vfomrlock", "VFO/MR Button",
1159
                              RadioSettingValueBoolean(_settings.vfomrlock))
1160
            advanced.append(rs)
1161

    
1162
        if self.MODEL == "UV-82":
1163
            # this is a UV-82C only feature
1164
            rs = RadioSetting("vfomrlock", "VFO/MR Switching (UV-82C only)",
1165
                              RadioSettingValueBoolean(_settings.vfomrlock))
1166
            advanced.append(rs)
1167

    
1168
        if self.MODEL == "UV-82HP":
1169
            # this is a UV-82HP only feature
1170
            rs = RadioSetting("vfomrlock", "VFO/MR Switching",
1171
                              RadioSettingValueBoolean(_settings.vfomrlock))
1172
            advanced.append(rs)
1173

    
1174
        if self.MODEL == "UV-82":
1175
            # this is an UV-82C only feature
1176
            rs = RadioSetting("singleptt", "Single PTT (UV-82C only)",
1177
                              RadioSettingValueBoolean(_settings.singleptt))
1178
            advanced.append(rs)
1179

    
1180
        if self.MODEL == "UV-82HP":
1181
            # this is an UV-82HP only feature
1182
            rs = RadioSetting("singleptt", "Single PTT",
1183
                              RadioSettingValueBoolean(_settings.singleptt))
1184
            advanced.append(rs)
1185

    
1186
        if self.MODEL == "UV-82HP":
1187
            # this is an UV-82HP only feature
1188
            rs = RadioSetting("tdrch", "Tone Burst Frequency",
1189
                              RadioSettingValueList(
1190
                                  RTONE_LIST, RTONE_LIST[_settings.tdrch]))
1191
            advanced.append(rs)
1192

    
1193
        if len(self._mmap.get_packed()) == 0x1808:
1194
            # Old image, without aux block
1195
            return group
1196

    
1197
        other = RadioSettingGroup("other", "Other Settings")
1198
        group.append(other)
1199

    
1200
        def _filter(name):
1201
            filtered = ""
1202
            for char in str(name):
1203
                if char in chirp_common.CHARSET_ASCII:
1204
                    filtered += char
1205
                else:
1206
                    filtered += " "
1207
            return filtered
1208

    
1209
        _msg = self._memobj.firmware_msg
1210
        val = RadioSettingValueString(0, 7, _filter(_msg.line1))
1211
        val.set_mutable(False)
1212
        rs = RadioSetting("firmware_msg.line1", "Firmware Message 1", val)
1213
        other.append(rs)
1214

    
1215
        val = RadioSettingValueString(0, 7, _filter(_msg.line2))
1216
        val.set_mutable(False)
1217
        rs = RadioSetting("firmware_msg.line2", "Firmware Message 2", val)
1218
        other.append(rs)
1219

    
1220
        if self.MODEL != "UV-6":
1221
            _msg = self._memobj.sixpoweron_msg
1222
            rs = RadioSetting("sixpoweron_msg.line1", "6+Power-On Message 1",
1223
                              RadioSettingValueString(
1224
                                  0, 7, _filter(_msg.line1)))
1225
            other.append(rs)
1226
            rs = RadioSetting("sixpoweron_msg.line2", "6+Power-On Message 2",
1227
                              RadioSettingValueString(
1228
                                  0, 7, _filter(_msg.line2)))
1229
            other.append(rs)
1230

    
1231
            _msg = self._memobj.poweron_msg
1232
            rs = RadioSetting("poweron_msg.line1", "Power-On Message 1",
1233
                              RadioSettingValueString(
1234
                                  0, 7, _filter(_msg.line1)))
1235
            other.append(rs)
1236
            rs = RadioSetting("poweron_msg.line2", "Power-On Message 2",
1237
                              RadioSettingValueString(
1238
                                  0, 7, _filter(_msg.line2)))
1239
            other.append(rs)
1240

    
1241
            rs = RadioSetting("ponmsg", "Power-On Message",
1242
                              RadioSettingValueList(
1243
                                  PONMSG_LIST, PONMSG_LIST[_settings.ponmsg]))
1244
            other.append(rs)
1245

    
1246
            if self._is_orig():
1247
                limit = "limits_old"
1248
            else:
1249
                limit = "limits_new"
1250

    
1251
            vhf_limit = getattr(self._memobj, limit).vhf
1252
            rs = RadioSetting("%s.vhf.lower" % limit, "VHF Lower Limit (MHz)",
1253
                              RadioSettingValueInteger(1, 1000,
1254
                                                       vhf_limit.lower))
1255
            other.append(rs)
1256

    
1257
            rs = RadioSetting("%s.vhf.upper" % limit, "VHF Upper Limit (MHz)",
1258
                              RadioSettingValueInteger(1, 1000,
1259
                                                       vhf_limit.upper))
1260
            other.append(rs)
1261

    
1262
            rs = RadioSetting("%s.vhf.enable" % limit, "VHF TX Enabled",
1263
                              RadioSettingValueBoolean(vhf_limit.enable))
1264
            other.append(rs)
1265

    
1266
            uhf_limit = getattr(self._memobj, limit).uhf
1267
            rs = RadioSetting("%s.uhf.lower" % limit, "UHF Lower Limit (MHz)",
1268
                              RadioSettingValueInteger(1, 1000,
1269
                                                       uhf_limit.lower))
1270
            other.append(rs)
1271
            rs = RadioSetting("%s.uhf.upper" % limit, "UHF Upper Limit (MHz)",
1272
                              RadioSettingValueInteger(1, 1000,
1273
                                                       uhf_limit.upper))
1274
            other.append(rs)
1275
            rs = RadioSetting("%s.uhf.enable" % limit, "UHF TX Enabled",
1276
                              RadioSettingValueBoolean(uhf_limit.enable))
1277
            other.append(rs)
1278

    
1279
        if self.MODEL != "UV-6":
1280
            workmode = RadioSettingGroup("workmode", "Work Mode Settings")
1281
            group.append(workmode)
1282

    
1283
            rs = RadioSetting("displayab", "Display",
1284
                              RadioSettingValueList(
1285
                                  AB_LIST, AB_LIST[_settings.displayab]))
1286
            workmode.append(rs)
1287

    
1288
            rs = RadioSetting("workmode", "VFO/MR Mode",
1289
                              RadioSettingValueList(
1290
                                  WORKMODE_LIST,
1291
                                  WORKMODE_LIST[_settings.workmode]))
1292
            workmode.append(rs)
1293

    
1294
            rs = RadioSetting("keylock", "Keypad Lock",
1295
                              RadioSettingValueBoolean(_settings.keylock))
1296
            workmode.append(rs)
1297

    
1298
            rs = RadioSetting("wmchannel.mrcha", "MR A Channel",
1299
                              RadioSettingValueInteger(0, 127,
1300
                                                       _wmchannel.mrcha))
1301
            workmode.append(rs)
1302

    
1303
            rs = RadioSetting("wmchannel.mrchb", "MR B Channel",
1304
                              RadioSettingValueInteger(0, 127,
1305
                                                       _wmchannel.mrchb))
1306
            workmode.append(rs)
1307

    
1308
            def convert_bytes_to_freq(bytes):
1309
                real_freq = 0
1310
                for byte in bytes:
1311
                    real_freq = (real_freq * 10) + byte
1312
                return chirp_common.format_freq(real_freq * 10)
1313

    
1314
            def my_validate(value):
1315
                value = chirp_common.parse_freq(value)
1316
                if 17400000 <= value and value < 40000000:
1317
                    msg = ("Can't be between 174.00000-400.00000")
1318
                    raise InvalidValueError(msg)
1319
                return chirp_common.format_freq(value)
1320

    
1321
            def apply_freq(setting, obj):
1322
                value = chirp_common.parse_freq(str(setting.value)) / 10
1323
                obj.band = value >= 40000000
1324
                for i in range(7, -1, -1):
1325
                    obj.freq[i] = value % 10
1326
                    value /= 10
1327

    
1328
            val1a = RadioSettingValueString(0, 10,
1329
                                            convert_bytes_to_freq(_vfoa.freq))
1330
            val1a.set_validate_callback(my_validate)
1331
            rs = RadioSetting("vfoa.freq", "VFO A Frequency", val1a)
1332
            rs.set_apply_callback(apply_freq, _vfoa)
1333
            workmode.append(rs)
1334

    
1335
            val1b = RadioSettingValueString(0, 10,
1336
                                            convert_bytes_to_freq(_vfob.freq))
1337
            val1b.set_validate_callback(my_validate)
1338
            rs = RadioSetting("vfob.freq", "VFO B Frequency", val1b)
1339
            rs.set_apply_callback(apply_freq, _vfob)
1340
            workmode.append(rs)
1341

    
1342
            rs = RadioSetting("vfoa.sftd", "VFO A Shift",
1343
                              RadioSettingValueList(
1344
                                  SHIFTD_LIST, SHIFTD_LIST[_vfoa.sftd]))
1345
            workmode.append(rs)
1346

    
1347
            rs = RadioSetting("vfob.sftd", "VFO B Shift",
1348
                              RadioSettingValueList(
1349
                                  SHIFTD_LIST, SHIFTD_LIST[_vfob.sftd]))
1350
            workmode.append(rs)
1351

    
1352
            def convert_bytes_to_offset(bytes):
1353
                real_offset = 0
1354
                for byte in bytes:
1355
                    real_offset = (real_offset * 10) + byte
1356
                return chirp_common.format_freq(real_offset * 10000)
1357

    
1358
            def apply_offset(setting, obj):
1359
                value = chirp_common.parse_freq(str(setting.value)) / 10000
1360
                for i in range(3, -1, -1):
1361
                    obj.offset[i] = value % 10
1362
                    value /= 10
1363

    
1364
            val1a = RadioSettingValueString(
1365
                0, 10, convert_bytes_to_offset(_vfoa.offset))
1366
            rs = RadioSetting("vfoa.offset",
1367
                              "VFO A Offset (0.00-69.95)", val1a)
1368
            rs.set_apply_callback(apply_offset, _vfoa)
1369
            workmode.append(rs)
1370

    
1371
            val1b = RadioSettingValueString(
1372
                0, 10, convert_bytes_to_offset(_vfob.offset))
1373
            rs = RadioSetting("vfob.offset",
1374
                              "VFO B Offset (0.00-69.95)", val1b)
1375
            rs.set_apply_callback(apply_offset, _vfob)
1376
            workmode.append(rs)
1377

    
1378
            if self.MODEL in ("KT-980HP", "BF-F8HP", "UV-82HP"):
1379
                rs = RadioSetting("vfoa.txpower3", "VFO A Power",
1380
                                  RadioSettingValueList(
1381
                                      TXPOWER3_LIST,
1382
                                      TXPOWER3_LIST[_vfoa.txpower3]))
1383
                workmode.append(rs)
1384

    
1385
                rs = RadioSetting("vfob.txpower3", "VFO B Power",
1386
                                  RadioSettingValueList(
1387
                                      TXPOWER3_LIST,
1388
                                      TXPOWER3_LIST[_vfob.txpower3]))
1389
                workmode.append(rs)
1390
            else:
1391
                rs = RadioSetting("vfoa.txpower", "VFO A Power",
1392
                                  RadioSettingValueList(
1393
                                      TXPOWER_LIST,
1394
                                      TXPOWER_LIST[_vfoa.txpower]))
1395
                workmode.append(rs)
1396

    
1397
                rs = RadioSetting("vfob.txpower", "VFO B Power",
1398
                                  RadioSettingValueList(
1399
                                      TXPOWER_LIST,
1400
                                      TXPOWER_LIST[_vfob.txpower]))
1401
                workmode.append(rs)
1402

    
1403
            rs = RadioSetting("vfoa.widenarr", "VFO A Bandwidth",
1404
                              RadioSettingValueList(
1405
                                  BANDWIDTH_LIST,
1406
                                  BANDWIDTH_LIST[_vfoa.widenarr]))
1407
            workmode.append(rs)
1408

    
1409
            rs = RadioSetting("vfob.widenarr", "VFO B Bandwidth",
1410
                              RadioSettingValueList(
1411
                                  BANDWIDTH_LIST,
1412
                                  BANDWIDTH_LIST[_vfob.widenarr]))
1413
            workmode.append(rs)
1414

    
1415
            rs = RadioSetting("vfoa.scode", "VFO A PTT-ID",
1416
                              RadioSettingValueList(
1417
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfoa.scode]))
1418
            workmode.append(rs)
1419

    
1420
            rs = RadioSetting("vfob.scode", "VFO B PTT-ID",
1421
                              RadioSettingValueList(
1422
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfob.scode]))
1423
            workmode.append(rs)
1424

    
1425
            if not self._is_orig():
1426
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1427
                                  RadioSettingValueList(
1428
                                      STEP291_LIST, STEP291_LIST[_vfoa.step]))
1429
                workmode.append(rs)
1430
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1431
                                  RadioSettingValueList(
1432
                                      STEP291_LIST, STEP291_LIST[_vfob.step]))
1433
                workmode.append(rs)
1434
            else:
1435
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1436
                                  RadioSettingValueList(
1437
                                      STEP_LIST, STEP_LIST[_vfoa.step]))
1438
                workmode.append(rs)
1439
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1440
                                  RadioSettingValueList(
1441
                                      STEP_LIST, STEP_LIST[_vfob.step]))
1442
                workmode.append(rs)
1443

    
1444
        fm_preset = RadioSettingGroup("fm_preset", "FM Radio Preset")
1445
        group.append(fm_preset)
1446

    
1447
        if _fm_presets <= 108.0 * 10 - 650:
1448
            preset = _fm_presets / 10.0 + 65
1449
        elif _fm_presets >= 65.0 * 10 and _fm_presets <= 108.0 * 10:
1450
            preset = _fm_presets / 10.0
1451
        else:
1452
            preset = 76.0
1453
        rs = RadioSetting("fm_presets", "FM Preset(MHz)",
1454
                          RadioSettingValueFloat(65, 108.0, preset, 0.1, 1))
1455
        fm_preset.append(rs)
1456

    
1457
        dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
1458
        group.append(dtmf)
1459
        dtmfchars = "0123456789 *#ABCD"
1460

    
1461
        for i in range(0, 15):
1462
            _codeobj = self._memobj.pttid[i].code
1463
            _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1464
            val = RadioSettingValueString(0, 5, _code, False)
1465
            val.set_charset(dtmfchars)
1466
            rs = RadioSetting("pttid/%i.code" % i,
1467
                              "PTT ID Code %i" % (i + 1), val)
1468

    
1469
            def apply_code(setting, obj):
1470
                code = []
1471
                for j in range(0, 5):
1472
                    try:
1473
                        code.append(dtmfchars.index(str(setting.value)[j]))
1474
                    except IndexError:
1475
                        code.append(0xFF)
1476
                obj.code = code
1477
            rs.set_apply_callback(apply_code, self._memobj.pttid[i])
1478
            dtmf.append(rs)
1479

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

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

    
1497
        rs = RadioSetting("ani.aniid", "ANI ID",
1498
                          RadioSettingValueList(PTTID_LIST,
1499
                                                PTTID_LIST[_ani.aniid]))
1500
        dtmf.append(rs)
1501

    
1502
        _codeobj = self._memobj.ani.alarmcode
1503
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1504
        val = RadioSettingValueString(0, 3, _code, False)
1505
        val.set_charset(dtmfchars)
1506
        rs = RadioSetting("ani.alarmcode", "Alarm Code", val)
1507

    
1508
        def apply_code(setting, obj):
1509
            alarmcode = []
1510
            for j in range(0, 3):
1511
                try:
1512
                    alarmcode.append(dtmfchars.index(str(setting.value)[j]))
1513
                except IndexError:
1514
                    alarmcode.append(0xFF)
1515
            obj.alarmcode = alarmcode
1516
        rs.set_apply_callback(apply_code, _ani)
1517
        dtmf.append(rs)
1518

    
1519
        rs = RadioSetting("dtmfst", "DTMF Sidetone",
1520
                          RadioSettingValueList(DTMFST_LIST,
1521
                                                DTMFST_LIST[_settings.dtmfst]))
1522
        dtmf.append(rs)
1523

    
1524
        if _ani.dtmfon > 0xC3:
1525
            val = 0x00
1526
        else:
1527
            val = _ani.dtmfon
1528
        rs = RadioSetting("ani.dtmfon", "DTMF Speed (on)",
1529
                          RadioSettingValueList(DTMFSPEED_LIST,
1530
                                                DTMFSPEED_LIST[val]))
1531
        dtmf.append(rs)
1532

    
1533
        if _ani.dtmfoff > 0xC3:
1534
            val = 0x00
1535
        else:
1536
            val = _ani.dtmfoff
1537
        rs = RadioSetting("ani.dtmfoff", "DTMF Speed (off)",
1538
                          RadioSettingValueList(DTMFSPEED_LIST,
1539
                                                DTMFSPEED_LIST[val]))
1540
        dtmf.append(rs)
1541

    
1542
        rs = RadioSetting("pttlt", "PTT ID Delay",
1543
                          RadioSettingValueInteger(0, 50, _settings.pttlt))
1544
        dtmf.append(rs)
1545

    
1546
        if not self._is_orig():
1547
            service = RadioSettingGroup("service", "Service Settings")
1548
            group.append(service)
1549

    
1550
            for band in ["vhf", "uhf"]:
1551
                for index in range(0, 10):
1552
                    key = "squelch_new.%s.sql%i" % (band, index)
1553
                    if band == "vhf":
1554
                        _obj = self._memobj.squelch_new.vhf
1555
                    elif band == "uhf":
1556
                        _obj = self._memobj.squelch_new.uhf
1557
                    name = "%s Squelch %i" % (band.upper(), index)
1558
                    rs = RadioSetting(key, name,
1559
                                      RadioSettingValueInteger(
1560
                                          0, 123,
1561
                                          getattr(_obj, "sql%i" % (index))))
1562
                    service.append(rs)
1563

    
1564
        return group
1565

    
1566
    def get_settings(self):
1567
        try:
1568
            return self._get_settings()
1569
        except:
1570
            import traceback
1571
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1572
            return None
1573

    
1574
    def set_settings(self, settings):
1575
        _settings = self._memobj.settings
1576
        for element in settings:
1577
            if not isinstance(element, RadioSetting):
1578
                if element.get_name() == "fm_preset":
1579
                    self._set_fm_preset(element)
1580
                else:
1581
                    self.set_settings(element)
1582
                    continue
1583
            else:
1584
                try:
1585
                    name = element.get_name()
1586
                    if "." in name:
1587
                        bits = name.split(".")
1588
                        obj = self._memobj
1589
                        for bit in bits[:-1]:
1590
                            if "/" in bit:
1591
                                bit, index = bit.split("/", 1)
1592
                                index = int(index)
1593
                                obj = getattr(obj, bit)[index]
1594
                            else:
1595
                                obj = getattr(obj, bit)
1596
                        setting = bits[-1]
1597
                    else:
1598
                        obj = _settings
1599
                        setting = element.get_name()
1600

    
1601
                    if element.has_apply_callback():
1602
                        LOG.debug("Using apply callback")
1603
                        element.run_apply_callback()
1604
                    elif element.value.get_mutable():
1605
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1606
                        setattr(obj, setting, element.value)
1607
                except Exception, e:
1608
                    LOG.debug(element.get_name())
1609
                    raise
1610

    
1611
    def _set_fm_preset(self, settings):
1612
        for element in settings:
1613
            try:
1614
                val = element.value
1615
                if self._memobj.fm_presets <= 108.0 * 10 - 650:
1616
                    value = int(val.get_value() * 10 - 650)
1617
                else:
1618
                    value = int(val.get_value() * 10)
1619
                LOG.debug("Setting fm_presets = %s" % (value))
1620
                self._memobj.fm_presets = value
1621
            except Exception, e:
1622
                LOG.debug(element.get_name())
1623
                raise
1624

    
1625

    
1626
class UV5XAlias(chirp_common.Alias):
1627
    VENDOR = "Baofeng"
1628
    MODEL = "UV-5X"
1629

    
1630

    
1631
class RT5RAlias(chirp_common.Alias):
1632
    VENDOR = "Retevis"
1633
    MODEL = "RT-5R"
1634

    
1635

    
1636
class RT5RVAlias(chirp_common.Alias):
1637
    VENDOR = "Retevis"
1638
    MODEL = "RT-5RV"
1639

    
1640

    
1641
class RT5Alias(chirp_common.Alias):
1642
    VENDOR = "Retevis"
1643
    MODEL = "RT5"
1644

    
1645

    
1646
class RT5_TPAlias(chirp_common.Alias):
1647
    VENDOR = "Retevis"
1648
    MODEL = "RT5(tri-power)"
1649

    
1650

    
1651
@directory.register
1652
class BaofengUV5RGeneric(BaofengUV5R):
1653
    ALIASES = [UV5XAlias, RT5RAlias, RT5RVAlias, RT5Alias]
1654

    
1655

    
1656
@directory.register
1657
class BaofengF11Radio(BaofengUV5R):
1658
    VENDOR = "Baofeng"
1659
    MODEL = "F-11"
1660
    _basetype = BASETYPE_F11
1661
    _idents = [UV5R_MODEL_F11]
1662

    
1663
    def _is_orig(self):
1664
        # Override this for F11 to always return False
1665
        return False
1666

    
1667

    
1668
@directory.register
1669
class BaofengUV82Radio(BaofengUV5R):
1670
    MODEL = "UV-82"
1671
    _basetype = BASETYPE_UV82
1672
    _idents = [UV5R_MODEL_UV82]
1673
    _vhf_range = (130000000, 176000000)
1674
    _uhf_range = (400000000, 521000000)
1675

    
1676
    def _is_orig(self):
1677
        # Override this for UV82 to always return False
1678
        return False
1679

    
1680

    
1681
@directory.register
1682
class BaofengUV6Radio(BaofengUV5R):
1683

    
1684
    """Baofeng UV-6/UV-7"""
1685
    VENDOR = "Baofeng"
1686
    MODEL = "UV-6"
1687
    _basetype = BASETYPE_UV6
1688
    _idents = [UV5R_MODEL_UV6,
1689
               UV5R_MODEL_UV6_ORIG
1690
               ]
1691

    
1692
    def get_features(self):
1693
        rf = BaofengUV5R.get_features(self)
1694
        rf.memory_bounds = (1, 128)
1695
        return rf
1696

    
1697
    def _get_mem(self, number):
1698
        return self._memobj.memory[number - 1]
1699

    
1700
    def _get_nam(self, number):
1701
        return self._memobj.names[number - 1]
1702

    
1703
    def _set_mem(self, number):
1704
        return self._memobj.memory[number - 1]
1705

    
1706
    def _set_nam(self, number):
1707
        return self._memobj.names[number - 1]
1708

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

    
1713

    
1714
@directory.register
1715
class IntekKT980Radio(BaofengUV5R):
1716
    VENDOR = "Intek"
1717
    MODEL = "KT-980HP"
1718
    _basetype = BASETYPE_KT980HP
1719
    _idents = [UV5R_MODEL_291]
1720
    _vhf_range = (130000000, 180000000)
1721
    _uhf_range = (400000000, 521000000)
1722

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

    
1728
    def _is_orig(self):
1729
        # Override this for KT980HP to always return False
1730
        return False
1731

    
1732

    
1733
@directory.register
1734
class BaofengBFF8HPRadio(BaofengUV5R):
1735
    VENDOR = "Baofeng"
1736
    MODEL = "BF-F8HP"
1737
    ALIASES = [RT5_TPAlias, ]
1738
    _basetype = BASETYPE_F8HP
1739
    _idents = [UV5R_MODEL_291,
1740
               UV5R_MODEL_A58
1741
               ]
1742
    _vhf_range = (130000000, 180000000)
1743
    _uhf_range = (400000000, 521000000)
1744

    
1745
    def get_features(self):
1746
        rf = BaofengUV5R.get_features(self)
1747
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1748
        return rf
1749

    
1750
    def _is_orig(self):
1751
        # Override this for BFF8HP to always return False
1752
        return False
1753

    
1754

    
1755
@directory.register
1756
class BaofengUV82HPRadio(BaofengUV5R):
1757
    VENDOR = "Baofeng"
1758
    MODEL = "UV-82HP"
1759
    _basetype = BASETYPE_UV82HP
1760
    _idents = [UV5R_MODEL_UV82]
1761
    _vhf_range = (136000000, 175000000)
1762
    _uhf_range = (400000000, 521000000)
1763

    
1764
    def get_features(self):
1765
        rf = BaofengUV5R.get_features(self)
1766
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1767
        return rf
1768

    
1769
    def _is_orig(self):
1770
        # Override this for UV82HP to always return False
1771
        return False
(3-3/9)