Project

General

Profile

Bug #2317 » uv5r.py

Jim Unroe, 03/13/2015 04:30 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;
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", "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

    
364
def validate_orig(ident):
365
    try:
366
        ver = int(ident[4:7])
367
        if ver >= 291:
368
            raise errors.RadioError("Radio version %i not supported" % ver)
369
    except ValueError:
370
        raise errors.RadioError("Radio reported invalid version string")
371

    
372

    
373
def validate_291(ident):
374
    if ident[4:7] != "\x30\x04\x50":
375
        raise errors.RadioError("Radio version not supported")
376

    
377
UV5R_MODEL_ORIG = "\x50\xBB\xFF\x01\x25\x98\x4D"
378
UV5R_MODEL_291 = "\x50\xBB\xFF\x20\x12\x07\x25"
379
UV5R_MODEL_F11 = "\x50\xBB\xFF\x13\xA1\x11\xDD"
380
UV5R_MODEL_UV82 = "\x50\xBB\xFF\x20\x13\x01\x05"
381
UV5R_MODEL_UV6 = "\x50\xBB\xFF\x20\x12\x08\x23"
382
UV5R_MODEL_UV6_ORIG = "\x50\xBB\xFF\x12\x03\x98\x4D"
383

    
384

    
385
def _upper_band_from_data(data):
386
    return data[0x03:0x04]
387

    
388

    
389
def _upper_band_from_image(radio):
390
    return _upper_band_from_data(radio.get_mmap())
391

    
392

    
393
def _firmware_version_from_data(data, version_start, version_stop):
394
    version_tag = data[version_start:version_stop]
395
    return version_tag
396

    
397

    
398
def _firmware_version_from_image(radio):
399
    version = _firmware_version_from_data(radio.get_mmap(),
400
                                          radio._fw_ver_file_start,
401
                                          radio._fw_ver_file_stop)
402
    LOG.debug("_firmware_version_from_image: " + util.hexprint(version))
403
    return version
404

    
405

    
406
def _special_block_from_data(data, special_block_start, special_block_stop):
407
    special_block_tag = data[special_block_start:special_block_stop]
408
    return special_block_tag
409

    
410

    
411
def _special_block_from_image(radio):
412
    special_block = _special_block_from_data(radio.get_mmap(), 0x0CFA, 0x0D01)
413
    LOG.debug("_special_block_from_image: " + util.hexprint(special_block))
414
    return special_block
415

    
416

    
417
def _do_ident(radio, magic):
418
    serial = radio.pipe
419
    serial.setTimeout(1)
420

    
421
    LOG.info("Sending Magic: %s" % util.hexprint(magic))
422
    for byte in magic:
423
        serial.write(byte)
424
        time.sleep(0.01)
425
    ack = serial.read(1)
426

    
427
    if ack != "\x06":
428
        if ack:
429
            LOG.debug(repr(ack))
430
        raise errors.RadioError("Radio did not respond")
431

    
432
    serial.write("\x02")
433
    ident = serial.read(8)
434

    
435
    LOG.info("Ident: %s" % util.hexprint(ident))
436

    
437
    serial.write("\x06")
438
    ack = serial.read(1)
439
    if ack != "\x06":
440
        raise errors.RadioError("Radio refused clone")
441

    
442
    return ident
443

    
444

    
445
def _read_block(radio, start, size, first_command = False):
446
    msg = struct.pack(">BHB", ord("S"), start, size)
447
    radio.pipe.write(msg)
448

    
449
    if(first_command == False):
450
        ack = radio.pipe.read(1)
451
        if ack != "\x06":
452
            raise errors.RadioError("Radio refused to send second block 0x%04x" % start)
453

    
454
    answer = radio.pipe.read(4)
455
    if len(answer) != 4:
456
        raise errors.RadioError("Radio refused to send block 0x%04x" % start)
457

    
458
    cmd, addr, length = struct.unpack(">BHB", answer)
459
    if cmd != ord("X") or addr != start or length != size:
460
        LOG.error("Invalid answer for block 0x%04x:" % start)
461
        LOG.debug("CMD: %s  ADDR: %04x  SIZE: %02x" % (cmd, addr, length))
462
        raise errors.RadioError("Unknown response from radio")
463

    
464
    chunk = radio.pipe.read(0x40)
465
    if not chunk:
466
        raise errors.RadioError("Radio did not send block 0x%04x" % start)
467
    elif len(chunk) != size:
468
        LOG.error("Chunk length was 0x%04i" % len(chunk))
469
        raise errors.RadioError("Radio sent incomplete block 0x%04x" % start)
470

    
471
    radio.pipe.write("\x06")
472
    time.sleep(0.005)
473

    
474
    return chunk
475

    
476

    
477
def _get_radio_firmware_version(radio):
478
    if radio.MODEL == "BJ-UV55":
479
        block = _read_block(radio, 0x1FF0, 0x40, True)
480
        version = block[0:6]
481
    else:
482
        block1 = _read_block(radio, 0x1EC0, 0x40, True)
483
        block2 = _read_block(radio, 0x1F00, 0x40, False)
484
        block = block1 + block2
485
        version = block[48:62]
486
    return version
487

    
488

    
489
def _get_radio_special_block(radio):
490
    block = _read_block(radio, 0xCF0, 0x40, False)
491
    special_block = block[2:9]
492
    return special_block
493

    
494

    
495
def _ident_radio(radio):
496
    for magic in radio._idents:
497
        error = None
498
        try:
499
            data = _do_ident(radio, magic)
500
            return data
501
        except errors.RadioError, e:
502
            LOG.error(e)
503
            error = e
504
            time.sleep(2)
505
    if error:
506
        raise error
507
    raise errors.RadioError("Radio did not respond")
508

    
509

    
510
def _do_download(radio):
511
    data = _ident_radio(radio)
512

    
513
    radio_version = _get_radio_firmware_version(radio)
514
    LOG.info("Radio Version is %s" % repr(radio_version))
515

    
516
    if not any(type in radio_version for type in radio._basetype):
517
        raise errors.RadioError("Incorrect 'Model' selected.")
518

    
519
    # Main block
520
    LOG.debug("downloading main block...")
521
    for i in range(0, 0x1800, 0x40):
522
        data += _read_block(radio, i, 0x40, False)
523
        _do_status(radio, i)
524
    _do_status(radio, radio.get_memsize())
525
    LOG.debug("done.")
526
    LOG.debug("downloading aux block...")
527
    # Auxiliary block starts at 0x1ECO (?)
528
    for i in range(0x1EC0, 0x2000, 0x40):
529
        data += _read_block(radio, i, 0x40, False)
530
    LOG.debug("done.")
531
    return memmap.MemoryMap(data)
532

    
533

    
534
def _send_block(radio, addr, data):
535
    msg = struct.pack(">BHB", ord("X"), addr, len(data))
536
    radio.pipe.write(msg + data)
537
    time.sleep(0.05)
538

    
539
    ack = radio.pipe.read(1)
540
    if ack != "\x06":
541
        raise errors.RadioError("Radio refused to accept block 0x%04x" % addr)
542

    
543

    
544
def _do_upload(radio):
545
    ident = _ident_radio(radio)
546
    radio_upper_band = ident[3:4]
547
    image_upper_band = _upper_band_from_image(radio)
548

    
549
    if image_upper_band == vhf_220_radio or radio_upper_band == vhf_220_radio:
550
        if image_upper_band != radio_upper_band:
551
            raise errors.RadioError("Image not supported by radio")
552

    
553
    image_version = _firmware_version_from_image(radio)
554
    radio_version = _get_radio_firmware_version(radio)
555
    LOG.info("Image Version is %s" % repr(image_version))
556
    LOG.info("Radio Version is %s" % repr(radio_version))
557

    
558
    if not any(type in radio_version for type in BASETYPE_LIST):
559
        raise errors.RadioError("Unsupported firmware version: `%s'" %
560
                                radio_version)
561

    
562
    image_special_block = _special_block_from_image(radio)
563
    radio_special_block = _get_radio_special_block(radio)
564
    LOG.debug("Image Special Block is " + util.hexprint(image_special_block))
565
    LOG.debug("Radio Special Block is " + util.hexprint(radio_special_block))
566

    
567
    if image_special_block != radio_special_block:
568
        raise errors.RadioError("Image not supported by radio: `%s'" %
569
                                radio_special_block)
570

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

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

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

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

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

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

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

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

    
605

    
606
# Uncomment this to actually register this radio in CHIRP
607
@directory.register
608
class BaofengUV5R(chirp_common.CloneModeRadio,
609
                  chirp_common.ExperimentalRadio):
610
    """Baofeng UV-5R"""
611
    VENDOR = "Baofeng"
612
    MODEL = "UV-5R"
613
    BAUD_RATE = 9600
614

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
846
        return mem
847

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

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

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

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

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

    
864
        _mem.rxfreq = mem.freq / 10
865

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

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

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

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

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

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

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

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

    
948
    def _my_version(self):
949
        version_tag = _firmware_version_from_image(self)
950
        if 'BFS' in version_tag:
951
            idx = version_tag.index("BFS") + 3
952
            return int(version_tag[idx:idx + 3])
953
        elif 'BTS' in version_tag:
954
            idx = version_tag.index("BTS") + 3
955
            return int(version_tag[idx:idx + 3])
956
        elif 'BF82' in version_tag:
957
            idx = version_tag.index("BF82") + 2
958
            return int(version_tag[idx:idx + 4])
959
        elif 'B82S' in version_tag:
960
            idx = version_tag.index("B82S") + 4
961
            return int(version_tag[idx:idx + 2]) + 8200
962
        elif 'US2S' in version_tag:
963
            idx = version_tag.index("US2S") + 4
964
            return int(version_tag[idx:idx + 2]) + 8200
965
        elif 'USA' in version_tag:
966
            idx = version_tag.index("USA") + 3
967
            return int(version_tag[idx:idx + 3]) + 11000
968
        elif 'BJ55' in version_tag:
969
            idx = version_tag.index("BJ55") + 2
970
            return int(version_tag[idx:idx + 4])
971
        elif 'BF1' in version_tag:
972
            idx = version_tag.index("BF1") + 2
973
            return int(version_tag[idx:idx + 4])
974
        elif 'BFP' in version_tag:
975
            idx = version_tag.index("BFP") + 5
976
            return int(version_tag[idx:idx + 1]) + 98000
977
        elif 'N5R-2' in version_tag:
978
            idx = version_tag.index("N5R-2") + 4
979
            return int(version_tag[idx:idx + 2]) + 300
980
        elif 'N5R-3' in version_tag:
981
            idx = version_tag.index("N5R-3") + 4
982
            return int(version_tag[idx:idx + 2]) + 98000
983
        elif 'N5R3' in version_tag:
984
            idx = version_tag.index("N5R3") + 4
985
            return int(version_tag[idx:idx + 3]) + 98000
986
        elif 'BFB' in version_tag:
987
            idx = version_tag.index("BFB") + 3
988
            return int(version_tag[idx:idx + 3])
989

    
990
        raise Exception("Unrecognized firmware version string")
991

    
992
    def _my_upper_band(self):
993
        band_tag = _upper_band_from_image(self)
994
        return band_tag
995

    
996
    def _get_settings(self):
997
        _ani = self._memobj.ani
998
        _settings = self._memobj.settings
999
        _squelch = self._memobj.squelch_new
1000
        _vfoa = self._memobj.vfoa
1001
        _vfob = self._memobj.vfob
1002
        _wmchannel = self._memobj.wmchannel
1003
        basic = RadioSettingGroup("basic", "Basic Settings")
1004
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
1005

    
1006
        group = RadioSettings(basic, advanced)
1007

    
1008
        rs = RadioSetting("squelch", "Carrier Squelch Level",
1009
                          RadioSettingValueInteger(0, 9, _settings.squelch))
1010
        basic.append(rs)
1011

    
1012
        rs = RadioSetting("save", "Battery Saver",
1013
                          RadioSettingValueList(
1014
                              SAVE_LIST, SAVE_LIST[_settings.save]))
1015
        basic.append(rs)
1016

    
1017
        rs = RadioSetting("vox", "VOX Sensitivity",
1018
                          RadioSettingValueList(
1019
                              VOX_LIST, VOX_LIST[_settings.vox]))
1020
        advanced.append(rs)
1021

    
1022
        if self.MODEL == "UV-6":
1023
            # NOTE: The UV-6 calls this byte voxenable, but the UV-5R calls it
1024
            # autolk. Since this is a minor difference, it will be referred to
1025
            # by the wrong name for the UV-6.
1026
            rs = RadioSetting("autolk", "Vox",
1027
                              RadioSettingValueBoolean(_settings.autolk))
1028
            advanced.append(rs)
1029

    
1030
        if self.MODEL != "UV-6":
1031
            rs = RadioSetting("abr", "Backlight Timeout",
1032
                              RadioSettingValueInteger(0, 24, _settings.abr))
1033
            basic.append(rs)
1034

    
1035
        rs = RadioSetting("tdr", "Dual Watch",
1036
                          RadioSettingValueBoolean(_settings.tdr))
1037
        advanced.append(rs)
1038

    
1039
        if self.MODEL == "UV-6":
1040
            rs = RadioSetting("tdrch", "Dual Watch Channel",
1041
                              RadioSettingValueList(
1042
                                  TDRCH_LIST, TDRCH_LIST[_settings.tdrch]))
1043
            advanced.append(rs)
1044

    
1045
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1046
                              RadioSettingValueBoolean(_settings.tdrab))
1047
            advanced.append(rs)
1048
        else:
1049
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1050
                              RadioSettingValueList(
1051
                                  TDRAB_LIST, TDRAB_LIST[_settings.tdrab]))
1052
            advanced.append(rs)
1053

    
1054
        if self.MODEL == "UV-6":
1055
            rs = RadioSetting("alarm", "Alarm Sound",
1056
                              RadioSettingValueBoolean(_settings.alarm))
1057
            advanced.append(rs)
1058

    
1059
        if _settings.almod > 0x02:
1060
            val = 0x01
1061
        else:
1062
            val = _settings.almod
1063
        rs = RadioSetting("almod", "Alarm Mode",
1064
                          RadioSettingValueList(
1065
                              ALMOD_LIST, ALMOD_LIST[val]))
1066
        advanced.append(rs)
1067

    
1068
        rs = RadioSetting("beep", "Beep",
1069
                          RadioSettingValueBoolean(_settings.beep))
1070
        basic.append(rs)
1071

    
1072
        rs = RadioSetting("timeout", "Timeout Timer",
1073
                          RadioSettingValueList(
1074
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
1075
        basic.append(rs)
1076

    
1077
        if self._is_orig() and self._my_version() < 251:
1078
            rs = RadioSetting("voice", "Voice",
1079
                              RadioSettingValueBoolean(_settings.voice))
1080
            advanced.append(rs)
1081
        else:
1082
            rs = RadioSetting("voice", "Voice",
1083
                              RadioSettingValueList(
1084
                                  VOICE_LIST, VOICE_LIST[_settings.voice]))
1085
            advanced.append(rs)
1086

    
1087
        rs = RadioSetting("screv", "Scan Resume",
1088
                          RadioSettingValueList(
1089
                              RESUME_LIST, RESUME_LIST[_settings.screv]))
1090
        advanced.append(rs)
1091

    
1092
        if self.MODEL != "UV-6":
1093
            rs = RadioSetting("mdfa", "Display Mode (A)",
1094
                              RadioSettingValueList(
1095
                                  MODE_LIST, MODE_LIST[_settings.mdfa]))
1096
            basic.append(rs)
1097

    
1098
            rs = RadioSetting("mdfb", "Display Mode (B)",
1099
                              RadioSettingValueList(
1100
                                  MODE_LIST, MODE_LIST[_settings.mdfb]))
1101
            basic.append(rs)
1102

    
1103
        rs = RadioSetting("bcl", "Busy Channel Lockout",
1104
                          RadioSettingValueBoolean(_settings.bcl))
1105
        advanced.append(rs)
1106

    
1107
        if self.MODEL != "UV-6":
1108
            rs = RadioSetting("autolk", "Automatic Key Lock",
1109
                              RadioSettingValueBoolean(_settings.autolk))
1110
            advanced.append(rs)
1111

    
1112
        rs = RadioSetting("fmradio", "Broadcast FM Radio",
1113
                          RadioSettingValueBoolean(_settings.fmradio))
1114
        advanced.append(rs)
1115

    
1116
        if self.MODEL != "UV-6":
1117
            rs = RadioSetting("wtled", "Standby LED Color",
1118
                              RadioSettingValueList(
1119
                                  COLOR_LIST, COLOR_LIST[_settings.wtled]))
1120
            basic.append(rs)
1121

    
1122
            rs = RadioSetting("rxled", "RX LED Color",
1123
                              RadioSettingValueList(
1124
                                  COLOR_LIST, COLOR_LIST[_settings.rxled]))
1125
            basic.append(rs)
1126

    
1127
            rs = RadioSetting("txled", "TX LED Color",
1128
                              RadioSettingValueList(
1129
                                  COLOR_LIST, COLOR_LIST[_settings.txled]))
1130
            basic.append(rs)
1131

    
1132
        if self.MODEL == "UV-82":
1133
            rs = RadioSetting("roger", "Roger Beep (TX)",
1134
                              RadioSettingValueBoolean(_settings.roger))
1135
            basic.append(rs)
1136
            rs = RadioSetting("rogerrx", "Roger Beep (RX)",
1137
                              RadioSettingValueList(
1138
                                  ROGERRX_LIST,
1139
                                  ROGERRX_LIST[_settings.rogerrx]))
1140
            basic.append(rs)
1141
        else:
1142
            rs = RadioSetting("roger", "Roger Beep",
1143
                              RadioSettingValueBoolean(_settings.roger))
1144
            basic.append(rs)
1145

    
1146
        rs = RadioSetting("ste", "Squelch Tail Eliminate (HT to HT)",
1147
                          RadioSettingValueBoolean(_settings.ste))
1148
        advanced.append(rs)
1149

    
1150
        rs = RadioSetting("rpste", "Squelch Tail Eliminate (repeater)",
1151
                          RadioSettingValueList(
1152
                              RPSTE_LIST, RPSTE_LIST[_settings.rpste]))
1153
        advanced.append(rs)
1154

    
1155
        rs = RadioSetting("rptrl", "STE Repeater Delay",
1156
                          RadioSettingValueList(
1157
                              STEDELAY_LIST, STEDELAY_LIST[_settings.rptrl]))
1158
        advanced.append(rs)
1159

    
1160
        if self.MODEL != "UV-6":
1161
            rs = RadioSetting("reset", "RESET Menu",
1162
                              RadioSettingValueBoolean(_settings.reset))
1163
            advanced.append(rs)
1164

    
1165
            rs = RadioSetting("menu", "All Menus",
1166
                              RadioSettingValueBoolean(_settings.menu))
1167
            advanced.append(rs)
1168

    
1169
        if self.MODEL == "F-11":
1170
            # this is an F-11 only feature
1171
            rs = RadioSetting("vfomrlock", "VFO/MR Button",
1172
                              RadioSettingValueBoolean(_settings.vfomrlock))
1173
            advanced.append(rs)
1174

    
1175
        if self.MODEL == "UV-82":
1176
            # this is a UV-82C only feature
1177
            rs = RadioSetting("vfomrlock", "VFO/MR Switching (UV-82C only)",
1178
                              RadioSettingValueBoolean(_settings.vfomrlock))
1179
            advanced.append(rs)
1180

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

    
1187
        if len(self._mmap.get_packed()) == 0x1808:
1188
            # Old image, without aux block
1189
            return group
1190

    
1191
        other = RadioSettingGroup("other", "Other Settings")
1192
        group.append(other)
1193

    
1194
        def _filter(name):
1195
            filtered = ""
1196
            for char in str(name):
1197
                if char in chirp_common.CHARSET_ASCII:
1198
                    filtered += char
1199
                else:
1200
                    filtered += " "
1201
            return filtered
1202

    
1203
        _msg = self._memobj.firmware_msg
1204
        val = RadioSettingValueString(0, 7, _filter(_msg.line1))
1205
        val.set_mutable(False)
1206
        rs = RadioSetting("firmware_msg.line1", "Firmware Message 1", val)
1207
        other.append(rs)
1208

    
1209
        val = RadioSettingValueString(0, 7, _filter(_msg.line2))
1210
        val.set_mutable(False)
1211
        rs = RadioSetting("firmware_msg.line2", "Firmware Message 2", val)
1212
        other.append(rs)
1213

    
1214
        if self.MODEL != "UV-6":
1215
            _msg = self._memobj.sixpoweron_msg
1216
            rs = RadioSetting("sixpoweron_msg.line1", "6+Power-On Message 1",
1217
                              RadioSettingValueString(
1218
                                  0, 7, _filter(_msg.line1)))
1219
            other.append(rs)
1220
            rs = RadioSetting("sixpoweron_msg.line2", "6+Power-On Message 2",
1221
                              RadioSettingValueString(
1222
                                  0, 7, _filter(_msg.line2)))
1223
            other.append(rs)
1224

    
1225
            _msg = self._memobj.poweron_msg
1226
            rs = RadioSetting("poweron_msg.line1", "Power-On Message 1",
1227
                              RadioSettingValueString(
1228
                                  0, 7, _filter(_msg.line1)))
1229
            other.append(rs)
1230
            rs = RadioSetting("poweron_msg.line2", "Power-On Message 2",
1231
                              RadioSettingValueString(
1232
                                  0, 7, _filter(_msg.line2)))
1233
            other.append(rs)
1234

    
1235
            rs = RadioSetting("ponmsg", "Power-On Message",
1236
                              RadioSettingValueList(
1237
                                  PONMSG_LIST, PONMSG_LIST[_settings.ponmsg]))
1238
            other.append(rs)
1239

    
1240
            if self._is_orig():
1241
                limit = "limits_old"
1242
            else:
1243
                limit = "limits_new"
1244

    
1245
            vhf_limit = getattr(self._memobj, limit).vhf
1246
            rs = RadioSetting("%s.vhf.lower" % limit, "VHF Lower Limit (MHz)",
1247
                              RadioSettingValueInteger(1, 1000,
1248
                                                       vhf_limit.lower))
1249
            other.append(rs)
1250

    
1251
            rs = RadioSetting("%s.vhf.upper" % limit, "VHF Upper Limit (MHz)",
1252
                              RadioSettingValueInteger(1, 1000,
1253
                                                       vhf_limit.upper))
1254
            other.append(rs)
1255

    
1256
            rs = RadioSetting("%s.vhf.enable" % limit, "VHF TX Enabled",
1257
                              RadioSettingValueBoolean(vhf_limit.enable))
1258
            other.append(rs)
1259

    
1260
            uhf_limit = getattr(self._memobj, limit).uhf
1261
            rs = RadioSetting("%s.uhf.lower" % limit, "UHF Lower Limit (MHz)",
1262
                              RadioSettingValueInteger(1, 1000,
1263
                                                       uhf_limit.lower))
1264
            other.append(rs)
1265
            rs = RadioSetting("%s.uhf.upper" % limit, "UHF Upper Limit (MHz)",
1266
                              RadioSettingValueInteger(1, 1000,
1267
                                                       uhf_limit.upper))
1268
            other.append(rs)
1269
            rs = RadioSetting("%s.uhf.enable" % limit, "UHF TX Enabled",
1270
                              RadioSettingValueBoolean(uhf_limit.enable))
1271
            other.append(rs)
1272

    
1273
        if self.MODEL != "UV-6":
1274
            workmode = RadioSettingGroup("workmode", "Work Mode Settings")
1275
            group.append(workmode)
1276

    
1277
            rs = RadioSetting("displayab", "Display",
1278
                              RadioSettingValueList(
1279
                                  AB_LIST, AB_LIST[_settings.displayab]))
1280
            workmode.append(rs)
1281

    
1282
            rs = RadioSetting("workmode", "VFO/MR Mode",
1283
                              RadioSettingValueList(
1284
                                  WORKMODE_LIST,
1285
                                  WORKMODE_LIST[_settings.workmode]))
1286
            workmode.append(rs)
1287

    
1288
            rs = RadioSetting("keylock", "Keypad Lock",
1289
                              RadioSettingValueBoolean(_settings.keylock))
1290
            workmode.append(rs)
1291

    
1292
            rs = RadioSetting("wmchannel.mrcha", "MR A Channel",
1293
                              RadioSettingValueInteger(0, 127,
1294
                                                       _wmchannel.mrcha))
1295
            workmode.append(rs)
1296

    
1297
            rs = RadioSetting("wmchannel.mrchb", "MR B Channel",
1298
                              RadioSettingValueInteger(0, 127,
1299
                                                       _wmchannel.mrchb))
1300
            workmode.append(rs)
1301

    
1302
            def convert_bytes_to_freq(bytes):
1303
                real_freq = 0
1304
                for byte in bytes:
1305
                    real_freq = (real_freq * 10) + byte
1306
                return chirp_common.format_freq(real_freq * 10)
1307

    
1308
            def my_validate(value):
1309
                value = chirp_common.parse_freq(value)
1310
                if 17400000 <= value and value < 40000000:
1311
                    msg = ("Can't be between 174.00000-400.00000")
1312
                    raise InvalidValueError(msg)
1313
                return chirp_common.format_freq(value)
1314

    
1315
            def apply_freq(setting, obj):
1316
                value = chirp_common.parse_freq(str(setting.value)) / 10
1317
                obj.band = value >= 40000000
1318
                for i in range(7, -1, -1):
1319
                    obj.freq[i] = value % 10
1320
                    value /= 10
1321

    
1322
            val1a = RadioSettingValueString(0, 10,
1323
                                            convert_bytes_to_freq(_vfoa.freq))
1324
            val1a.set_validate_callback(my_validate)
1325
            rs = RadioSetting("vfoa.freq", "VFO A Frequency", val1a)
1326
            rs.set_apply_callback(apply_freq, _vfoa)
1327
            workmode.append(rs)
1328

    
1329
            val1b = RadioSettingValueString(0, 10,
1330
                                            convert_bytes_to_freq(_vfob.freq))
1331
            val1b.set_validate_callback(my_validate)
1332
            rs = RadioSetting("vfob.freq", "VFO B Frequency", val1b)
1333
            rs.set_apply_callback(apply_freq, _vfob)
1334
            workmode.append(rs)
1335

    
1336
            rs = RadioSetting("vfoa.sftd", "VFO A Shift",
1337
                              RadioSettingValueList(
1338
                                  SHIFTD_LIST, SHIFTD_LIST[_vfoa.sftd]))
1339
            workmode.append(rs)
1340

    
1341
            rs = RadioSetting("vfob.sftd", "VFO B Shift",
1342
                              RadioSettingValueList(
1343
                                  SHIFTD_LIST, SHIFTD_LIST[_vfob.sftd]))
1344
            workmode.append(rs)
1345

    
1346
            def convert_bytes_to_offset(bytes):
1347
                real_offset = 0
1348
                for byte in bytes:
1349
                    real_offset = (real_offset * 10) + byte
1350
                return chirp_common.format_freq(real_offset * 10000)
1351

    
1352
            def apply_offset(setting, obj):
1353
                value = chirp_common.parse_freq(str(setting.value)) / 10000
1354
                for i in range(3, -1, -1):
1355
                    obj.offset[i] = value % 10
1356
                    value /= 10
1357

    
1358
            val1a = RadioSettingValueString(
1359
                        0, 10, convert_bytes_to_offset(_vfoa.offset))
1360
            rs = RadioSetting("vfoa.offset",
1361
                              "VFO A Offset (0.00-69.95)", val1a)
1362
            rs.set_apply_callback(apply_offset, _vfoa)
1363
            workmode.append(rs)
1364

    
1365
            val1b = RadioSettingValueString(
1366
                        0, 10, convert_bytes_to_offset(_vfob.offset))
1367
            rs = RadioSetting("vfob.offset",
1368
                              "VFO B Offset (0.00-69.95)", val1b)
1369
            rs.set_apply_callback(apply_offset, _vfob)
1370
            workmode.append(rs)
1371

    
1372
            if self.MODEL == "KT-980HP" or self.MODEL == "BF-F8HP":
1373
                rs = RadioSetting("vfoa.txpower3", "VFO A Power",
1374
                                  RadioSettingValueList(
1375
                                      TXPOWER3_LIST,
1376
                                      TXPOWER3_LIST[_vfoa.txpower3]))
1377
                workmode.append(rs)
1378

    
1379
                rs = RadioSetting("vfob.txpower3", "VFO B Power",
1380
                                  RadioSettingValueList(
1381
                                      TXPOWER3_LIST,
1382
                                      TXPOWER3_LIST[_vfob.txpower3]))
1383
                workmode.append(rs)
1384
            else:
1385
                rs = RadioSetting("vfoa.txpower", "VFO A Power",
1386
                                  RadioSettingValueList(
1387
                                      TXPOWER_LIST,
1388
                                      TXPOWER_LIST[_vfoa.txpower]))
1389
                workmode.append(rs)
1390

    
1391
                rs = RadioSetting("vfob.txpower", "VFO B Power",
1392
                                  RadioSettingValueList(
1393
                                      TXPOWER_LIST,
1394
                                      TXPOWER_LIST[_vfob.txpower]))
1395
                workmode.append(rs)
1396

    
1397
            rs = RadioSetting("vfoa.widenarr", "VFO A Bandwidth",
1398
                              RadioSettingValueList(
1399
                                  BANDWIDTH_LIST,
1400
                                  BANDWIDTH_LIST[_vfoa.widenarr]))
1401
            workmode.append(rs)
1402

    
1403
            rs = RadioSetting("vfob.widenarr", "VFO B Bandwidth",
1404
                              RadioSettingValueList(
1405
                                  BANDWIDTH_LIST,
1406
                                  BANDWIDTH_LIST[_vfob.widenarr]))
1407
            workmode.append(rs)
1408

    
1409
            rs = RadioSetting("vfoa.scode", "VFO A PTT-ID",
1410
                              RadioSettingValueList(
1411
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfoa.scode]))
1412
            workmode.append(rs)
1413

    
1414
            rs = RadioSetting("vfob.scode", "VFO B PTT-ID",
1415
                              RadioSettingValueList(
1416
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfob.scode]))
1417
            workmode.append(rs)
1418

    
1419
            if not self._is_orig():
1420
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1421
                                  RadioSettingValueList(
1422
                                      STEP291_LIST, STEP291_LIST[_vfoa.step]))
1423
                workmode.append(rs)
1424
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1425
                                  RadioSettingValueList(
1426
                                      STEP291_LIST, STEP291_LIST[_vfob.step]))
1427
                workmode.append(rs)
1428
            else:
1429
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1430
                                  RadioSettingValueList(
1431
                                      STEP_LIST, STEP_LIST[_vfoa.step]))
1432
                workmode.append(rs)
1433
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1434
                                  RadioSettingValueList(
1435
                                      STEP_LIST, STEP_LIST[_vfob.step]))
1436
                workmode.append(rs)
1437

    
1438
        fm_preset = RadioSettingGroup("fm_preset", "FM Radio Preset")
1439
        group.append(fm_preset)
1440

    
1441
        if self._memobj.fm_presets <= 116.1 * 10 - 650:
1442
            preset = self._memobj.fm_presets / 10.0 + 65
1443
        else:
1444
            preset = 76.0
1445
        rs = RadioSetting("fm_presets", "FM Preset(MHz)",
1446
                          RadioSettingValueFloat(65, 116.1, preset, 0.1, 1))
1447
        fm_preset.append(rs)
1448

    
1449
        dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
1450
        group.append(dtmf)
1451
        dtmfchars = "0123456789 *#ABCD"
1452

    
1453
        for i in range(0, 15):
1454
            _codeobj = self._memobj.pttid[i].code
1455
            _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1456
            val = RadioSettingValueString(0, 5, _code, False)
1457
            val.set_charset(dtmfchars)
1458
            rs = RadioSetting("pttid/%i.code" % i,
1459
                              "PTT ID Code %i" % (i + 1), val)
1460

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

    
1472
        _codeobj = self._memobj.ani.code
1473
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1474
        val = RadioSettingValueString(0, 5, _code, False)
1475
        val.set_charset(dtmfchars)
1476
        rs = RadioSetting("ani.code", "ANI Code", val)
1477

    
1478
        def apply_code(setting, obj):
1479
            code = []
1480
            for j in range(0, 5):
1481
                try:
1482
                    code.append(dtmfchars.index(str(setting.value)[j]))
1483
                except IndexError:
1484
                    code.append(0xFF)
1485
            obj.code = code
1486
        rs.set_apply_callback(apply_code, _ani)
1487
        dtmf.append(rs)
1488

    
1489
        rs = RadioSetting("ani.aniid", "ANI ID",
1490
                          RadioSettingValueList(PTTID_LIST,
1491
                                                PTTID_LIST[_ani.aniid]))
1492
        dtmf.append(rs)
1493

    
1494
        _codeobj = self._memobj.ani.alarmcode
1495
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1496
        val = RadioSettingValueString(0, 3, _code, False)
1497
        val.set_charset(dtmfchars)
1498
        rs = RadioSetting("ani.alarmcode", "Alarm Code", val)
1499

    
1500
        def apply_code(setting, obj):
1501
            alarmcode = []
1502
            for j in range(0, 3):
1503
                try:
1504
                    alarmcode.append(dtmfchars.index(str(setting.value)[j]))
1505
                except IndexError:
1506
                    alarmcode.append(0xFF)
1507
            obj.alarmcode = alarmcode
1508
        rs.set_apply_callback(apply_code, _ani)
1509
        dtmf.append(rs)
1510

    
1511
        rs = RadioSetting("dtmfst", "DTMF Sidetone",
1512
                          RadioSettingValueList(DTMFST_LIST,
1513
                                                DTMFST_LIST[_settings.dtmfst]))
1514
        dtmf.append(rs)
1515

    
1516
        if _ani.dtmfon > 0xC3:
1517
            val = 0x00
1518
        else:
1519
            val = _ani.dtmfon
1520
        rs = RadioSetting("ani.dtmfon", "DTMF Speed (on)",
1521
                          RadioSettingValueList(DTMFSPEED_LIST,
1522
                                                DTMFSPEED_LIST[val]))
1523
        dtmf.append(rs)
1524

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

    
1534
        if not self._my_version() < 291:
1535
            service = RadioSettingGroup("service", "Service Settings")
1536
            group.append(service)
1537

    
1538
            for band in ["vhf", "uhf"]:
1539
                for index in range(0, 10):
1540
                    key = "squelch_new.%s.sql%i" % (band, index)
1541
                    if band == "vhf":
1542
                        _obj = self._memobj.squelch_new.vhf
1543
                    elif band == "uhf":
1544
                        _obj = self._memobj.squelch_new.uhf
1545
                    name = "%s Squelch %i" % (band.upper(), index)
1546
                    rs = RadioSetting(key, name,
1547
                                      RadioSettingValueInteger(
1548
                                          0, 123,
1549
                                          getattr(_obj, "sql%i" % (index))))
1550
                    service.append(rs)
1551

    
1552
        return group
1553

    
1554
    def get_settings(self):
1555
        try:
1556
            return self._get_settings()
1557
        except:
1558
            import traceback
1559
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1560
            return None
1561

    
1562
    def set_settings(self, settings):
1563
        _settings = self._memobj.settings
1564
        for element in settings:
1565
            if not isinstance(element, RadioSetting):
1566
                if element.get_name() == "fm_preset":
1567
                    self._set_fm_preset(element)
1568
                else:
1569
                    self.set_settings(element)
1570
                    continue
1571
            else:
1572
                try:
1573
                    name = element.get_name()
1574
                    if "." in name:
1575
                        bits = name.split(".")
1576
                        obj = self._memobj
1577
                        for bit in bits[:-1]:
1578
                            if "/" in bit:
1579
                                bit, index = bit.split("/", 1)
1580
                                index = int(index)
1581
                                obj = getattr(obj, bit)[index]
1582
                            else:
1583
                                obj = getattr(obj, bit)
1584
                        setting = bits[-1]
1585
                    else:
1586
                        obj = _settings
1587
                        setting = element.get_name()
1588

    
1589
                    if element.has_apply_callback():
1590
                        LOG.debug("Using apply callback")
1591
                        element.run_apply_callback()
1592
                    else:
1593
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1594
                        setattr(obj, setting, element.value)
1595
                except Exception, e:
1596
                    LOG.debug(element.get_name())
1597
                    raise
1598

    
1599
    def _set_fm_preset(self, settings):
1600
        for element in settings:
1601
            try:
1602
                val = element.value
1603
                value = int(val.get_value() * 10 - 650)
1604
                LOG.debug("Setting fm_presets = %s" % (value))
1605
                self._memobj.fm_presets = value
1606
            except Exception, e:
1607
                LOG.debug(element.get_name())
1608
                raise
1609

    
1610

    
1611
@directory.register
1612
class BaofengF11Radio(BaofengUV5R):
1613
    VENDOR = "Baofeng"
1614
    MODEL = "F-11"
1615
    _basetype = BASETYPE_F11
1616
    _idents = [UV5R_MODEL_F11]
1617

    
1618
    def _is_orig(self):
1619
        # Override this for F11 to always return False
1620
        return False
1621

    
1622

    
1623
@directory.register
1624
class BaofengUV82Radio(BaofengUV5R):
1625
    MODEL = "UV-82"
1626
    _basetype = BASETYPE_UV82
1627
    _idents = [UV5R_MODEL_UV82]
1628
    _vhf_range = (130000000, 176000000)
1629
    _uhf_range = (400000000, 521000000)
1630

    
1631
    def _is_orig(self):
1632
        # Override this for UV82 to always return False
1633
        return False
1634

    
1635

    
1636
@directory.register
1637
class BaofengUV6Radio(BaofengUV5R):
1638
    """Baofeng UV-6/UV-7"""
1639
    VENDOR = "Baofeng"
1640
    MODEL = "UV-6"
1641
    _basetype = BASETYPE_UV6
1642
    _idents = [UV5R_MODEL_UV6,
1643
               UV5R_MODEL_UV6_ORIG
1644
               ]
1645

    
1646
    def get_features(self):
1647
        rf = BaofengUV5R.get_features(self)
1648
        rf.memory_bounds = (1, 128)
1649
        return rf
1650

    
1651
    def _get_mem(self, number):
1652
        return self._memobj.memory[number - 1]
1653

    
1654
    def _get_nam(self, number):
1655
        return self._memobj.names[number - 1]
1656

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

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

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

    
1667

    
1668
@directory.register
1669
class IntekKT980Radio(BaofengUV5R):
1670
    VENDOR = "Intek"
1671
    MODEL = "KT-980HP"
1672
    _basetype = BASETYPE_KT980HP
1673
    _idents = [UV5R_MODEL_291]
1674
    _vhf_range = (130000000, 180000000)
1675
    _uhf_range = (400000000, 521000000)
1676

    
1677
    def get_features(self):
1678
        rf = BaofengUV5R.get_features(self)
1679
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1680
        return rf
1681

    
1682
    def _is_orig(self):
1683
        # Override this for KT980HP to always return False
1684
        return False
1685

    
1686

    
1687
@directory.register
1688
class BaofengBFF8HPRadio(BaofengUV5R):
1689
    VENDOR = "Baofeng"
1690
    MODEL = "BF-F8HP"
1691
    _basetype = BASETYPE_F8HP
1692
    _idents = [UV5R_MODEL_291]
1693
    _vhf_range = (130000000, 180000000)
1694
    _uhf_range = (400000000, 521000000)
1695

    
1696
    def get_features(self):
1697
        rf = BaofengUV5R.get_features(self)
1698
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1699
        return rf
1700

    
1701
    def _is_orig(self):
1702
        # Override this for BFF8HP to always return False
1703
        return False
(1-1/4)