Project

General

Profile

New Model #2475 » uv5r (4).py

ferencak gregor, 04/25/2015 01:20 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;
128
  u8 displayab:1,
129
     unknown1:2,
130
     fmradio:1,
131
     alarm:1,
132
     unknown2:1,
133
     reset:1,
134
     menu:1;
135
  u8 unknown1:6,
136
     singleptt:1,
137
     vfomrlock:1;
138
  u8 workmode;
139
  u8 keylock;
140
} settings;
141

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

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

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

    
198
#seekto 0x0F56;
199
u16 fm_presets;
200

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

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

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

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

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

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

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

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

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

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

    
275
"""
276

    
277
# 0x1EC0 - 0x2000
278

    
279
vhf_220_radio = "\x02"
280

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

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

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

    
355

    
356
def _do_status(radio, block):
357
    status = chirp_common.Status()
358
    status.msg = "Cloning"
359
    status.cur = block
360
    status.max = radio.get_memsize()
361
    radio.status_fn(status)
362

    
363
UV5R_MODEL_ORIG = "\x50\xBB\xFF\x01\x25\x98\x4D"
364
UV5R_MODEL_291 = "\x50\xBB\xFF\x20\x12\x07\x25"
365
UV5R_MODEL_F11 = "\x50\xBB\xFF\x13\xA1\x11\xDD"
366
UV5R_MODEL_UV82 = "\x50\xBB\xFF\x20\x13\x01\x05"
367
UV5R_MODEL_UV6 = "\x50\xBB\xFF\x20\x12\x08\x23"
368
UV5R_MODEL_UV6_ORIG = "\x50\xBB\xFF\x12\x03\x98\x4D"
369

    
370

    
371
def _upper_band_from_data(data):
372
    return data[0x03:0x04]
373

    
374

    
375
def _upper_band_from_image(radio):
376
    return _upper_band_from_data(radio.get_mmap())
377

    
378

    
379
def _firmware_version_from_data(data, version_start, version_stop):
380
    version_tag = data[version_start:version_stop]
381
    return version_tag
382

    
383

    
384
def _firmware_version_from_image(radio):
385
    version = _firmware_version_from_data(radio.get_mmap(),
386
                                          radio._fw_ver_file_start,
387
                                          radio._fw_ver_file_stop)
388
    LOG.debug("_firmware_version_from_image: " + util.hexprint(version))
389
    return version
390

    
391

    
392
def _special_block_from_data(data, special_block_start, special_block_stop):
393
    special_block_tag = data[special_block_start:special_block_stop]
394
    return special_block_tag
395

    
396

    
397
def _special_block_from_image(radio):
398
    special_block = _special_block_from_data(radio.get_mmap(), 0x0CFA, 0x0D01)
399
    LOG.debug("_special_block_from_image: " + util.hexprint(special_block))
400
    return special_block
401

    
402

    
403
def _do_ident(radio, magic):
404
    serial = radio.pipe
405
    serial.setTimeout(1)
406

    
407
    LOG.info("Sending Magic: %s" % util.hexprint(magic))
408
    for byte in magic:
409
        serial.write(byte)
410
        time.sleep(0.01)
411
    ack = serial.read(1)
412

    
413
    if ack != "\x06":
414
        if ack:
415
            LOG.debug(repr(ack))
416
        raise errors.RadioError("Radio did not respond")
417

    
418
    serial.write("\x02")
419
    ident = serial.read(8)
420

    
421
    LOG.info("Ident: %s" % util.hexprint(ident))
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 _get_radio_special_block(radio):
477
    block = _read_block(radio, 0xCF0, 0x40, False)
478
    special_block = block[2:9]
479
    return special_block
480

    
481

    
482
def _ident_radio(radio):
483
    for magic in radio._idents:
484
        error = None
485
        try:
486
            data = _do_ident(radio, magic)
487
            return data
488
        except errors.RadioError, e:
489
            LOG.error(e)
490
            error = e
491
            time.sleep(2)
492
    if error:
493
        raise error
494
    raise errors.RadioError("Radio did not respond")
495

    
496

    
497
def _do_download(radio):
498
    data = _ident_radio(radio)
499

    
500
    radio_version = _get_radio_firmware_version(radio)
501
    LOG.info("Radio Version is %s" % repr(radio_version))
502

    
503
    #if not any(type in radio_version for type in radio._basetype):
504
    #    raise errors.RadioError("Incorrect 'Model' selected.")
505

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

    
520

    
521
def _send_block(radio, addr, data):
522
    msg = struct.pack(">BHB", ord("X"), addr, len(data))
523
    radio.pipe.write(msg + data)
524
    time.sleep(0.05)
525

    
526
    ack = radio.pipe.read(1)
527
    if ack != "\x06":
528
        raise errors.RadioError("Radio refused to accept block 0x%04x" % addr)
529

    
530

    
531
def _do_upload(radio):
532
    ident = _ident_radio(radio)
533
    radio_upper_band = ident[3:4]
534
    image_upper_band = _upper_band_from_image(radio)
535

    
536
    if image_upper_band == vhf_220_radio or radio_upper_band == vhf_220_radio:
537
        if image_upper_band != radio_upper_band:
538
            raise errors.RadioError("Image not supported by radio")
539

    
540
    image_version = _firmware_version_from_image(radio)
541
    radio_version = _get_radio_firmware_version(radio)
542
    LOG.info("Image Version is %s" % repr(image_version))
543
    LOG.info("Radio Version is %s" % repr(radio_version))
544

    
545
    if image_version != radio_version:
546
        msg = ("The upload was stopped because the firmware "
547
               "version of the image (%s) does not match that "
548
               "of the radio (%s).")
549
        raise errors.RadioError(msg % (image_version, radio_version))
550

    
551
    image_special_block = _special_block_from_image(radio)
552
    radio_special_block = _get_radio_special_block(radio)
553
    LOG.debug("Image Special Block is " + util.hexprint(image_special_block))
554
    LOG.debug("Radio Special Block is " + util.hexprint(radio_special_block))
555

    
556
    if image_special_block != radio_special_block:
557
        raise errors.RadioError("Image not supported by radio: `%s'" %
558
                                radio_special_block)
559

    
560
    # Main block
561
    for i in range(0x08, 0x1808, 0x10):
562
        _send_block(radio, i - 0x08, radio.get_mmap()[i:i + 0x10])
563
        _do_status(radio, i)
564
    _do_status(radio, radio.get_memsize())
565

    
566
    if len(radio.get_mmap().get_packed()) == 0x1808:
567
        LOG.info("Old image, not writing aux block")
568
        return  # Old image, no aux block
569

    
570
    if image_version != radio_version:
571
        msg = ("Upload finished, but the 'Other Settings' "
572
               "could not be sent because the firmware "
573
               "version of the image (%s) does not match "
574
               "that of the radio (%s).")
575
        raise errors.RadioError(msg % (image_version, radio_version))
576

    
577
    # Auxiliary block at radio address 0x1EC0, our offset 0x1808
578
    for i in range(0x1EC0, 0x2000, 0x10):
579
        addr = 0x1808 + (i - 0x1EC0)
580
        _send_block(radio, i, radio.get_mmap()[addr:addr + 0x10])
581

    
582
UV5R_POWER_LEVELS = [chirp_common.PowerLevel("High", watts=4.00),
583
                     chirp_common.PowerLevel("Low",  watts=1.00)]
584

    
585
UV5R_POWER_LEVELS3 = [chirp_common.PowerLevel("High", watts=8.00),
586
                      chirp_common.PowerLevel("Med",  watts=4.00),
587
                      chirp_common.PowerLevel("Low",  watts=1.00)]
588

    
589
UV5R_DTCS = sorted(chirp_common.DTCS_CODES + [645])
590

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

    
594

    
595
# Uncomment this to actually register this radio in CHIRP
596
@directory.register
597
class BaofengUV5R(chirp_common.CloneModeRadio,
598
                  chirp_common.ExperimentalRadio):
599
    """Baofeng UV-5R"""
600
    VENDOR = "Baofeng"
601
    MODEL = "UV-5R"
602
    BAUD_RATE = 9600
603

    
604
    _memsize = 0x1808
605
    _basetype = BASETYPE_UV5R
606
    _idents = [UV5R_MODEL_291,
607
               UV5R_MODEL_ORIG
608
               ]
609
    _vhf_range = (136000000, 174000000)
610
    _220_range = (220000000, 260000000)
611
    _uhf_range = (400000000, 520000000)
612
    _mem_params = (0x1828  # poweron_msg offset
613
                   )
614
    # offset of fw version in image file
615
    _fw_ver_file_start = 0x1838
616
    _fw_ver_file_stop = 0x1846
617

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

    
644
    def get_features(self):
645
        rf = chirp_common.RadioFeatures()
646
        rf.has_settings = True
647
        rf.has_bank = False
648
        rf.has_cross = True
649
        rf.has_rx_dtcs = True
650
        rf.has_tuning_step = False
651
        rf.can_odd_split = True
652
        rf.valid_name_length = 7
653
        rf.valid_characters = UV5R_CHARSET
654
        rf.valid_skips = ["", "S"]
655
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
656
        rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone",
657
                                "->Tone", "->DTCS", "DTCS->", "DTCS->DTCS"]
658
        rf.valid_power_levels = UV5R_POWER_LEVELS
659
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
660
        rf.valid_modes = ["FM", "NFM"]
661

    
662
        normal_bands = [self._vhf_range, self._uhf_range]
663
        rax_bands = [self._vhf_range, self._220_range]
664

    
665
        if self._mmap is None:
666
            rf.valid_bands = [normal_bands[0], rax_bands[1], normal_bands[1]]
667
        elif not self._is_orig() and self._my_upper_band() == vhf_220_radio:
668
            rf.valid_bands = rax_bands
669
        else:
670
            rf.valid_bands = normal_bands
671
        rf.memory_bounds = (0, 127)
672
        return rf
673

    
674
    @classmethod
675
    def match_model(cls, filedata, filename):
676
        match_size = False
677
        match_model = False
678
        if len(filedata) in [0x1808, 0x1948]:
679
            match_size = True
680
        fwdata = _firmware_version_from_data(filedata,
681
                                             cls._fw_ver_file_start,
682
                                             cls._fw_ver_file_stop)
683
        if any(type in fwdata for type in cls._basetype):
684
            match_model = True
685
        if match_size and match_model:
686
            return True
687
        else:
688
            return False
689

    
690
    def process_mmap(self):
691
        self._memobj = bitwise.parse(MEM_FORMAT % self._mem_params, self._mmap)
692

    
693
    def sync_in(self):
694
        try:
695
            self._mmap = _do_download(self)
696
        except errors.RadioError:
697
            raise
698
        except Exception, e:
699
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
700
        self.process_mmap()
701

    
702
    def sync_out(self):
703
        try:
704
            _do_upload(self)
705
        except errors.RadioError:
706
            raise
707
        except Exception, e:
708
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
709

    
710
    def get_raw_memory(self, number):
711
        return repr(self._memobj.memory[number])
712

    
713
    def _is_txinh(self, _mem):
714
        raw_tx = ""
715
        for i in range(0, 4):
716
            raw_tx += _mem.txfreq[i].get_raw()
717
        return raw_tx == "\xFF\xFF\xFF\xFF"
718

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

    
722
    def _get_nam(self, number):
723
        return self._memobj.names[number]
724

    
725
    def get_memory(self, number):
726
        _mem = self._get_mem(number)
727
        _nam = self._get_nam(number)
728

    
729
        mem = chirp_common.Memory()
730
        mem.number = number
731

    
732
        if _mem.get_raw()[0] == "\xff":
733
            mem.empty = True
734
            return mem
735

    
736
        mem.freq = int(_mem.rxfreq) * 10
737

    
738
        if self._is_txinh(_mem):
739
            mem.duplex = "off"
740
            mem.offset = 0
741
        elif int(_mem.rxfreq) == int(_mem.txfreq):
742
            mem.duplex = ""
743
            mem.offset = 0
744
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 70000000:
745
            mem.duplex = "split"
746
            mem.offset = int(_mem.txfreq) * 10
747
        else:
748
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
749
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
750

    
751
        for char in _nam.name:
752
            if str(char) == "\xFF":
753
                char = " "  # The UV-5R software may have 0xFF mid-name
754
            mem.name += str(char)
755
        mem.name = mem.name.rstrip()
756

    
757
        dtcs_pol = ["N", "N"]
758

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

    
775
        if _mem.rxtone in [0, 0xFFFF]:
776
            rxmode = ""
777
        elif _mem.rxtone >= 0x0258:
778
            rxmode = "Tone"
779
            mem.ctone = int(_mem.rxtone) / 10.0
780
        elif _mem.rxtone <= 0x0258:
781
            rxmode = "DTCS"
782
            if _mem.rxtone >= 0x6A:
783
                index = _mem.rxtone - 0x6A
784
                dtcs_pol[1] = "R"
785
            else:
786
                index = _mem.rxtone - 1
787
            mem.rx_dtcs = UV5R_DTCS[index]
788
        else:
789
            LOG.warn("Bug: rxtone is %04x" % _mem.rxtone)
790

    
791
        if txmode == "Tone" and not rxmode:
792
            mem.tmode = "Tone"
793
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
794
            mem.tmode = "TSQL"
795
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
796
            mem.tmode = "DTCS"
797
        elif rxmode or txmode:
798
            mem.tmode = "Cross"
799
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
800

    
801
        mem.dtcs_polarity = "".join(dtcs_pol)
802

    
803
        if not _mem.scan:
804
            mem.skip = "S"
805

    
806
        if self.MODEL == "KT-980HP" or self.MODEL == "BF-F8HP":
807
            levels = UV5R_POWER_LEVELS3
808
        else:
809
            levels = UV5R_POWER_LEVELS
810
        try:
811
            mem.power = levels[_mem.lowpower]
812
        except IndexError:
813
            LOG.error("Radio reported invalid power level %s (in %s)" %
814
                      (_mem.power, levels))
815
            mem.power = levels[0]
816

    
817
        mem.mode = _mem.wide and "FM" or "NFM"
818

    
819
        mem.extra = RadioSettingGroup("Extra", "extra")
820

    
821
        rs = RadioSetting("bcl", "BCL",
822
                          RadioSettingValueBoolean(_mem.bcl))
823
        mem.extra.append(rs)
824

    
825
        rs = RadioSetting("pttid", "PTT ID",
826
                          RadioSettingValueList(PTTID_LIST,
827
                                                PTTID_LIST[_mem.pttid]))
828
        mem.extra.append(rs)
829

    
830
        rs = RadioSetting("scode", "PTT ID Code",
831
                          RadioSettingValueList(PTTIDCODE_LIST,
832
                                                PTTIDCODE_LIST[_mem.scode]))
833
        mem.extra.append(rs)
834

    
835
        return mem
836

    
837
    def _set_mem(self, number):
838
        return self._memobj.memory[number]
839

    
840
    def _set_nam(self, number):
841
        return self._memobj.names[number]
842

    
843
    def set_memory(self, mem):
844
        _mem = self._get_mem(mem.number)
845
        _nam = self._get_nam(mem.number)
846

    
847
        if mem.empty:
848
            _mem.set_raw("\xff" * 16)
849
            return
850

    
851
        _mem.set_raw("\x00" * 16)
852

    
853
        _mem.rxfreq = mem.freq / 10
854

    
855
        if mem.duplex == "off":
856
            for i in range(0, 4):
857
                _mem.txfreq[i].set_raw("\xFF")
858
        elif mem.duplex == "split":
859
            _mem.txfreq = mem.offset / 10
860
        elif mem.duplex == "+":
861
            _mem.txfreq = (mem.freq + mem.offset) / 10
862
        elif mem.duplex == "-":
863
            _mem.txfreq = (mem.freq - mem.offset) / 10
864
        else:
865
            _mem.txfreq = mem.freq / 10
866

    
867
        _namelength = self.get_features().valid_name_length
868
        for i in range(_namelength):
869
            try:
870
                _nam.name[i] = mem.name[i]
871
            except IndexError:
872
                _nam.name[i] = "\xFF"
873

    
874
        rxmode = txmode = ""
875
        if mem.tmode == "Tone":
876
            _mem.txtone = int(mem.rtone * 10)
877
            _mem.rxtone = 0
878
        elif mem.tmode == "TSQL":
879
            _mem.txtone = int(mem.ctone * 10)
880
            _mem.rxtone = int(mem.ctone * 10)
881
        elif mem.tmode == "DTCS":
882
            rxmode = txmode = "DTCS"
883
            _mem.txtone = UV5R_DTCS.index(mem.dtcs) + 1
884
            _mem.rxtone = UV5R_DTCS.index(mem.dtcs) + 1
885
        elif mem.tmode == "Cross":
886
            txmode, rxmode = mem.cross_mode.split("->", 1)
887
            if txmode == "Tone":
888
                _mem.txtone = int(mem.rtone * 10)
889
            elif txmode == "DTCS":
890
                _mem.txtone = UV5R_DTCS.index(mem.dtcs) + 1
891
            else:
892
                _mem.txtone = 0
893
            if rxmode == "Tone":
894
                _mem.rxtone = int(mem.ctone * 10)
895
            elif rxmode == "DTCS":
896
                _mem.rxtone = UV5R_DTCS.index(mem.rx_dtcs) + 1
897
            else:
898
                _mem.rxtone = 0
899
        else:
900
            _mem.rxtone = 0
901
            _mem.txtone = 0
902

    
903
        if txmode == "DTCS" and mem.dtcs_polarity[0] == "R":
904
            _mem.txtone += 0x69
905
        if rxmode == "DTCS" and mem.dtcs_polarity[1] == "R":
906
            _mem.rxtone += 0x69
907

    
908
        _mem.scan = mem.skip != "S"
909
        _mem.wide = mem.mode == "FM"
910

    
911
        if mem.power:
912
            if self.MODEL == "KT-980HP" or self.MODEL == "BF-F8HP":
913
                levels = [str(l) for l in UV5R_POWER_LEVELS3]
914
                _mem.lowpower = levels.index(str(mem.power))
915
            else:
916
                _mem.lowpower = UV5R_POWER_LEVELS.index(mem.power)
917
        else:
918
            _mem.lowpower = 0
919

    
920
        for setting in mem.extra:
921
            setattr(_mem, setting.get_name(), setting.value)
922

    
923
    def _is_orig(self):
924
        version_tag = _firmware_version_from_image(self)
925
        LOG.debug("@_is_orig, version_tag: %s", util.hexprint(version_tag))
926
        try:
927
            if 'BFB' in version_tag:
928
                idx = version_tag.index("BFB") + 3
929
                version = int(version_tag[idx:idx + 3])
930
                return version < 291
931
            return False
932
        except:
933
            pass
934
        raise errors.RadioError("Unable to parse version string %s" %
935
                                version_tag)
936

    
937
    def _my_version(self):
938
        version_tag = _firmware_version_from_image(self)
939
        if 'BFB' in version_tag:
940
            idx = version_tag.index("BFB") + 3
941
            return int(version_tag[idx:idx + 3])
942

    
943
        raise Exception("Unrecognized firmware version string")
944

    
945
    def _my_upper_band(self):
946
        band_tag = _upper_band_from_image(self)
947
        return band_tag
948

    
949
    def _get_settings(self):
950
        _ani = self._memobj.ani
951
        _settings = self._memobj.settings
952
        _squelch = self._memobj.squelch_new
953
        _vfoa = self._memobj.vfoa
954
        _vfob = self._memobj.vfob
955
        _wmchannel = self._memobj.wmchannel
956
        basic = RadioSettingGroup("basic", "Basic Settings")
957
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
958

    
959
        group = RadioSettings(basic, advanced)
960

    
961
        rs = RadioSetting("squelch", "Carrier Squelch Level",
962
                          RadioSettingValueInteger(0, 9, _settings.squelch))
963
        basic.append(rs)
964

    
965
        rs = RadioSetting("save", "Battery Saver",
966
                          RadioSettingValueList(
967
                              SAVE_LIST, SAVE_LIST[_settings.save]))
968
        basic.append(rs)
969

    
970
        rs = RadioSetting("vox", "VOX Sensitivity",
971
                          RadioSettingValueList(
972
                              VOX_LIST, VOX_LIST[_settings.vox]))
973
        advanced.append(rs)
974

    
975
        if self.MODEL == "UV-6":
976
            # NOTE: The UV-6 calls this byte voxenable, but the UV-5R calls it
977
            # autolk. Since this is a minor difference, it will be referred to
978
            # by the wrong name for the UV-6.
979
            rs = RadioSetting("autolk", "Vox",
980
                              RadioSettingValueBoolean(_settings.autolk))
981
            advanced.append(rs)
982

    
983
        if self.MODEL != "UV-6":
984
            rs = RadioSetting("abr", "Backlight Timeout",
985
                              RadioSettingValueInteger(0, 24, _settings.abr))
986
            basic.append(rs)
987

    
988
        rs = RadioSetting("tdr", "Dual Watch",
989
                          RadioSettingValueBoolean(_settings.tdr))
990
        advanced.append(rs)
991

    
992
        if self.MODEL == "UV-6":
993
            rs = RadioSetting("tdrch", "Dual Watch Channel",
994
                              RadioSettingValueList(
995
                                  TDRCH_LIST, TDRCH_LIST[_settings.tdrch]))
996
            advanced.append(rs)
997

    
998
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
999
                              RadioSettingValueBoolean(_settings.tdrab))
1000
            advanced.append(rs)
1001
        else:
1002
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1003
                              RadioSettingValueList(
1004
                                  TDRAB_LIST, TDRAB_LIST[_settings.tdrab]))
1005
            advanced.append(rs)
1006

    
1007
        if self.MODEL == "UV-6":
1008
            rs = RadioSetting("alarm", "Alarm Sound",
1009
                              RadioSettingValueBoolean(_settings.alarm))
1010
            advanced.append(rs)
1011

    
1012
        if _settings.almod > 0x02:
1013
            val = 0x01
1014
        else:
1015
            val = _settings.almod
1016
        rs = RadioSetting("almod", "Alarm Mode",
1017
                          RadioSettingValueList(
1018
                              ALMOD_LIST, ALMOD_LIST[val]))
1019
        advanced.append(rs)
1020

    
1021
        rs = RadioSetting("beep", "Beep",
1022
                          RadioSettingValueBoolean(_settings.beep))
1023
        basic.append(rs)
1024

    
1025
        rs = RadioSetting("timeout", "Timeout Timer",
1026
                          RadioSettingValueList(
1027
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
1028
        basic.append(rs)
1029

    
1030
        if self._is_orig() and self._my_version() < 251:
1031
            rs = RadioSetting("voice", "Voice",
1032
                              RadioSettingValueBoolean(_settings.voice))
1033
            advanced.append(rs)
1034
        else:
1035
            rs = RadioSetting("voice", "Voice",
1036
                              RadioSettingValueList(
1037
                                  VOICE_LIST, VOICE_LIST[_settings.voice]))
1038
            advanced.append(rs)
1039

    
1040
        rs = RadioSetting("screv", "Scan Resume",
1041
                          RadioSettingValueList(
1042
                              RESUME_LIST, RESUME_LIST[_settings.screv]))
1043
        advanced.append(rs)
1044

    
1045
        if self.MODEL != "UV-6":
1046
            rs = RadioSetting("mdfa", "Display Mode (A)",
1047
                              RadioSettingValueList(
1048
                                  MODE_LIST, MODE_LIST[_settings.mdfa]))
1049
            basic.append(rs)
1050

    
1051
            rs = RadioSetting("mdfb", "Display Mode (B)",
1052
                              RadioSettingValueList(
1053
                                  MODE_LIST, MODE_LIST[_settings.mdfb]))
1054
            basic.append(rs)
1055

    
1056
        rs = RadioSetting("bcl", "Busy Channel Lockout",
1057
                          RadioSettingValueBoolean(_settings.bcl))
1058
        advanced.append(rs)
1059

    
1060
        if self.MODEL != "UV-6":
1061
            rs = RadioSetting("autolk", "Automatic Key Lock",
1062
                              RadioSettingValueBoolean(_settings.autolk))
1063
            advanced.append(rs)
1064

    
1065
        rs = RadioSetting("fmradio", "Broadcast FM Radio",
1066
                          RadioSettingValueBoolean(_settings.fmradio))
1067
        advanced.append(rs)
1068

    
1069
        if self.MODEL != "UV-6":
1070
            rs = RadioSetting("wtled", "Standby LED Color",
1071
                              RadioSettingValueList(
1072
                                  COLOR_LIST, COLOR_LIST[_settings.wtled]))
1073
            basic.append(rs)
1074

    
1075
            rs = RadioSetting("rxled", "RX LED Color",
1076
                              RadioSettingValueList(
1077
                                  COLOR_LIST, COLOR_LIST[_settings.rxled]))
1078
            basic.append(rs)
1079

    
1080
            rs = RadioSetting("txled", "TX LED Color",
1081
                              RadioSettingValueList(
1082
                                  COLOR_LIST, COLOR_LIST[_settings.txled]))
1083
            basic.append(rs)
1084

    
1085
        if self.MODEL == "UV-82":
1086
            rs = RadioSetting("roger", "Roger Beep (TX)",
1087
                              RadioSettingValueBoolean(_settings.roger))
1088
            basic.append(rs)
1089
            rs = RadioSetting("rogerrx", "Roger Beep (RX)",
1090
                              RadioSettingValueList(
1091
                                  ROGERRX_LIST,
1092
                                  ROGERRX_LIST[_settings.rogerrx]))
1093
            basic.append(rs)
1094
        else:
1095
            rs = RadioSetting("roger", "Roger Beep",
1096
                              RadioSettingValueBoolean(_settings.roger))
1097
            basic.append(rs)
1098

    
1099
        rs = RadioSetting("ste", "Squelch Tail Eliminate (HT to HT)",
1100
                          RadioSettingValueBoolean(_settings.ste))
1101
        advanced.append(rs)
1102

    
1103
        rs = RadioSetting("rpste", "Squelch Tail Eliminate (repeater)",
1104
                          RadioSettingValueList(
1105
                              RPSTE_LIST, RPSTE_LIST[_settings.rpste]))
1106
        advanced.append(rs)
1107

    
1108
        rs = RadioSetting("rptrl", "STE Repeater Delay",
1109
                          RadioSettingValueList(
1110
                              STEDELAY_LIST, STEDELAY_LIST[_settings.rptrl]))
1111
        advanced.append(rs)
1112

    
1113
        if self.MODEL != "UV-6":
1114
            rs = RadioSetting("reset", "RESET Menu",
1115
                              RadioSettingValueBoolean(_settings.reset))
1116
            advanced.append(rs)
1117

    
1118
            rs = RadioSetting("menu", "All Menus",
1119
                              RadioSettingValueBoolean(_settings.menu))
1120
            advanced.append(rs)
1121

    
1122
        if self.MODEL == "F-11":
1123
            # this is an F-11 only feature
1124
            rs = RadioSetting("vfomrlock", "VFO/MR Button",
1125
                              RadioSettingValueBoolean(_settings.vfomrlock))
1126
            advanced.append(rs)
1127

    
1128
        if self.MODEL == "UV-82":
1129
            # this is a UV-82C only feature
1130
            rs = RadioSetting("vfomrlock", "VFO/MR Switching (UV-82C only)",
1131
                              RadioSettingValueBoolean(_settings.vfomrlock))
1132
            advanced.append(rs)
1133

    
1134
        if self.MODEL == "UV-82":
1135
            # this is an UV-82C only feature
1136
            rs = RadioSetting("singleptt", "Single PTT (UV-82C only)",
1137
                              RadioSettingValueBoolean(_settings.singleptt))
1138
            advanced.append(rs)
1139

    
1140
        if len(self._mmap.get_packed()) == 0x1808:
1141
            # Old image, without aux block
1142
            return group
1143

    
1144
        other = RadioSettingGroup("other", "Other Settings")
1145
        group.append(other)
1146

    
1147
        def _filter(name):
1148
            filtered = ""
1149
            for char in str(name):
1150
                if char in chirp_common.CHARSET_ASCII:
1151
                    filtered += char
1152
                else:
1153
                    filtered += " "
1154
            return filtered
1155

    
1156
        _msg = self._memobj.firmware_msg
1157
        val = RadioSettingValueString(0, 7, _filter(_msg.line1))
1158
        val.set_mutable(False)
1159
        rs = RadioSetting("firmware_msg.line1", "Firmware Message 1", val)
1160
        other.append(rs)
1161

    
1162
        val = RadioSettingValueString(0, 7, _filter(_msg.line2))
1163
        val.set_mutable(False)
1164
        rs = RadioSetting("firmware_msg.line2", "Firmware Message 2", val)
1165
        other.append(rs)
1166

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

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

    
1188
            rs = RadioSetting("ponmsg", "Power-On Message",
1189
                              RadioSettingValueList(
1190
                                  PONMSG_LIST, PONMSG_LIST[_settings.ponmsg]))
1191
            other.append(rs)
1192

    
1193
            if self._is_orig():
1194
                limit = "limits_old"
1195
            else:
1196
                limit = "limits_new"
1197

    
1198
            vhf_limit = getattr(self._memobj, limit).vhf
1199
            rs = RadioSetting("%s.vhf.lower" % limit, "VHF Lower Limit (MHz)",
1200
                              RadioSettingValueInteger(1, 1000,
1201
                                                       vhf_limit.lower))
1202
            other.append(rs)
1203

    
1204
            rs = RadioSetting("%s.vhf.upper" % limit, "VHF Upper Limit (MHz)",
1205
                              RadioSettingValueInteger(1, 1000,
1206
                                                       vhf_limit.upper))
1207
            other.append(rs)
1208

    
1209
            rs = RadioSetting("%s.vhf.enable" % limit, "VHF TX Enabled",
1210
                              RadioSettingValueBoolean(vhf_limit.enable))
1211
            other.append(rs)
1212

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

    
1226
        if self.MODEL != "UV-6":
1227
            workmode = RadioSettingGroup("workmode", "Work Mode Settings")
1228
            group.append(workmode)
1229

    
1230
            rs = RadioSetting("displayab", "Display",
1231
                              RadioSettingValueList(
1232
                                  AB_LIST, AB_LIST[_settings.displayab]))
1233
            workmode.append(rs)
1234

    
1235
            rs = RadioSetting("workmode", "VFO/MR Mode",
1236
                              RadioSettingValueList(
1237
                                  WORKMODE_LIST,
1238
                                  WORKMODE_LIST[_settings.workmode]))
1239
            workmode.append(rs)
1240

    
1241
            rs = RadioSetting("keylock", "Keypad Lock",
1242
                              RadioSettingValueBoolean(_settings.keylock))
1243
            workmode.append(rs)
1244

    
1245
            rs = RadioSetting("wmchannel.mrcha", "MR A Channel",
1246
                              RadioSettingValueInteger(0, 127,
1247
                                                       _wmchannel.mrcha))
1248
            workmode.append(rs)
1249

    
1250
            rs = RadioSetting("wmchannel.mrchb", "MR B Channel",
1251
                              RadioSettingValueInteger(0, 127,
1252
                                                       _wmchannel.mrchb))
1253
            workmode.append(rs)
1254

    
1255
            def convert_bytes_to_freq(bytes):
1256
                real_freq = 0
1257
                for byte in bytes:
1258
                    real_freq = (real_freq * 10) + byte
1259
                return chirp_common.format_freq(real_freq * 10)
1260

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

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

    
1275
            val1a = RadioSettingValueString(0, 10,
1276
                                            convert_bytes_to_freq(_vfoa.freq))
1277
            val1a.set_validate_callback(my_validate)
1278
            rs = RadioSetting("vfoa.freq", "VFO A Frequency", val1a)
1279
            rs.set_apply_callback(apply_freq, _vfoa)
1280
            workmode.append(rs)
1281

    
1282
            val1b = RadioSettingValueString(0, 10,
1283
                                            convert_bytes_to_freq(_vfob.freq))
1284
            val1b.set_validate_callback(my_validate)
1285
            rs = RadioSetting("vfob.freq", "VFO B Frequency", val1b)
1286
            rs.set_apply_callback(apply_freq, _vfob)
1287
            workmode.append(rs)
1288

    
1289
            rs = RadioSetting("vfoa.sftd", "VFO A Shift",
1290
                              RadioSettingValueList(
1291
                                  SHIFTD_LIST, SHIFTD_LIST[_vfoa.sftd]))
1292
            workmode.append(rs)
1293

    
1294
            rs = RadioSetting("vfob.sftd", "VFO B Shift",
1295
                              RadioSettingValueList(
1296
                                  SHIFTD_LIST, SHIFTD_LIST[_vfob.sftd]))
1297
            workmode.append(rs)
1298

    
1299
            def convert_bytes_to_offset(bytes):
1300
                real_offset = 0
1301
                for byte in bytes:
1302
                    real_offset = (real_offset * 10) + byte
1303
                return chirp_common.format_freq(real_offset * 10000)
1304

    
1305
            def apply_offset(setting, obj):
1306
                value = chirp_common.parse_freq(str(setting.value)) / 10000
1307
                for i in range(3, -1, -1):
1308
                    obj.offset[i] = value % 10
1309
                    value /= 10
1310

    
1311
            val1a = RadioSettingValueString(
1312
                        0, 10, convert_bytes_to_offset(_vfoa.offset))
1313
            rs = RadioSetting("vfoa.offset",
1314
                              "VFO A Offset (0.00-69.95)", val1a)
1315
            rs.set_apply_callback(apply_offset, _vfoa)
1316
            workmode.append(rs)
1317

    
1318
            val1b = RadioSettingValueString(
1319
                        0, 10, convert_bytes_to_offset(_vfob.offset))
1320
            rs = RadioSetting("vfob.offset",
1321
                              "VFO B Offset (0.00-69.95)", val1b)
1322
            rs.set_apply_callback(apply_offset, _vfob)
1323
            workmode.append(rs)
1324

    
1325
            if self.MODEL == "KT-980HP" or self.MODEL == "BF-F8HP":
1326
                rs = RadioSetting("vfoa.txpower3", "VFO A Power",
1327
                                  RadioSettingValueList(
1328
                                      TXPOWER3_LIST,
1329
                                      TXPOWER3_LIST[_vfoa.txpower3]))
1330
                workmode.append(rs)
1331

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

    
1344
                rs = RadioSetting("vfob.txpower", "VFO B Power",
1345
                                  RadioSettingValueList(
1346
                                      TXPOWER_LIST,
1347
                                      TXPOWER_LIST[_vfob.txpower]))
1348
                workmode.append(rs)
1349

    
1350
            rs = RadioSetting("vfoa.widenarr", "VFO A Bandwidth",
1351
                              RadioSettingValueList(
1352
                                  BANDWIDTH_LIST,
1353
                                  BANDWIDTH_LIST[_vfoa.widenarr]))
1354
            workmode.append(rs)
1355

    
1356
            rs = RadioSetting("vfob.widenarr", "VFO B Bandwidth",
1357
                              RadioSettingValueList(
1358
                                  BANDWIDTH_LIST,
1359
                                  BANDWIDTH_LIST[_vfob.widenarr]))
1360
            workmode.append(rs)
1361

    
1362
            rs = RadioSetting("vfoa.scode", "VFO A PTT-ID",
1363
                              RadioSettingValueList(
1364
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfoa.scode]))
1365
            workmode.append(rs)
1366

    
1367
            rs = RadioSetting("vfob.scode", "VFO B PTT-ID",
1368
                              RadioSettingValueList(
1369
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfob.scode]))
1370
            workmode.append(rs)
1371

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

    
1391
        fm_preset = RadioSettingGroup("fm_preset", "FM Radio Preset")
1392
        group.append(fm_preset)
1393

    
1394
        if self._memobj.fm_presets <= 116.1 * 10 - 650:
1395
            preset = self._memobj.fm_presets / 10.0 + 65
1396
        else:
1397
            preset = 76.0
1398
        rs = RadioSetting("fm_presets", "FM Preset(MHz)",
1399
                          RadioSettingValueFloat(65, 116.1, preset, 0.1, 1))
1400
        fm_preset.append(rs)
1401

    
1402
        dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
1403
        group.append(dtmf)
1404
        dtmfchars = "0123456789 *#ABCD"
1405

    
1406
        for i in range(0, 15):
1407
            _codeobj = self._memobj.pttid[i].code
1408
            _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1409
            val = RadioSettingValueString(0, 5, _code, False)
1410
            val.set_charset(dtmfchars)
1411
            rs = RadioSetting("pttid/%i.code" % i,
1412
                              "PTT ID Code %i" % (i + 1), val)
1413

    
1414
            def apply_code(setting, obj):
1415
                code = []
1416
                for j in range(0, 5):
1417
                    try:
1418
                        code.append(dtmfchars.index(str(setting.value)[j]))
1419
                    except IndexError:
1420
                        code.append(0xFF)
1421
                obj.code = code
1422
            rs.set_apply_callback(apply_code, self._memobj.pttid[i])
1423
            dtmf.append(rs)
1424

    
1425
        _codeobj = self._memobj.ani.code
1426
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1427
        val = RadioSettingValueString(0, 5, _code, False)
1428
        val.set_charset(dtmfchars)
1429
        rs = RadioSetting("ani.code", "ANI Code", val)
1430

    
1431
        def apply_code(setting, obj):
1432
            code = []
1433
            for j in range(0, 5):
1434
                try:
1435
                    code.append(dtmfchars.index(str(setting.value)[j]))
1436
                except IndexError:
1437
                    code.append(0xFF)
1438
            obj.code = code
1439
        rs.set_apply_callback(apply_code, _ani)
1440
        dtmf.append(rs)
1441

    
1442
        rs = RadioSetting("ani.aniid", "ANI ID",
1443
                          RadioSettingValueList(PTTID_LIST,
1444
                                                PTTID_LIST[_ani.aniid]))
1445
        dtmf.append(rs)
1446

    
1447
        _codeobj = self._memobj.ani.alarmcode
1448
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1449
        val = RadioSettingValueString(0, 3, _code, False)
1450
        val.set_charset(dtmfchars)
1451
        rs = RadioSetting("ani.alarmcode", "Alarm Code", val)
1452

    
1453
        def apply_code(setting, obj):
1454
            alarmcode = []
1455
            for j in range(0, 3):
1456
                try:
1457
                    alarmcode.append(dtmfchars.index(str(setting.value)[j]))
1458
                except IndexError:
1459
                    alarmcode.append(0xFF)
1460
            obj.alarmcode = alarmcode
1461
        rs.set_apply_callback(apply_code, _ani)
1462
        dtmf.append(rs)
1463

    
1464
        rs = RadioSetting("dtmfst", "DTMF Sidetone",
1465
                          RadioSettingValueList(DTMFST_LIST,
1466
                                                DTMFST_LIST[_settings.dtmfst]))
1467
        dtmf.append(rs)
1468

    
1469
        if _ani.dtmfon > 0xC3:
1470
            val = 0x00
1471
        else:
1472
            val = _ani.dtmfon
1473
        rs = RadioSetting("ani.dtmfon", "DTMF Speed (on)",
1474
                          RadioSettingValueList(DTMFSPEED_LIST,
1475
                                                DTMFSPEED_LIST[val]))
1476
        dtmf.append(rs)
1477

    
1478
        if _ani.dtmfoff > 0xC3:
1479
            val = 0x00
1480
        else:
1481
            val = _ani.dtmfoff
1482
        rs = RadioSetting("ani.dtmfoff", "DTMF Speed (off)",
1483
                          RadioSettingValueList(DTMFSPEED_LIST,
1484
                                                DTMFSPEED_LIST[val]))
1485
        dtmf.append(rs)
1486

    
1487
        if not self._is_orig():
1488
            service = RadioSettingGroup("service", "Service Settings")
1489
            group.append(service)
1490

    
1491
            for band in ["vhf", "uhf"]:
1492
                for index in range(0, 10):
1493
                    key = "squelch_new.%s.sql%i" % (band, index)
1494
                    if band == "vhf":
1495
                        _obj = self._memobj.squelch_new.vhf
1496
                    elif band == "uhf":
1497
                        _obj = self._memobj.squelch_new.uhf
1498
                    name = "%s Squelch %i" % (band.upper(), index)
1499
                    rs = RadioSetting(key, name,
1500
                                      RadioSettingValueInteger(
1501
                                          0, 123,
1502
                                          getattr(_obj, "sql%i" % (index))))
1503
                    service.append(rs)
1504

    
1505
        return group
1506

    
1507
    def get_settings(self):
1508
        try:
1509
            return self._get_settings()
1510
        except:
1511
            import traceback
1512
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1513
            return None
1514

    
1515
    def set_settings(self, settings):
1516
        _settings = self._memobj.settings
1517
        for element in settings:
1518
            if not isinstance(element, RadioSetting):
1519
                if element.get_name() == "fm_preset":
1520
                    self._set_fm_preset(element)
1521
                else:
1522
                    self.set_settings(element)
1523
                    continue
1524
            else:
1525
                try:
1526
                    name = element.get_name()
1527
                    if "." in name:
1528
                        bits = name.split(".")
1529
                        obj = self._memobj
1530
                        for bit in bits[:-1]:
1531
                            if "/" in bit:
1532
                                bit, index = bit.split("/", 1)
1533
                                index = int(index)
1534
                                obj = getattr(obj, bit)[index]
1535
                            else:
1536
                                obj = getattr(obj, bit)
1537
                        setting = bits[-1]
1538
                    else:
1539
                        obj = _settings
1540
                        setting = element.get_name()
1541

    
1542
                    if element.has_apply_callback():
1543
                        LOG.debug("Using apply callback")
1544
                        element.run_apply_callback()
1545
                    else:
1546
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1547
                        setattr(obj, setting, element.value)
1548
                except Exception, e:
1549
                    LOG.debug(element.get_name())
1550
                    raise
1551

    
1552
    def _set_fm_preset(self, settings):
1553
        for element in settings:
1554
            try:
1555
                val = element.value
1556
                value = int(val.get_value() * 10 - 650)
1557
                LOG.debug("Setting fm_presets = %s" % (value))
1558
                self._memobj.fm_presets = value
1559
            except Exception, e:
1560
                LOG.debug(element.get_name())
1561
                raise
1562

    
1563

    
1564
@directory.register
1565
class BaofengF11Radio(BaofengUV5R):
1566
    VENDOR = "Baofeng"
1567
    MODEL = "F-11"
1568
    _basetype = BASETYPE_F11
1569
    _idents = [UV5R_MODEL_F11]
1570

    
1571
    def _is_orig(self):
1572
        # Override this for F11 to always return False
1573
        return False
1574

    
1575

    
1576
@directory.register
1577
class BaofengUV82Radio(BaofengUV5R):
1578
    MODEL = "UV-82"
1579
    _basetype = BASETYPE_UV82
1580
    _idents = [UV5R_MODEL_UV82]
1581
    _vhf_range = (130000000, 176000000)
1582
    _uhf_range = (400000000, 521000000)
1583

    
1584
    def _is_orig(self):
1585
        # Override this for UV82 to always return False
1586
        return False
1587

    
1588

    
1589
@directory.register
1590
class BaofengUV6Radio(BaofengUV5R):
1591
    """Baofeng UV-6/UV-7"""
1592
    VENDOR = "Baofeng"
1593
    MODEL = "UV-6"
1594
    _basetype = BASETYPE_UV6
1595
    _idents = [UV5R_MODEL_UV6,
1596
               UV5R_MODEL_UV6_ORIG
1597
               ]
1598

    
1599
    def get_features(self):
1600
        rf = BaofengUV5R.get_features(self)
1601
        rf.memory_bounds = (1, 128)
1602
        return rf
1603

    
1604
    def _get_mem(self, number):
1605
        return self._memobj.memory[number - 1]
1606

    
1607
    def _get_nam(self, number):
1608
        return self._memobj.names[number - 1]
1609

    
1610
    def _set_mem(self, number):
1611
        return self._memobj.memory[number - 1]
1612

    
1613
    def _set_nam(self, number):
1614
        return self._memobj.names[number - 1]
1615

    
1616
    def _is_orig(self):
1617
        # Override this for UV6 to always return False
1618
        return False
1619

    
1620

    
1621
@directory.register
1622
class IntekKT980Radio(BaofengUV5R):
1623
    VENDOR = "Intek"
1624
    MODEL = "KT-980HP"
1625
    _basetype = BASETYPE_KT980HP
1626
    _idents = [UV5R_MODEL_291]
1627
    _vhf_range = (130000000, 180000000)
1628
    _uhf_range = (400000000, 521000000)
1629

    
1630
    def get_features(self):
1631
        rf = BaofengUV5R.get_features(self)
1632
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1633
        return rf
1634

    
1635
    def _is_orig(self):
1636
        # Override this for KT980HP to always return False
1637
        return False
1638

    
1639

    
1640
@directory.register
1641
class BaofengBFF8HPRadio(BaofengUV5R):
1642
    VENDOR = "Baofeng"
1643
    MODEL = "BF-F8HP"
1644
    _basetype = BASETYPE_F8HP
1645
    _idents = [UV5R_MODEL_291]
1646
    _vhf_range = (130000000, 180000000)
1647
    _uhf_range = (400000000, 521000000)
1648

    
1649
    def get_features(self):
1650
        rf = BaofengUV5R.get_features(self)
1651
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1652
        return rf
1653

    
1654
    def _is_orig(self):
1655
        # Override this for BFF8HP to always return False
1656
        return False
(9-9/9)