Project

General

Profile

New Model #2475 » uv5r.py

Jim Unroe, 04/08/2015 07:35 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", "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

    
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 is False:
450
        ack = radio.pipe.read(1)
451
        if ack != "\x06":
452
            raise errors.RadioError(
453
                "Radio refused to send second block 0x%04x" % start)
454

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

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

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

    
472
    radio.pipe.write("\x06")
473
    time.sleep(0.05)
474

    
475
    return chunk
476

    
477

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

    
489

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

    
495

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

    
510

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

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

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

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

    
534

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

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

    
544

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
606

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
847
        return mem
848

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

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

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

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

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

    
865
        _mem.rxfreq = mem.freq / 10
866

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

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

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

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

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

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

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

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

    
949
    def _my_version(self):
950
        version_tag = _firmware_version_from_image(self)
951
        if 'BFB' in version_tag:
952
            idx = version_tag.index("BFB") + 3
953
            return int(version_tag[idx:idx + 3])
954

    
955
        raise Exception("Unrecognized firmware version string")
956

    
957
        #if 'BFS' in version_tag:
958
        #    idx = version_tag.index("BFS") + 3
959
        #    return int(version_tag[idx:idx + 3])
960
        #elif 'BTS' in version_tag:
961
        #    idx = version_tag.index("BTS") + 3
962
        #    return int(version_tag[idx:idx + 3])
963
        #elif 'BF82' in version_tag:
964
        #    idx = version_tag.index("BF82") + 2
965
        #    return int(version_tag[idx:idx + 4])
966
        #elif 'B82S' in version_tag:
967
        #    idx = version_tag.index("B82S") + 4
968
        #    return int(version_tag[idx:idx + 2]) + 8200
969
        #elif 'US2S' in version_tag:
970
        #    idx = version_tag.index("US2S") + 4
971
        #    return int(version_tag[idx:idx + 2]) + 8200
972
        #elif 'USA' in version_tag:
973
        #    idx = version_tag.index("USA") + 3
974
        #    return int(version_tag[idx:idx + 3]) + 11000
975
        #elif 'BJ55' in version_tag:
976
        #    idx = version_tag.index("BJ55") + 2
977
        #    return int(version_tag[idx:idx + 4])
978
        #elif 'BF1' in version_tag:
979
        #    idx = version_tag.index("BF1") + 2
980
        #    return int(version_tag[idx:idx + 4])
981
        #elif 'BFP' in version_tag:
982
        #    idx = version_tag.index("BFP") + 5
983
        #    return int(version_tag[idx:idx + 1]) + 98000
984
        #elif 'N5R-2' in version_tag:
985
        #    idx = version_tag.index("N5R-2") + 4
986
        #    return int(version_tag[idx:idx + 2]) + 300
987
        #elif 'N5R-3' in version_tag:
988
        #    idx = version_tag.index("N5R-3") + 4
989
        #    return int(version_tag[idx:idx + 2]) + 98000
990
        #elif 'N5R3' in version_tag:
991
        #    idx = version_tag.index("N5R3") + 4
992
        #    return int(version_tag[idx:idx + 3]) + 98000
993
        #elif 'BFB' in version_tag:
994
        #    idx = version_tag.index("BFB") + 3
995
        #    return int(version_tag[idx:idx + 3])
996

    
997
        #raise Exception("Unrecognized firmware version string")
998

    
999
    def _my_upper_band(self):
1000
        band_tag = _upper_band_from_image(self)
1001
        return band_tag
1002

    
1003
    def _get_settings(self):
1004
        _ani = self._memobj.ani
1005
        _settings = self._memobj.settings
1006
        _squelch = self._memobj.squelch_new
1007
        _vfoa = self._memobj.vfoa
1008
        _vfob = self._memobj.vfob
1009
        _wmchannel = self._memobj.wmchannel
1010
        basic = RadioSettingGroup("basic", "Basic Settings")
1011
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
1012

    
1013
        group = RadioSettings(basic, advanced)
1014

    
1015
        rs = RadioSetting("squelch", "Carrier Squelch Level",
1016
                          RadioSettingValueInteger(0, 9, _settings.squelch))
1017
        basic.append(rs)
1018

    
1019
        rs = RadioSetting("save", "Battery Saver",
1020
                          RadioSettingValueList(
1021
                              SAVE_LIST, SAVE_LIST[_settings.save]))
1022
        basic.append(rs)
1023

    
1024
        rs = RadioSetting("vox", "VOX Sensitivity",
1025
                          RadioSettingValueList(
1026
                              VOX_LIST, VOX_LIST[_settings.vox]))
1027
        advanced.append(rs)
1028

    
1029
        if self.MODEL == "UV-6":
1030
            # NOTE: The UV-6 calls this byte voxenable, but the UV-5R calls it
1031
            # autolk. Since this is a minor difference, it will be referred to
1032
            # by the wrong name for the UV-6.
1033
            rs = RadioSetting("autolk", "Vox",
1034
                              RadioSettingValueBoolean(_settings.autolk))
1035
            advanced.append(rs)
1036

    
1037
        if self.MODEL != "UV-6":
1038
            rs = RadioSetting("abr", "Backlight Timeout",
1039
                              RadioSettingValueInteger(0, 24, _settings.abr))
1040
            basic.append(rs)
1041

    
1042
        rs = RadioSetting("tdr", "Dual Watch",
1043
                          RadioSettingValueBoolean(_settings.tdr))
1044
        advanced.append(rs)
1045

    
1046
        if self.MODEL == "UV-6":
1047
            rs = RadioSetting("tdrch", "Dual Watch Channel",
1048
                              RadioSettingValueList(
1049
                                  TDRCH_LIST, TDRCH_LIST[_settings.tdrch]))
1050
            advanced.append(rs)
1051

    
1052
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1053
                              RadioSettingValueBoolean(_settings.tdrab))
1054
            advanced.append(rs)
1055
        else:
1056
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1057
                              RadioSettingValueList(
1058
                                  TDRAB_LIST, TDRAB_LIST[_settings.tdrab]))
1059
            advanced.append(rs)
1060

    
1061
        if self.MODEL == "UV-6":
1062
            rs = RadioSetting("alarm", "Alarm Sound",
1063
                              RadioSettingValueBoolean(_settings.alarm))
1064
            advanced.append(rs)
1065

    
1066
        if _settings.almod > 0x02:
1067
            val = 0x01
1068
        else:
1069
            val = _settings.almod
1070
        rs = RadioSetting("almod", "Alarm Mode",
1071
                          RadioSettingValueList(
1072
                              ALMOD_LIST, ALMOD_LIST[val]))
1073
        advanced.append(rs)
1074

    
1075
        rs = RadioSetting("beep", "Beep",
1076
                          RadioSettingValueBoolean(_settings.beep))
1077
        basic.append(rs)
1078

    
1079
        rs = RadioSetting("timeout", "Timeout Timer",
1080
                          RadioSettingValueList(
1081
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
1082
        basic.append(rs)
1083

    
1084
        if self._is_orig() and self._my_version() < 251:
1085
            rs = RadioSetting("voice", "Voice",
1086
                              RadioSettingValueBoolean(_settings.voice))
1087
            advanced.append(rs)
1088
        else:
1089
            rs = RadioSetting("voice", "Voice",
1090
                              RadioSettingValueList(
1091
                                  VOICE_LIST, VOICE_LIST[_settings.voice]))
1092
            advanced.append(rs)
1093

    
1094
        rs = RadioSetting("screv", "Scan Resume",
1095
                          RadioSettingValueList(
1096
                              RESUME_LIST, RESUME_LIST[_settings.screv]))
1097
        advanced.append(rs)
1098

    
1099
        if self.MODEL != "UV-6":
1100
            rs = RadioSetting("mdfa", "Display Mode (A)",
1101
                              RadioSettingValueList(
1102
                                  MODE_LIST, MODE_LIST[_settings.mdfa]))
1103
            basic.append(rs)
1104

    
1105
            rs = RadioSetting("mdfb", "Display Mode (B)",
1106
                              RadioSettingValueList(
1107
                                  MODE_LIST, MODE_LIST[_settings.mdfb]))
1108
            basic.append(rs)
1109

    
1110
        rs = RadioSetting("bcl", "Busy Channel Lockout",
1111
                          RadioSettingValueBoolean(_settings.bcl))
1112
        advanced.append(rs)
1113

    
1114
        if self.MODEL != "UV-6":
1115
            rs = RadioSetting("autolk", "Automatic Key Lock",
1116
                              RadioSettingValueBoolean(_settings.autolk))
1117
            advanced.append(rs)
1118

    
1119
        rs = RadioSetting("fmradio", "Broadcast FM Radio",
1120
                          RadioSettingValueBoolean(_settings.fmradio))
1121
        advanced.append(rs)
1122

    
1123
        if self.MODEL != "UV-6":
1124
            rs = RadioSetting("wtled", "Standby LED Color",
1125
                              RadioSettingValueList(
1126
                                  COLOR_LIST, COLOR_LIST[_settings.wtled]))
1127
            basic.append(rs)
1128

    
1129
            rs = RadioSetting("rxled", "RX LED Color",
1130
                              RadioSettingValueList(
1131
                                  COLOR_LIST, COLOR_LIST[_settings.rxled]))
1132
            basic.append(rs)
1133

    
1134
            rs = RadioSetting("txled", "TX LED Color",
1135
                              RadioSettingValueList(
1136
                                  COLOR_LIST, COLOR_LIST[_settings.txled]))
1137
            basic.append(rs)
1138

    
1139
        if self.MODEL == "UV-82":
1140
            rs = RadioSetting("roger", "Roger Beep (TX)",
1141
                              RadioSettingValueBoolean(_settings.roger))
1142
            basic.append(rs)
1143
            rs = RadioSetting("rogerrx", "Roger Beep (RX)",
1144
                              RadioSettingValueList(
1145
                                  ROGERRX_LIST,
1146
                                  ROGERRX_LIST[_settings.rogerrx]))
1147
            basic.append(rs)
1148
        else:
1149
            rs = RadioSetting("roger", "Roger Beep",
1150
                              RadioSettingValueBoolean(_settings.roger))
1151
            basic.append(rs)
1152

    
1153
        rs = RadioSetting("ste", "Squelch Tail Eliminate (HT to HT)",
1154
                          RadioSettingValueBoolean(_settings.ste))
1155
        advanced.append(rs)
1156

    
1157
        rs = RadioSetting("rpste", "Squelch Tail Eliminate (repeater)",
1158
                          RadioSettingValueList(
1159
                              RPSTE_LIST, RPSTE_LIST[_settings.rpste]))
1160
        advanced.append(rs)
1161

    
1162
        rs = RadioSetting("rptrl", "STE Repeater Delay",
1163
                          RadioSettingValueList(
1164
                              STEDELAY_LIST, STEDELAY_LIST[_settings.rptrl]))
1165
        advanced.append(rs)
1166

    
1167
        if self.MODEL != "UV-6":
1168
            rs = RadioSetting("reset", "RESET Menu",
1169
                              RadioSettingValueBoolean(_settings.reset))
1170
            advanced.append(rs)
1171

    
1172
            rs = RadioSetting("menu", "All Menus",
1173
                              RadioSettingValueBoolean(_settings.menu))
1174
            advanced.append(rs)
1175

    
1176
        if self.MODEL == "F-11":
1177
            # this is an F-11 only feature
1178
            rs = RadioSetting("vfomrlock", "VFO/MR Button",
1179
                              RadioSettingValueBoolean(_settings.vfomrlock))
1180
            advanced.append(rs)
1181

    
1182
        if self.MODEL == "UV-82":
1183
            # this is a UV-82C only feature
1184
            rs = RadioSetting("vfomrlock", "VFO/MR Switching (UV-82C only)",
1185
                              RadioSettingValueBoolean(_settings.vfomrlock))
1186
            advanced.append(rs)
1187

    
1188
        if self.MODEL == "UV-82":
1189
            # this is an UV-82C only feature
1190
            rs = RadioSetting("singleptt", "Single PTT (UV-82C only)",
1191
                              RadioSettingValueBoolean(_settings.singleptt))
1192
            advanced.append(rs)
1193

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1448
        if self._memobj.fm_presets <= 116.1 * 10 - 650:
1449
            preset = self._memobj.fm_presets / 10.0 + 65
1450
        else:
1451
            preset = 76.0
1452
        rs = RadioSetting("fm_presets", "FM Preset(MHz)",
1453
                          RadioSettingValueFloat(65, 116.1, preset, 0.1, 1))
1454
        fm_preset.append(rs)
1455

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

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

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

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

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

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

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

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

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

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

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

    
1541
        if not self._is_orig():
1542
            service = RadioSettingGroup("service", "Service Settings")
1543
            group.append(service)
1544

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

    
1559
        return group
1560

    
1561
    def get_settings(self):
1562
        try:
1563
            return self._get_settings()
1564
        except:
1565
            import traceback
1566
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1567
            return None
1568

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

    
1596
                    if element.has_apply_callback():
1597
                        LOG.debug("Using apply callback")
1598
                        element.run_apply_callback()
1599
                    else:
1600
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1601
                        setattr(obj, setting, element.value)
1602
                except Exception, e:
1603
                    LOG.debug(element.get_name())
1604
                    raise
1605

    
1606
    def _set_fm_preset(self, settings):
1607
        for element in settings:
1608
            try:
1609
                val = element.value
1610
                value = int(val.get_value() * 10 - 650)
1611
                LOG.debug("Setting fm_presets = %s" % (value))
1612
                self._memobj.fm_presets = value
1613
            except Exception, e:
1614
                LOG.debug(element.get_name())
1615
                raise
1616

    
1617

    
1618
@directory.register
1619
class BaofengF11Radio(BaofengUV5R):
1620
    VENDOR = "Baofeng"
1621
    MODEL = "F-11"
1622
    _basetype = BASETYPE_F11
1623
    _idents = [UV5R_MODEL_F11]
1624

    
1625
    def _is_orig(self):
1626
        # Override this for F11 to always return False
1627
        return False
1628

    
1629

    
1630
@directory.register
1631
class BaofengUV82Radio(BaofengUV5R):
1632
    MODEL = "UV-82"
1633
    _basetype = BASETYPE_UV82
1634
    _idents = [UV5R_MODEL_UV82]
1635
    _vhf_range = (130000000, 176000000)
1636
    _uhf_range = (400000000, 521000000)
1637

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

    
1642

    
1643
@directory.register
1644
class BaofengUV6Radio(BaofengUV5R):
1645
    """Baofeng UV-6/UV-7"""
1646
    VENDOR = "Baofeng"
1647
    MODEL = "UV-6"
1648
    _basetype = BASETYPE_UV6
1649
    _idents = [UV5R_MODEL_UV6,
1650
               UV5R_MODEL_UV6_ORIG
1651
               ]
1652

    
1653
    def get_features(self):
1654
        rf = BaofengUV5R.get_features(self)
1655
        rf.memory_bounds = (1, 128)
1656
        return rf
1657

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

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

    
1664
    def _set_mem(self, number):
1665
        return self._memobj.memory[number - 1]
1666

    
1667
    def _set_nam(self, number):
1668
        return self._memobj.names[number - 1]
1669

    
1670
    def _is_orig(self):
1671
        # Override this for UV6 to always return False
1672
        return False
1673

    
1674

    
1675
@directory.register
1676
class IntekKT980Radio(BaofengUV5R):
1677
    VENDOR = "Intek"
1678
    MODEL = "KT-980HP"
1679
    _basetype = BASETYPE_KT980HP
1680
    _idents = [UV5R_MODEL_291]
1681
    _vhf_range = (130000000, 180000000)
1682
    _uhf_range = (400000000, 521000000)
1683

    
1684
    def get_features(self):
1685
        rf = BaofengUV5R.get_features(self)
1686
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1687
        return rf
1688

    
1689
    def _is_orig(self):
1690
        # Override this for KT980HP to always return False
1691
        return False
1692

    
1693

    
1694
@directory.register
1695
class BaofengBFF8HPRadio(BaofengUV5R):
1696
    VENDOR = "Baofeng"
1697
    MODEL = "BF-F8HP"
1698
    _basetype = BASETYPE_F8HP
1699
    _idents = [UV5R_MODEL_291]
1700
    _vhf_range = (130000000, 180000000)
1701
    _uhf_range = (400000000, 521000000)
1702

    
1703
    def get_features(self):
1704
        rf = BaofengUV5R.get_features(self)
1705
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1706
        return rf
1707

    
1708
    def _is_orig(self):
1709
        # Override this for BFF8HP to always return False
1710
        return False
(3-3/9)