Project

General

Profile

Bug #1707 » uv5r.py

test driver for UV-6 with 12 byte ident reply - Jim Unroe, 08/08/2016 08:09 PM

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

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

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

    
29
LOG = logging.getLogger(__name__)
30

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

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

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

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

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

    
152
#seekto 0x0F10;
153
struct {
154
  u8 freq[8];
155
  u8 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", "UV6S83"]
288
BASETYPE_KT980HP = ["BFP3V3 B"]
289
BASETYPE_F8HP = ["BFP3V3 F", "N5R-3", "N5R3", "F5R3", "BFT"]
290
BASETYPE_UV82HP = ["N82-3", "N823"]
291
BASETYPE_LIST = BASETYPE_UV5R + BASETYPE_F11 + BASETYPE_UV82 + \
292
                BASETYPE_BJ55 + BASETYPE_UV6 + BASETYPE_KT980HP + \
293
                BASETYPE_F8HP + BASETYPE_UV82HP
294

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

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

    
360

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

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

    
376

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

    
380

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

    
384

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

    
389

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

    
397

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

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

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

    
413
    serial.write("\x02")
414
    ident = serial.read(8)
415

    
416
    LOG.info("Ident: %s" % util.hexprint(ident))
417

    
418
    if not ident.endswith("\xdd") and radio.MODEL == "UV-6":
419
        # chew up the extra 4 bytes
420
        extra = serial.read(4)
421
        LOG.info("Extra: %s" % util.hexprint(extra))
422

    
423
    serial.write("\x06")
424
    ack = serial.read(1)
425
    if ack != "\x06":
426
        raise errors.RadioError("Radio refused clone")
427

    
428
    return ident
429

    
430

    
431
def _read_block(radio, start, size, first_command=False):
432
    msg = struct.pack(">BHB", ord("S"), start, size)
433
    radio.pipe.write(msg)
434

    
435
    if first_command is False:
436
        ack = radio.pipe.read(1)
437
        if ack != "\x06":
438
            raise errors.RadioError(
439
                "Radio refused to send second block 0x%04x" % start)
440

    
441
    answer = radio.pipe.read(4)
442
    if len(answer) != 4:
443
        raise errors.RadioError("Radio refused to send block 0x%04x" % start)
444

    
445
    cmd, addr, length = struct.unpack(">BHB", answer)
446
    if cmd != ord("X") or addr != start or length != size:
447
        LOG.error("Invalid answer for block 0x%04x:" % start)
448
        LOG.debug("CMD: %s  ADDR: %04x  SIZE: %02x" % (cmd, addr, length))
449
        raise errors.RadioError("Unknown response from radio")
450

    
451
    chunk = radio.pipe.read(0x40)
452
    if not chunk:
453
        raise errors.RadioError("Radio did not send block 0x%04x" % start)
454
    elif len(chunk) != size:
455
        LOG.error("Chunk length was 0x%04i" % len(chunk))
456
        raise errors.RadioError("Radio sent incomplete block 0x%04x" % start)
457

    
458
    radio.pipe.write("\x06")
459
    time.sleep(0.05)
460

    
461
    return chunk
462

    
463

    
464
def _get_radio_firmware_version(radio):
465
    if radio.MODEL == "BJ-UV55":
466
        block = _read_block(radio, 0x1FF0, 0x40, True)
467
        version = block[0:6]
468
    else:
469
        block1 = _read_block(radio, 0x1EC0, 0x40, True)
470
        block2 = _read_block(radio, 0x1F00, 0x40, False)
471
        block = block1 + block2
472
        version = block[48:62]
473
    return version
474

    
475

    
476
def _ident_radio(radio):
477
    for magic in radio._idents:
478
        error = None
479
        try:
480
            data = _do_ident(radio, magic)
481
            return data
482
        except errors.RadioError, e:
483
            LOG.error(e)
484
            error = e
485
            time.sleep(2)
486
    if error:
487
        raise error
488
    raise errors.RadioError("Radio did not respond")
489

    
490

    
491
def _do_download(radio):
492
    data = _ident_radio(radio)
493

    
494
    radio_version = _get_radio_firmware_version(radio)
495
    LOG.info("Radio Version is %s" % repr(radio_version))
496

    
497
    if not any(type in radio_version for type in radio._basetype):
498
        raise errors.RadioError("Incorrect 'Model' selected.")
499

    
500
    # Main block
501
    LOG.debug("downloading main block...")
502
    for i in range(0, 0x1800, 0x40):
503
        data += _read_block(radio, i, 0x40, False)
504
        _do_status(radio, i)
505
    _do_status(radio, radio.get_memsize())
506
    LOG.debug("done.")
507
    LOG.debug("downloading aux block...")
508
    # Auxiliary block starts at 0x1ECO (?)
509
    for i in range(0x1EC0, 0x2000, 0x40):
510
        data += _read_block(radio, i, 0x40, False)
511
    LOG.debug("done.")
512
    return memmap.MemoryMap(data)
513

    
514

    
515
def _send_block(radio, addr, data):
516
    msg = struct.pack(">BHB", ord("X"), addr, len(data))
517
    radio.pipe.write(msg + data)
518
    time.sleep(0.05)
519

    
520
    ack = radio.pipe.read(1)
521
    if ack != "\x06":
522
        raise errors.RadioError("Radio refused to accept block 0x%04x" % addr)
523

    
524

    
525
def _do_upload(radio):
526
    ident = _ident_radio(radio)
527
    radio_upper_band = ident[3:4]
528
    image_upper_band = _upper_band_from_image(radio)
529

    
530
    if image_upper_band == vhf_220_radio or radio_upper_band == vhf_220_radio:
531
        if image_upper_band != radio_upper_band:
532
            raise errors.RadioError("Image not supported by radio")
533

    
534
    image_version = _firmware_version_from_image(radio)
535
    radio_version = _get_radio_firmware_version(radio)
536
    LOG.info("Image Version is %s" % repr(image_version))
537
    LOG.info("Radio Version is %s" % repr(radio_version))
538

    
539
    if image_version != radio_version:
540
        msg = ("The upload was stopped because the firmware "
541
               "version of the image (%s) does not match that "
542
               "of the radio (%s).")
543
        raise errors.RadioError(msg % (image_version, radio_version))
544

    
545
    # Main block
546
    for i in range(0x08, 0x1808, 0x10):
547
        _send_block(radio, i - 0x08, radio.get_mmap()[i:i + 0x10])
548
        _do_status(radio, i)
549
    _do_status(radio, radio.get_memsize())
550

    
551
    if len(radio.get_mmap().get_packed()) == 0x1808:
552
        LOG.info("Old image, not writing aux block")
553
        return  # Old image, no aux block
554

    
555
    if image_version != radio_version:
556
        msg = ("Upload finished, but the 'Other Settings' "
557
               "could not be sent because the firmware "
558
               "version of the image (%s) does not match "
559
               "that of the radio (%s).")
560
        raise errors.RadioError(msg % (image_version, radio_version))
561

    
562
    # Auxiliary block at radio address 0x1EC0, our offset 0x1808
563
    for i in range(0x1EC0, 0x2000, 0x10):
564
        addr = 0x1808 + (i - 0x1EC0)
565
        _send_block(radio, i, radio.get_mmap()[addr:addr + 0x10])
566

    
567
UV5R_POWER_LEVELS = [chirp_common.PowerLevel("High", watts=4.00),
568
                     chirp_common.PowerLevel("Low",  watts=1.00)]
569

    
570
UV5R_POWER_LEVELS3 = [chirp_common.PowerLevel("High", watts=8.00),
571
                      chirp_common.PowerLevel("Med",  watts=4.00),
572
                      chirp_common.PowerLevel("Low",  watts=1.00)]
573

    
574
UV5R_DTCS = sorted(chirp_common.DTCS_CODES + [645])
575

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

    
579

    
580
class BaofengUV5R(chirp_common.CloneModeRadio,
581
                  chirp_common.ExperimentalRadio):
582
    """Baofeng UV-5R"""
583
    VENDOR = "Baofeng"
584
    MODEL = "UV-5R"
585
    BAUD_RATE = 9600
586

    
587
    _memsize = 0x1808
588
    _basetype = BASETYPE_UV5R
589
    _idents = [UV5R_MODEL_291,
590
               UV5R_MODEL_ORIG
591
               ]
592
    _vhf_range = (136000000, 174000000)
593
    _220_range = (220000000, 260000000)
594
    _uhf_range = (400000000, 520000000)
595
    _mem_params = (0x1828  # poweron_msg offset
596
                   )
597
    # offset of fw version in image file
598
    _fw_ver_file_start = 0x1838
599
    _fw_ver_file_stop = 0x1846
600

    
601
    @classmethod
602
    def get_prompts(cls):
603
        rp = chirp_common.RadioPrompts()
604
        rp.experimental = \
605
            ('Due to the fact that the manufacturer continues to '
606
             'release new versions of the firmware with obscure and '
607
             'hard-to-track changes, this driver may not work with '
608
             'your device. Thus far and to the best knowledge of the '
609
             'author, no UV-5R radios have been harmed by using CHIRP. '
610
             'However, proceed at your own risk!')
611
        rp.pre_download = _(dedent("""\
612
            1. Turn radio off.
613
            2. Connect cable to mic/spkr connector.
614
            3. Make sure connector is firmly connected.
615
            4. Turn radio on (volume may need to be set at 100%).
616
            5. Ensure that the radio is tuned to channel with no activity.
617
            6. Click OK to download image from device."""))
618
        rp.pre_upload = _(dedent("""\
619
            1. Turn radio off.
620
            2. Connect cable to mic/spkr connector.
621
            3. Make sure connector is firmly connected.
622
            4. Turn radio on (volume may need to be set at 100%).
623
            5. Ensure that the radio is tuned to channel with no activity.
624
            6. Click OK to upload image to device."""))
625
        return rp
626

    
627
    def get_features(self):
628
        rf = chirp_common.RadioFeatures()
629
        rf.has_settings = True
630
        rf.has_bank = False
631
        rf.has_cross = True
632
        rf.has_rx_dtcs = True
633
        rf.has_tuning_step = False
634
        rf.can_odd_split = True
635
        rf.valid_name_length = 7
636
        rf.valid_characters = UV5R_CHARSET
637
        rf.valid_skips = ["", "S"]
638
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
639
        rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone",
640
                                "->Tone", "->DTCS", "DTCS->", "DTCS->DTCS"]
641
        rf.valid_power_levels = UV5R_POWER_LEVELS
642
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
643
        rf.valid_modes = ["FM", "NFM"]
644

    
645
        normal_bands = [self._vhf_range, self._uhf_range]
646
        rax_bands = [self._vhf_range, self._220_range]
647

    
648
        if self._mmap is None:
649
            rf.valid_bands = [normal_bands[0], rax_bands[1], normal_bands[1]]
650
        elif not self._is_orig() and self._my_upper_band() == vhf_220_radio:
651
            rf.valid_bands = rax_bands
652
        else:
653
            rf.valid_bands = normal_bands
654
        rf.memory_bounds = (0, 127)
655
        return rf
656

    
657
    @classmethod
658
    def match_model(cls, filedata, filename):
659
        match_size = False
660
        match_model = False
661
        if len(filedata) in [0x1808, 0x1948]:
662
            match_size = True
663
        fwdata = _firmware_version_from_data(filedata,
664
                                             cls._fw_ver_file_start,
665
                                             cls._fw_ver_file_stop)
666
        if any(type in fwdata for type in cls._basetype):
667
            match_model = True
668
        if match_size and match_model:
669
            return True
670
        else:
671
            return False
672

    
673
    def process_mmap(self):
674
        self._memobj = bitwise.parse(MEM_FORMAT % self._mem_params, self._mmap)
675

    
676
    def sync_in(self):
677
        try:
678
            self._mmap = _do_download(self)
679
        except errors.RadioError:
680
            raise
681
        except Exception, e:
682
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
683
        self.process_mmap()
684

    
685
    def sync_out(self):
686
        try:
687
            _do_upload(self)
688
        except errors.RadioError:
689
            raise
690
        except Exception, e:
691
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
692

    
693
    def get_raw_memory(self, number):
694
        return repr(self._memobj.memory[number])
695

    
696
    def _is_txinh(self, _mem):
697
        raw_tx = ""
698
        for i in range(0, 4):
699
            raw_tx += _mem.txfreq[i].get_raw()
700
        return raw_tx == "\xFF\xFF\xFF\xFF"
701

    
702
    def _get_mem(self, number):
703
        return self._memobj.memory[number]
704

    
705
    def _get_nam(self, number):
706
        return self._memobj.names[number]
707

    
708
    def get_memory(self, number):
709
        _mem = self._get_mem(number)
710
        _nam = self._get_nam(number)
711

    
712
        mem = chirp_common.Memory()
713
        mem.number = number
714

    
715
        if _mem.get_raw()[0] == "\xff":
716
            mem.empty = True
717
            return mem
718

    
719
        mem.freq = int(_mem.rxfreq) * 10
720

    
721
        if self._is_txinh(_mem):
722
            mem.duplex = "off"
723
            mem.offset = 0
724
        elif int(_mem.rxfreq) == int(_mem.txfreq):
725
            mem.duplex = ""
726
            mem.offset = 0
727
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 70000000:
728
            mem.duplex = "split"
729
            mem.offset = int(_mem.txfreq) * 10
730
        else:
731
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
732
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
733

    
734
        for char in _nam.name:
735
            if str(char) == "\xFF":
736
                char = " "  # The UV-5R software may have 0xFF mid-name
737
            mem.name += str(char)
738
        mem.name = mem.name.rstrip()
739

    
740
        dtcs_pol = ["N", "N"]
741

    
742
        if _mem.txtone in [0, 0xFFFF]:
743
            txmode = ""
744
        elif _mem.txtone >= 0x0258:
745
            txmode = "Tone"
746
            mem.rtone = int(_mem.txtone) / 10.0
747
        elif _mem.txtone <= 0x0258:
748
            txmode = "DTCS"
749
            if _mem.txtone > 0x69:
750
                index = _mem.txtone - 0x6A
751
                dtcs_pol[0] = "R"
752
            else:
753
                index = _mem.txtone - 1
754
            mem.dtcs = UV5R_DTCS[index]
755
        else:
756
            LOG.warn("Bug: txtone is %04x" % _mem.txtone)
757

    
758
        if _mem.rxtone in [0, 0xFFFF]:
759
            rxmode = ""
760
        elif _mem.rxtone >= 0x0258:
761
            rxmode = "Tone"
762
            mem.ctone = int(_mem.rxtone) / 10.0
763
        elif _mem.rxtone <= 0x0258:
764
            rxmode = "DTCS"
765
            if _mem.rxtone >= 0x6A:
766
                index = _mem.rxtone - 0x6A
767
                dtcs_pol[1] = "R"
768
            else:
769
                index = _mem.rxtone - 1
770
            mem.rx_dtcs = UV5R_DTCS[index]
771
        else:
772
            LOG.warn("Bug: rxtone is %04x" % _mem.rxtone)
773

    
774
        if txmode == "Tone" and not rxmode:
775
            mem.tmode = "Tone"
776
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
777
            mem.tmode = "TSQL"
778
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
779
            mem.tmode = "DTCS"
780
        elif rxmode or txmode:
781
            mem.tmode = "Cross"
782
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
783

    
784
        mem.dtcs_polarity = "".join(dtcs_pol)
785

    
786
        if not _mem.scan:
787
            mem.skip = "S"
788

    
789
        if self.MODEL in ("KT-980HP", "BF-F8HP", "UV-82HP"):
790
            levels = UV5R_POWER_LEVELS3
791
        else:
792
            levels = UV5R_POWER_LEVELS
793
        try:
794
            mem.power = levels[_mem.lowpower]
795
        except IndexError:
796
            LOG.error("Radio reported invalid power level %s (in %s)" %
797
                      (_mem.power, levels))
798
            mem.power = levels[0]
799

    
800
        mem.mode = _mem.wide and "FM" or "NFM"
801

    
802
        mem.extra = RadioSettingGroup("Extra", "extra")
803

    
804
        rs = RadioSetting("bcl", "BCL",
805
                          RadioSettingValueBoolean(_mem.bcl))
806
        mem.extra.append(rs)
807

    
808
        rs = RadioSetting("pttid", "PTT ID",
809
                          RadioSettingValueList(PTTID_LIST,
810
                                                PTTID_LIST[_mem.pttid]))
811
        mem.extra.append(rs)
812

    
813
        rs = RadioSetting("scode", "PTT ID Code",
814
                          RadioSettingValueList(PTTIDCODE_LIST,
815
                                                PTTIDCODE_LIST[_mem.scode]))
816
        mem.extra.append(rs)
817

    
818
        return mem
819

    
820
    def _set_mem(self, number):
821
        return self._memobj.memory[number]
822

    
823
    def _set_nam(self, number):
824
        return self._memobj.names[number]
825

    
826
    def set_memory(self, mem):
827
        _mem = self._get_mem(mem.number)
828
        _nam = self._get_nam(mem.number)
829

    
830
        if mem.empty:
831
            _mem.set_raw("\xff" * 16)
832
            _nam.set_raw("\xff" * 16)
833
            return
834

    
835
        _mem.set_raw("\x00" * 16)
836

    
837
        _mem.rxfreq = mem.freq / 10
838

    
839
        if mem.duplex == "off":
840
            for i in range(0, 4):
841
                _mem.txfreq[i].set_raw("\xFF")
842
        elif mem.duplex == "split":
843
            _mem.txfreq = mem.offset / 10
844
        elif mem.duplex == "+":
845
            _mem.txfreq = (mem.freq + mem.offset) / 10
846
        elif mem.duplex == "-":
847
            _mem.txfreq = (mem.freq - mem.offset) / 10
848
        else:
849
            _mem.txfreq = mem.freq / 10
850

    
851
        _namelength = self.get_features().valid_name_length
852
        for i in range(_namelength):
853
            try:
854
                _nam.name[i] = mem.name[i]
855
            except IndexError:
856
                _nam.name[i] = "\xFF"
857

    
858
        rxmode = txmode = ""
859
        if mem.tmode == "Tone":
860
            _mem.txtone = int(mem.rtone * 10)
861
            _mem.rxtone = 0
862
        elif mem.tmode == "TSQL":
863
            _mem.txtone = int(mem.ctone * 10)
864
            _mem.rxtone = int(mem.ctone * 10)
865
        elif mem.tmode == "DTCS":
866
            rxmode = txmode = "DTCS"
867
            _mem.txtone = UV5R_DTCS.index(mem.dtcs) + 1
868
            _mem.rxtone = UV5R_DTCS.index(mem.dtcs) + 1
869
        elif mem.tmode == "Cross":
870
            txmode, rxmode = mem.cross_mode.split("->", 1)
871
            if txmode == "Tone":
872
                _mem.txtone = int(mem.rtone * 10)
873
            elif txmode == "DTCS":
874
                _mem.txtone = UV5R_DTCS.index(mem.dtcs) + 1
875
            else:
876
                _mem.txtone = 0
877
            if rxmode == "Tone":
878
                _mem.rxtone = int(mem.ctone * 10)
879
            elif rxmode == "DTCS":
880
                _mem.rxtone = UV5R_DTCS.index(mem.rx_dtcs) + 1
881
            else:
882
                _mem.rxtone = 0
883
        else:
884
            _mem.rxtone = 0
885
            _mem.txtone = 0
886

    
887
        if txmode == "DTCS" and mem.dtcs_polarity[0] == "R":
888
            _mem.txtone += 0x69
889
        if rxmode == "DTCS" and mem.dtcs_polarity[1] == "R":
890
            _mem.rxtone += 0x69
891

    
892
        _mem.scan = mem.skip != "S"
893
        _mem.wide = mem.mode == "FM"
894

    
895
        if mem.power:
896
            if self.MODEL in ("KT-980HP", "BF-F8HP", "UV-82HP"):
897
                levels = [str(l) for l in UV5R_POWER_LEVELS3]
898
                _mem.lowpower = levels.index(str(mem.power))
899
            else:
900
                _mem.lowpower = UV5R_POWER_LEVELS.index(mem.power)
901
        else:
902
            _mem.lowpower = 0
903

    
904
        for setting in mem.extra:
905
            setattr(_mem, setting.get_name(), setting.value)
906

    
907
    def _is_orig(self):
908
        version_tag = _firmware_version_from_image(self)
909
        LOG.debug("@_is_orig, version_tag: %s", util.hexprint(version_tag))
910
        try:
911
            if 'BFB' in version_tag:
912
                idx = version_tag.index("BFB") + 3
913
                version = int(version_tag[idx:idx + 3])
914
                return version < 291
915
            return False
916
        except:
917
            pass
918
        raise errors.RadioError("Unable to parse version string %s" %
919
                                version_tag)
920

    
921
    def _my_version(self):
922
        version_tag = _firmware_version_from_image(self)
923
        if 'BFB' in version_tag:
924
            idx = version_tag.index("BFB") + 3
925
            return int(version_tag[idx:idx + 3])
926

    
927
        raise Exception("Unrecognized firmware version string")
928

    
929
    def _my_upper_band(self):
930
        band_tag = _upper_band_from_image(self)
931
        return band_tag
932

    
933
    def _get_settings(self):
934
        _ani = self._memobj.ani
935
        _fm_presets = self._memobj.fm_presets
936
        _settings = self._memobj.settings
937
        _squelch = self._memobj.squelch_new
938
        _vfoa = self._memobj.vfoa
939
        _vfob = self._memobj.vfob
940
        _wmchannel = self._memobj.wmchannel
941
        basic = RadioSettingGroup("basic", "Basic Settings")
942
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
943

    
944
        group = RadioSettings(basic, advanced)
945

    
946
        rs = RadioSetting("squelch", "Carrier Squelch Level",
947
                          RadioSettingValueInteger(0, 9, _settings.squelch))
948
        basic.append(rs)
949

    
950
        rs = RadioSetting("save", "Battery Saver",
951
                          RadioSettingValueList(
952
                              SAVE_LIST, SAVE_LIST[_settings.save]))
953
        basic.append(rs)
954

    
955
        rs = RadioSetting("vox", "VOX Sensitivity",
956
                          RadioSettingValueList(
957
                              VOX_LIST, VOX_LIST[_settings.vox]))
958
        advanced.append(rs)
959

    
960
        if self.MODEL == "UV-6":
961
            # NOTE: The UV-6 calls this byte voxenable, but the UV-5R calls it
962
            # autolk. Since this is a minor difference, it will be referred to
963
            # by the wrong name for the UV-6.
964
            rs = RadioSetting("autolk", "Vox",
965
                              RadioSettingValueBoolean(_settings.autolk))
966
            advanced.append(rs)
967

    
968
        if self.MODEL != "UV-6":
969
            rs = RadioSetting("abr", "Backlight Timeout",
970
                              RadioSettingValueInteger(0, 24, _settings.abr))
971
            basic.append(rs)
972

    
973
        rs = RadioSetting("tdr", "Dual Watch",
974
                          RadioSettingValueBoolean(_settings.tdr))
975
        advanced.append(rs)
976

    
977
        if self.MODEL == "UV-6":
978
            rs = RadioSetting("tdrch", "Dual Watch Channel",
979
                              RadioSettingValueList(
980
                                  TDRCH_LIST, TDRCH_LIST[_settings.tdrch]))
981
            advanced.append(rs)
982

    
983
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
984
                              RadioSettingValueBoolean(_settings.tdrab))
985
            advanced.append(rs)
986
        else:
987
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
988
                              RadioSettingValueList(
989
                                  TDRAB_LIST, TDRAB_LIST[_settings.tdrab]))
990
            advanced.append(rs)
991

    
992
        if self.MODEL == "UV-6":
993
            rs = RadioSetting("alarm", "Alarm Sound",
994
                              RadioSettingValueBoolean(_settings.alarm))
995
            advanced.append(rs)
996

    
997
        if _settings.almod > 0x02:
998
            val = 0x01
999
        else:
1000
            val = _settings.almod
1001
        rs = RadioSetting("almod", "Alarm Mode",
1002
                          RadioSettingValueList(
1003
                              ALMOD_LIST, ALMOD_LIST[val]))
1004
        advanced.append(rs)
1005

    
1006
        rs = RadioSetting("beep", "Beep",
1007
                          RadioSettingValueBoolean(_settings.beep))
1008
        basic.append(rs)
1009

    
1010
        rs = RadioSetting("timeout", "Timeout Timer",
1011
                          RadioSettingValueList(
1012
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
1013
        basic.append(rs)
1014

    
1015
        if self._is_orig() and self._my_version() < 251:
1016
            rs = RadioSetting("voice", "Voice",
1017
                              RadioSettingValueBoolean(_settings.voice))
1018
            advanced.append(rs)
1019
        else:
1020
            rs = RadioSetting("voice", "Voice",
1021
                              RadioSettingValueList(
1022
                                  VOICE_LIST, VOICE_LIST[_settings.voice]))
1023
            advanced.append(rs)
1024

    
1025
        rs = RadioSetting("screv", "Scan Resume",
1026
                          RadioSettingValueList(
1027
                              RESUME_LIST, RESUME_LIST[_settings.screv]))
1028
        advanced.append(rs)
1029

    
1030
        if self.MODEL != "UV-6":
1031
            rs = RadioSetting("mdfa", "Display Mode (A)",
1032
                              RadioSettingValueList(
1033
                                  MODE_LIST, MODE_LIST[_settings.mdfa]))
1034
            basic.append(rs)
1035

    
1036
            rs = RadioSetting("mdfb", "Display Mode (B)",
1037
                              RadioSettingValueList(
1038
                                  MODE_LIST, MODE_LIST[_settings.mdfb]))
1039
            basic.append(rs)
1040

    
1041
        rs = RadioSetting("bcl", "Busy Channel Lockout",
1042
                          RadioSettingValueBoolean(_settings.bcl))
1043
        advanced.append(rs)
1044

    
1045
        if self.MODEL != "UV-6":
1046
            rs = RadioSetting("autolk", "Automatic Key Lock",
1047
                              RadioSettingValueBoolean(_settings.autolk))
1048
            advanced.append(rs)
1049

    
1050
        rs = RadioSetting("fmradio", "Broadcast FM Radio",
1051
                          RadioSettingValueBoolean(_settings.fmradio))
1052
        advanced.append(rs)
1053

    
1054
        if self.MODEL != "UV-6":
1055
            rs = RadioSetting("wtled", "Standby LED Color",
1056
                              RadioSettingValueList(
1057
                                  COLOR_LIST, COLOR_LIST[_settings.wtled]))
1058
            basic.append(rs)
1059

    
1060
            rs = RadioSetting("rxled", "RX LED Color",
1061
                              RadioSettingValueList(
1062
                                  COLOR_LIST, COLOR_LIST[_settings.rxled]))
1063
            basic.append(rs)
1064

    
1065
            rs = RadioSetting("txled", "TX LED Color",
1066
                              RadioSettingValueList(
1067
                                  COLOR_LIST, COLOR_LIST[_settings.txled]))
1068
            basic.append(rs)
1069

    
1070
        if self.MODEL == "UV-82":
1071
            rs = RadioSetting("roger", "Roger Beep (TX)",
1072
                              RadioSettingValueBoolean(_settings.roger))
1073
            basic.append(rs)
1074
            rs = RadioSetting("rogerrx", "Roger Beep (RX)",
1075
                              RadioSettingValueList(
1076
                                  ROGERRX_LIST,
1077
                                  ROGERRX_LIST[_settings.rogerrx]))
1078
            basic.append(rs)
1079
        else:
1080
            rs = RadioSetting("roger", "Roger Beep",
1081
                              RadioSettingValueBoolean(_settings.roger))
1082
            basic.append(rs)
1083

    
1084
        rs = RadioSetting("ste", "Squelch Tail Eliminate (HT to HT)",
1085
                          RadioSettingValueBoolean(_settings.ste))
1086
        advanced.append(rs)
1087

    
1088
        rs = RadioSetting("rpste", "Squelch Tail Eliminate (repeater)",
1089
                          RadioSettingValueList(
1090
                              RPSTE_LIST, RPSTE_LIST[_settings.rpste]))
1091
        advanced.append(rs)
1092

    
1093
        rs = RadioSetting("rptrl", "STE Repeater Delay",
1094
                          RadioSettingValueList(
1095
                              STEDELAY_LIST, STEDELAY_LIST[_settings.rptrl]))
1096
        advanced.append(rs)
1097

    
1098
        if self.MODEL != "UV-6":
1099
            rs = RadioSetting("reset", "RESET Menu",
1100
                              RadioSettingValueBoolean(_settings.reset))
1101
            advanced.append(rs)
1102

    
1103
            rs = RadioSetting("menu", "All Menus",
1104
                              RadioSettingValueBoolean(_settings.menu))
1105
            advanced.append(rs)
1106

    
1107
        if self.MODEL == "F-11":
1108
            # this is an F-11 only feature
1109
            rs = RadioSetting("vfomrlock", "VFO/MR Button",
1110
                              RadioSettingValueBoolean(_settings.vfomrlock))
1111
            advanced.append(rs)
1112

    
1113
        if self.MODEL == "UV-82":
1114
            # this is a UV-82C only feature
1115
            rs = RadioSetting("vfomrlock", "VFO/MR Switching (UV-82C only)",
1116
                              RadioSettingValueBoolean(_settings.vfomrlock))
1117
            advanced.append(rs)
1118

    
1119
        if self.MODEL == "UV-82HP":
1120
            # this is a UV-82HP only feature
1121
            rs = RadioSetting("vfomrlock", "VFO/MR Switching",
1122
                              RadioSettingValueBoolean(_settings.vfomrlock))
1123
            advanced.append(rs)
1124

    
1125
        if self.MODEL == "UV-82":
1126
            # this is an UV-82C only feature
1127
            rs = RadioSetting("singleptt", "Single PTT (UV-82C only)",
1128
                              RadioSettingValueBoolean(_settings.singleptt))
1129
            advanced.append(rs)
1130

    
1131
        if self.MODEL == "UV-82HP":
1132
            # this is an UV-82HP only feature
1133
            rs = RadioSetting("singleptt", "Single PTT",
1134
                              RadioSettingValueBoolean(_settings.singleptt))
1135
            advanced.append(rs)
1136

    
1137
        if self.MODEL == "UV-82HP":
1138
            # this is an UV-82HP only feature
1139
            rs = RadioSetting("tdrch", "Tone Burst Frequency",
1140
                              RadioSettingValueList(
1141
                                  RTONE_LIST, RTONE_LIST[_settings.tdrch]))
1142
            advanced.append(rs)
1143

    
1144
        if len(self._mmap.get_packed()) == 0x1808:
1145
            # Old image, without aux block
1146
            return group
1147

    
1148
        other = RadioSettingGroup("other", "Other Settings")
1149
        group.append(other)
1150

    
1151
        def _filter(name):
1152
            filtered = ""
1153
            for char in str(name):
1154
                if char in chirp_common.CHARSET_ASCII:
1155
                    filtered += char
1156
                else:
1157
                    filtered += " "
1158
            return filtered
1159

    
1160
        _msg = self._memobj.firmware_msg
1161
        val = RadioSettingValueString(0, 7, _filter(_msg.line1))
1162
        val.set_mutable(False)
1163
        rs = RadioSetting("firmware_msg.line1", "Firmware Message 1", val)
1164
        other.append(rs)
1165

    
1166
        val = RadioSettingValueString(0, 7, _filter(_msg.line2))
1167
        val.set_mutable(False)
1168
        rs = RadioSetting("firmware_msg.line2", "Firmware Message 2", val)
1169
        other.append(rs)
1170

    
1171
        if self.MODEL != "UV-6":
1172
            _msg = self._memobj.sixpoweron_msg
1173
            rs = RadioSetting("sixpoweron_msg.line1", "6+Power-On Message 1",
1174
                              RadioSettingValueString(
1175
                                  0, 7, _filter(_msg.line1)))
1176
            other.append(rs)
1177
            rs = RadioSetting("sixpoweron_msg.line2", "6+Power-On Message 2",
1178
                              RadioSettingValueString(
1179
                                  0, 7, _filter(_msg.line2)))
1180
            other.append(rs)
1181

    
1182
            _msg = self._memobj.poweron_msg
1183
            rs = RadioSetting("poweron_msg.line1", "Power-On Message 1",
1184
                              RadioSettingValueString(
1185
                                  0, 7, _filter(_msg.line1)))
1186
            other.append(rs)
1187
            rs = RadioSetting("poweron_msg.line2", "Power-On Message 2",
1188
                              RadioSettingValueString(
1189
                                  0, 7, _filter(_msg.line2)))
1190
            other.append(rs)
1191

    
1192
            rs = RadioSetting("ponmsg", "Power-On Message",
1193
                              RadioSettingValueList(
1194
                                  PONMSG_LIST, PONMSG_LIST[_settings.ponmsg]))
1195
            other.append(rs)
1196

    
1197
            if self._is_orig():
1198
                limit = "limits_old"
1199
            else:
1200
                limit = "limits_new"
1201

    
1202
            vhf_limit = getattr(self._memobj, limit).vhf
1203
            rs = RadioSetting("%s.vhf.lower" % limit, "VHF Lower Limit (MHz)",
1204
                              RadioSettingValueInteger(1, 1000,
1205
                                                       vhf_limit.lower))
1206
            other.append(rs)
1207

    
1208
            rs = RadioSetting("%s.vhf.upper" % limit, "VHF Upper Limit (MHz)",
1209
                              RadioSettingValueInteger(1, 1000,
1210
                                                       vhf_limit.upper))
1211
            other.append(rs)
1212

    
1213
            rs = RadioSetting("%s.vhf.enable" % limit, "VHF TX Enabled",
1214
                              RadioSettingValueBoolean(vhf_limit.enable))
1215
            other.append(rs)
1216

    
1217
            uhf_limit = getattr(self._memobj, limit).uhf
1218
            rs = RadioSetting("%s.uhf.lower" % limit, "UHF Lower Limit (MHz)",
1219
                              RadioSettingValueInteger(1, 1000,
1220
                                                       uhf_limit.lower))
1221
            other.append(rs)
1222
            rs = RadioSetting("%s.uhf.upper" % limit, "UHF Upper Limit (MHz)",
1223
                              RadioSettingValueInteger(1, 1000,
1224
                                                       uhf_limit.upper))
1225
            other.append(rs)
1226
            rs = RadioSetting("%s.uhf.enable" % limit, "UHF TX Enabled",
1227
                              RadioSettingValueBoolean(uhf_limit.enable))
1228
            other.append(rs)
1229

    
1230
        if self.MODEL != "UV-6":
1231
            workmode = RadioSettingGroup("workmode", "Work Mode Settings")
1232
            group.append(workmode)
1233

    
1234
            rs = RadioSetting("displayab", "Display",
1235
                              RadioSettingValueList(
1236
                                  AB_LIST, AB_LIST[_settings.displayab]))
1237
            workmode.append(rs)
1238

    
1239
            rs = RadioSetting("workmode", "VFO/MR Mode",
1240
                              RadioSettingValueList(
1241
                                  WORKMODE_LIST,
1242
                                  WORKMODE_LIST[_settings.workmode]))
1243
            workmode.append(rs)
1244

    
1245
            rs = RadioSetting("keylock", "Keypad Lock",
1246
                              RadioSettingValueBoolean(_settings.keylock))
1247
            workmode.append(rs)
1248

    
1249
            rs = RadioSetting("wmchannel.mrcha", "MR A Channel",
1250
                              RadioSettingValueInteger(0, 127,
1251
                                                       _wmchannel.mrcha))
1252
            workmode.append(rs)
1253

    
1254
            rs = RadioSetting("wmchannel.mrchb", "MR B Channel",
1255
                              RadioSettingValueInteger(0, 127,
1256
                                                       _wmchannel.mrchb))
1257
            workmode.append(rs)
1258

    
1259
            def convert_bytes_to_freq(bytes):
1260
                real_freq = 0
1261
                for byte in bytes:
1262
                    real_freq = (real_freq * 10) + byte
1263
                return chirp_common.format_freq(real_freq * 10)
1264

    
1265
            def my_validate(value):
1266
                value = chirp_common.parse_freq(value)
1267
                if 17400000 <= value and value < 40000000:
1268
                    msg = ("Can't be between 174.00000-400.00000")
1269
                    raise InvalidValueError(msg)
1270
                return chirp_common.format_freq(value)
1271

    
1272
            def apply_freq(setting, obj):
1273
                value = chirp_common.parse_freq(str(setting.value)) / 10
1274
                obj.band = value >= 40000000
1275
                for i in range(7, -1, -1):
1276
                    obj.freq[i] = value % 10
1277
                    value /= 10
1278

    
1279
            val1a = RadioSettingValueString(0, 10,
1280
                                            convert_bytes_to_freq(_vfoa.freq))
1281
            val1a.set_validate_callback(my_validate)
1282
            rs = RadioSetting("vfoa.freq", "VFO A Frequency", val1a)
1283
            rs.set_apply_callback(apply_freq, _vfoa)
1284
            workmode.append(rs)
1285

    
1286
            val1b = RadioSettingValueString(0, 10,
1287
                                            convert_bytes_to_freq(_vfob.freq))
1288
            val1b.set_validate_callback(my_validate)
1289
            rs = RadioSetting("vfob.freq", "VFO B Frequency", val1b)
1290
            rs.set_apply_callback(apply_freq, _vfob)
1291
            workmode.append(rs)
1292

    
1293
            rs = RadioSetting("vfoa.sftd", "VFO A Shift",
1294
                              RadioSettingValueList(
1295
                                  SHIFTD_LIST, SHIFTD_LIST[_vfoa.sftd]))
1296
            workmode.append(rs)
1297

    
1298
            rs = RadioSetting("vfob.sftd", "VFO B Shift",
1299
                              RadioSettingValueList(
1300
                                  SHIFTD_LIST, SHIFTD_LIST[_vfob.sftd]))
1301
            workmode.append(rs)
1302

    
1303
            def convert_bytes_to_offset(bytes):
1304
                real_offset = 0
1305
                for byte in bytes:
1306
                    real_offset = (real_offset * 10) + byte
1307
                return chirp_common.format_freq(real_offset * 10000)
1308

    
1309
            def apply_offset(setting, obj):
1310
                value = chirp_common.parse_freq(str(setting.value)) / 10000
1311
                for i in range(3, -1, -1):
1312
                    obj.offset[i] = value % 10
1313
                    value /= 10
1314

    
1315
            val1a = RadioSettingValueString(
1316
                        0, 10, convert_bytes_to_offset(_vfoa.offset))
1317
            rs = RadioSetting("vfoa.offset",
1318
                              "VFO A Offset (0.00-69.95)", val1a)
1319
            rs.set_apply_callback(apply_offset, _vfoa)
1320
            workmode.append(rs)
1321

    
1322
            val1b = RadioSettingValueString(
1323
                        0, 10, convert_bytes_to_offset(_vfob.offset))
1324
            rs = RadioSetting("vfob.offset",
1325
                              "VFO B Offset (0.00-69.95)", val1b)
1326
            rs.set_apply_callback(apply_offset, _vfob)
1327
            workmode.append(rs)
1328

    
1329
            if self.MODEL in ("KT-980HP", "BF-F8HP", "UV-82HP"):
1330
                rs = RadioSetting("vfoa.txpower3", "VFO A Power",
1331
                                  RadioSettingValueList(
1332
                                      TXPOWER3_LIST,
1333
                                      TXPOWER3_LIST[_vfoa.txpower3]))
1334
                workmode.append(rs)
1335

    
1336
                rs = RadioSetting("vfob.txpower3", "VFO B Power",
1337
                                  RadioSettingValueList(
1338
                                      TXPOWER3_LIST,
1339
                                      TXPOWER3_LIST[_vfob.txpower3]))
1340
                workmode.append(rs)
1341
            else:
1342
                rs = RadioSetting("vfoa.txpower", "VFO A Power",
1343
                                  RadioSettingValueList(
1344
                                      TXPOWER_LIST,
1345
                                      TXPOWER_LIST[_vfoa.txpower]))
1346
                workmode.append(rs)
1347

    
1348
                rs = RadioSetting("vfob.txpower", "VFO B Power",
1349
                                  RadioSettingValueList(
1350
                                      TXPOWER_LIST,
1351
                                      TXPOWER_LIST[_vfob.txpower]))
1352
                workmode.append(rs)
1353

    
1354
            rs = RadioSetting("vfoa.widenarr", "VFO A Bandwidth",
1355
                              RadioSettingValueList(
1356
                                  BANDWIDTH_LIST,
1357
                                  BANDWIDTH_LIST[_vfoa.widenarr]))
1358
            workmode.append(rs)
1359

    
1360
            rs = RadioSetting("vfob.widenarr", "VFO B Bandwidth",
1361
                              RadioSettingValueList(
1362
                                  BANDWIDTH_LIST,
1363
                                  BANDWIDTH_LIST[_vfob.widenarr]))
1364
            workmode.append(rs)
1365

    
1366
            rs = RadioSetting("vfoa.scode", "VFO A PTT-ID",
1367
                              RadioSettingValueList(
1368
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfoa.scode]))
1369
            workmode.append(rs)
1370

    
1371
            rs = RadioSetting("vfob.scode", "VFO B PTT-ID",
1372
                              RadioSettingValueList(
1373
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfob.scode]))
1374
            workmode.append(rs)
1375

    
1376
            if not self._is_orig():
1377
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1378
                                  RadioSettingValueList(
1379
                                      STEP291_LIST, STEP291_LIST[_vfoa.step]))
1380
                workmode.append(rs)
1381
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1382
                                  RadioSettingValueList(
1383
                                      STEP291_LIST, STEP291_LIST[_vfob.step]))
1384
                workmode.append(rs)
1385
            else:
1386
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1387
                                  RadioSettingValueList(
1388
                                      STEP_LIST, STEP_LIST[_vfoa.step]))
1389
                workmode.append(rs)
1390
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1391
                                  RadioSettingValueList(
1392
                                      STEP_LIST, STEP_LIST[_vfob.step]))
1393
                workmode.append(rs)
1394

    
1395
        fm_preset = RadioSettingGroup("fm_preset", "FM Radio Preset")
1396
        group.append(fm_preset)
1397

    
1398
        if _fm_presets <= 108.0 * 10 - 650:
1399
            preset = _fm_presets / 10.0 + 65
1400
        elif _fm_presets >= 65.0 * 10 and _fm_presets <= 108.0 * 10:
1401
            preset = _fm_presets / 10.0
1402
        else:
1403
            preset = 76.0
1404
        rs = RadioSetting("fm_presets", "FM Preset(MHz)",
1405
                          RadioSettingValueFloat(65, 108.0, preset, 0.1, 1))
1406
        fm_preset.append(rs)
1407

    
1408
        dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
1409
        group.append(dtmf)
1410
        dtmfchars = "0123456789 *#ABCD"
1411

    
1412
        for i in range(0, 15):
1413
            _codeobj = self._memobj.pttid[i].code
1414
            _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1415
            val = RadioSettingValueString(0, 5, _code, False)
1416
            val.set_charset(dtmfchars)
1417
            rs = RadioSetting("pttid/%i.code" % i,
1418
                              "PTT ID Code %i" % (i + 1), val)
1419

    
1420
            def apply_code(setting, obj):
1421
                code = []
1422
                for j in range(0, 5):
1423
                    try:
1424
                        code.append(dtmfchars.index(str(setting.value)[j]))
1425
                    except IndexError:
1426
                        code.append(0xFF)
1427
                obj.code = code
1428
            rs.set_apply_callback(apply_code, self._memobj.pttid[i])
1429
            dtmf.append(rs)
1430

    
1431
        _codeobj = self._memobj.ani.code
1432
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1433
        val = RadioSettingValueString(0, 5, _code, False)
1434
        val.set_charset(dtmfchars)
1435
        rs = RadioSetting("ani.code", "ANI Code", val)
1436

    
1437
        def apply_code(setting, obj):
1438
            code = []
1439
            for j in range(0, 5):
1440
                try:
1441
                    code.append(dtmfchars.index(str(setting.value)[j]))
1442
                except IndexError:
1443
                    code.append(0xFF)
1444
            obj.code = code
1445
        rs.set_apply_callback(apply_code, _ani)
1446
        dtmf.append(rs)
1447

    
1448
        rs = RadioSetting("ani.aniid", "ANI ID",
1449
                          RadioSettingValueList(PTTID_LIST,
1450
                                                PTTID_LIST[_ani.aniid]))
1451
        dtmf.append(rs)
1452

    
1453
        _codeobj = self._memobj.ani.alarmcode
1454
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1455
        val = RadioSettingValueString(0, 3, _code, False)
1456
        val.set_charset(dtmfchars)
1457
        rs = RadioSetting("ani.alarmcode", "Alarm Code", val)
1458

    
1459
        def apply_code(setting, obj):
1460
            alarmcode = []
1461
            for j in range(0, 3):
1462
                try:
1463
                    alarmcode.append(dtmfchars.index(str(setting.value)[j]))
1464
                except IndexError:
1465
                    alarmcode.append(0xFF)
1466
            obj.alarmcode = alarmcode
1467
        rs.set_apply_callback(apply_code, _ani)
1468
        dtmf.append(rs)
1469

    
1470
        rs = RadioSetting("dtmfst", "DTMF Sidetone",
1471
                          RadioSettingValueList(DTMFST_LIST,
1472
                                                DTMFST_LIST[_settings.dtmfst]))
1473
        dtmf.append(rs)
1474

    
1475
        if _ani.dtmfon > 0xC3:
1476
            val = 0x00
1477
        else:
1478
            val = _ani.dtmfon
1479
        rs = RadioSetting("ani.dtmfon", "DTMF Speed (on)",
1480
                          RadioSettingValueList(DTMFSPEED_LIST,
1481
                                                DTMFSPEED_LIST[val]))
1482
        dtmf.append(rs)
1483

    
1484
        if _ani.dtmfoff > 0xC3:
1485
            val = 0x00
1486
        else:
1487
            val = _ani.dtmfoff
1488
        rs = RadioSetting("ani.dtmfoff", "DTMF Speed (off)",
1489
                          RadioSettingValueList(DTMFSPEED_LIST,
1490
                                                DTMFSPEED_LIST[val]))
1491
        dtmf.append(rs)
1492

    
1493
        rs = RadioSetting("pttlt", "PTT ID Delay",
1494
                          RadioSettingValueInteger(0, 30, _settings.pttlt))
1495
        dtmf.append(rs)
1496

    
1497
        if not self._is_orig():
1498
            service = RadioSettingGroup("service", "Service Settings")
1499
            group.append(service)
1500

    
1501
            for band in ["vhf", "uhf"]:
1502
                for index in range(0, 10):
1503
                    key = "squelch_new.%s.sql%i" % (band, index)
1504
                    if band == "vhf":
1505
                        _obj = self._memobj.squelch_new.vhf
1506
                    elif band == "uhf":
1507
                        _obj = self._memobj.squelch_new.uhf
1508
                    name = "%s Squelch %i" % (band.upper(), index)
1509
                    rs = RadioSetting(key, name,
1510
                                      RadioSettingValueInteger(
1511
                                          0, 123,
1512
                                          getattr(_obj, "sql%i" % (index))))
1513
                    service.append(rs)
1514

    
1515
        return group
1516

    
1517
    def get_settings(self):
1518
        try:
1519
            return self._get_settings()
1520
        except:
1521
            import traceback
1522
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1523
            return None
1524

    
1525
    def set_settings(self, settings):
1526
        _settings = self._memobj.settings
1527
        for element in settings:
1528
            if not isinstance(element, RadioSetting):
1529
                if element.get_name() == "fm_preset":
1530
                    self._set_fm_preset(element)
1531
                else:
1532
                    self.set_settings(element)
1533
                    continue
1534
            else:
1535
                try:
1536
                    name = element.get_name()
1537
                    if "." in name:
1538
                        bits = name.split(".")
1539
                        obj = self._memobj
1540
                        for bit in bits[:-1]:
1541
                            if "/" in bit:
1542
                                bit, index = bit.split("/", 1)
1543
                                index = int(index)
1544
                                obj = getattr(obj, bit)[index]
1545
                            else:
1546
                                obj = getattr(obj, bit)
1547
                        setting = bits[-1]
1548
                    else:
1549
                        obj = _settings
1550
                        setting = element.get_name()
1551

    
1552
                    if element.has_apply_callback():
1553
                        LOG.debug("Using apply callback")
1554
                        element.run_apply_callback()
1555
                    elif element.value.get_mutable():
1556
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1557
                        setattr(obj, setting, element.value)
1558
                except Exception, e:
1559
                    LOG.debug(element.get_name())
1560
                    raise
1561

    
1562
    def _set_fm_preset(self, settings):
1563
        for element in settings:
1564
            try:
1565
                val = element.value
1566
                if self._memobj.fm_presets <= 108.0 * 10 - 650:
1567
                    value = int(val.get_value() * 10 - 650)
1568
                else:
1569
                    value = int(val.get_value() * 10)
1570
                LOG.debug("Setting fm_presets = %s" % (value))
1571
                self._memobj.fm_presets = value
1572
            except Exception, e:
1573
                LOG.debug(element.get_name())
1574
                raise
1575

    
1576

    
1577
class UV5XAlias(chirp_common.Alias):
1578
    VENDOR = "Baofeng"
1579
    MODEL = "UV-5X"
1580

    
1581

    
1582
@directory.register
1583
class BaofengUV5RGeneric(BaofengUV5R):
1584
    ALIASES = [UV5XAlias]
1585

    
1586

    
1587
@directory.register
1588
class BaofengF11Radio(BaofengUV5R):
1589
    VENDOR = "Baofeng"
1590
    MODEL = "F-11"
1591
    _basetype = BASETYPE_F11
1592
    _idents = [UV5R_MODEL_F11]
1593

    
1594
    def _is_orig(self):
1595
        # Override this for F11 to always return False
1596
        return False
1597

    
1598

    
1599
@directory.register
1600
class BaofengUV82Radio(BaofengUV5R):
1601
    MODEL = "UV-82"
1602
    _basetype = BASETYPE_UV82
1603
    _idents = [UV5R_MODEL_UV82]
1604
    _vhf_range = (130000000, 176000000)
1605
    _uhf_range = (400000000, 521000000)
1606

    
1607
    def _is_orig(self):
1608
        # Override this for UV82 to always return False
1609
        return False
1610

    
1611

    
1612
@directory.register
1613
class BaofengUV6Radio(BaofengUV5R):
1614
    """Baofeng UV-6/UV-7"""
1615
    VENDOR = "Baofeng"
1616
    MODEL = "UV-6"
1617
    _basetype = BASETYPE_UV6
1618
    _idents = [UV5R_MODEL_UV6,
1619
               UV5R_MODEL_UV6_ORIG
1620
               ]
1621

    
1622
    def get_features(self):
1623
        rf = BaofengUV5R.get_features(self)
1624
        rf.memory_bounds = (1, 128)
1625
        return rf
1626

    
1627
    def _get_mem(self, number):
1628
        return self._memobj.memory[number - 1]
1629

    
1630
    def _get_nam(self, number):
1631
        return self._memobj.names[number - 1]
1632

    
1633
    def _set_mem(self, number):
1634
        return self._memobj.memory[number - 1]
1635

    
1636
    def _set_nam(self, number):
1637
        return self._memobj.names[number - 1]
1638

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

    
1643

    
1644
@directory.register
1645
class IntekKT980Radio(BaofengUV5R):
1646
    VENDOR = "Intek"
1647
    MODEL = "KT-980HP"
1648
    _basetype = BASETYPE_KT980HP
1649
    _idents = [UV5R_MODEL_291]
1650
    _vhf_range = (130000000, 180000000)
1651
    _uhf_range = (400000000, 521000000)
1652

    
1653
    def get_features(self):
1654
        rf = BaofengUV5R.get_features(self)
1655
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1656
        return rf
1657

    
1658
    def _is_orig(self):
1659
        # Override this for KT980HP to always return False
1660
        return False
1661

    
1662

    
1663
@directory.register
1664
class BaofengBFF8HPRadio(BaofengUV5R):
1665
    VENDOR = "Baofeng"
1666
    MODEL = "BF-F8HP"
1667
    _basetype = BASETYPE_F8HP
1668
    _idents = [UV5R_MODEL_291,
1669
               UV5R_MODEL_A58
1670
               ]
1671
    _vhf_range = (130000000, 180000000)
1672
    _uhf_range = (400000000, 521000000)
1673

    
1674
    def get_features(self):
1675
        rf = BaofengUV5R.get_features(self)
1676
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1677
        return rf
1678

    
1679
    def _is_orig(self):
1680
        # Override this for BFF8HP to always return False
1681
        return False
1682

    
1683

    
1684
@directory.register
1685
class BaofengUV82HPRadio(BaofengUV5R):
1686
    VENDOR = "Baofeng"
1687
    MODEL = "UV-82HP"
1688
    _basetype = BASETYPE_UV82HP
1689
    _idents = [UV5R_MODEL_UV82]
1690
    _vhf_range = (136000000, 175000000)
1691
    _uhf_range = (400000000, 521000000)
1692

    
1693
    def get_features(self):
1694
        rf = BaofengUV5R.get_features(self)
1695
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1696
        return rf
1697

    
1698
    def _is_orig(self):
1699
        # Override this for UV82HP to always return False
1700
        return False
(32-32/32)