Project

General

Profile

New Model #4441 » uv5r(custom_to_get_image).py

for grabbing an image only - Jim Unroe, 01/24/2017 03:39 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
UV5R_MODEL_CT3 = "\x50\x5B\x5F\x20\x13\x05\x10"
376

    
377

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

    
381

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

    
385

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

    
390

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

    
398

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

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

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

    
414
    serial.write("\x02")
415

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

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

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

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

    
457
    return ident
458

    
459

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

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

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

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

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

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

    
490
    return chunk
491

    
492

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

    
504

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

    
519

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

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

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

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

    
543

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

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

    
553

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

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

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

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

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

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

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

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

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

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

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

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

    
608

    
609
class BaofengUV5R(chirp_common.CloneModeRadio,
610
                  chirp_common.ExperimentalRadio):
611

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
848
        return mem
849

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

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

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

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

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

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

    
881
        _mem.rxfreq = mem.freq / 10
882

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

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

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

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

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

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

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

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

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

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

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

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

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

    
994
        group = RadioSettings(basic, advanced)
995

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1565
        return group
1566

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

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

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

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

    
1626

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

    
1631

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

    
1636

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

    
1641

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

    
1646

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

    
1651

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

    
1656

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

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

    
1668

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

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

    
1681

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

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

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

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

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

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

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

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

    
1714

    
1715
@directory.register
1716
class IntekKT980Radio(BaofengUV5R):
1717
    VENDOR = "Intek"
1718
    MODEL = "KT-980HP"
1719
    _basetype = BASETYPE_KT980HP
1720
    _idents = [UV5R_MODEL_291]
1721
    _vhf_range = (130000000, 180000000)
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 KT980HP to always return False
1731
        return False
1732

    
1733

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

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

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

    
1755

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

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

    
1770
    def _is_orig(self):
1771
        # Override this for UV82HP to always return False
1772
        return False
1773

    
1774

    
1775
@directory.register
1776
class BaofengUV82PlusRadio(BaofengUV5R):
1777
    MODEL = "UV-82 Plus"
1778
    _basetype = BASETYPE_UV82
1779
    _idents = [UV5R_MODEL_CT3]
1780
    _vhf_range = (130000000, 180000000)
1781
    _uhf_range = (400000000, 521000000)
1782

    
1783
    def _is_orig(self):
1784
        # Override this for UV82Plus to always return False
1785
        return False
1786

    
(1-1/2)