Project

General

Profile

New Model #2261 » uv5r.py

Test driver for reading the BF-A58 - Jim Unroe, 05/30/2015 05:09 PM

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

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

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

    
29
LOG = logging.getLogger(__name__)
30

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

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

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

    
86
#seekto 0x0E28;
87
struct {
88
  u8 squelch;
89
  u8 step;
90
  u8 unknown1;
91
  u8 save;
92
  u8 vox;
93
  u8 unknown2;
94
  u8 abr;
95
  u8 tdr;
96
  u8 beep;
97
  u8 timeout;
98
  u8 unknown3[4];
99
  u8 voice;
100
  u8 unknown4;
101
  u8 dtmfst;
102
  u8 unknown5;
103
  u8 unknown12:6,
104
     screv:2;
105
  u8 pttid;
106
  u8 pttlt;
107
  u8 mdfa;
108
  u8 mdfb;
109
  u8 bcl;
110
  u8 autolk; // NOTE: The UV-6 calls this byte voxenable, but the UV-5R
111
             // calls it autolk. Since this is a minor difference, it will
112
             // be referred to by the wrong name for the UV-6.
113
  u8 sftd;
114
  u8 unknown6[3];
115
  u8 wtled;
116
  u8 rxled;
117
  u8 txled;
118
  u8 almod;
119
  u8 band;
120
  u8 tdrab;
121
  u8 ste;
122
  u8 rpste;
123
  u8 rptrl;
124
  u8 ponmsg;
125
  u8 roger;
126
  u8 rogerrx;
127
  u8 tdrch;
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", "F5R3"]
288
BASETYPE_LIST = BASETYPE_UV5R + BASETYPE_F11 + BASETYPE_UV82 + \
289
                BASETYPE_BJ55 + BASETYPE_UV6 + BASETYPE_KT980HP + \
290
                BASETYPE_F8HP
291

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

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

    
355

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

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

    
371

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

    
375

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

    
379

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

    
384

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

    
392

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

    
397

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

    
403

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

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

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

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

    
422
    LOG.info("Ident: %s" % util.hexprint(ident))
423

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

    
429
    return ident
430

    
431

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

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

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

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

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

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

    
462
    return chunk
463

    
464

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

    
476

    
477
def _get_radio_special_block(radio):
478
    block = _read_block(radio, 0xCF0, 0x40, False)
479
    special_block = block[2:9]
480
    return special_block
481

    
482

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

    
497

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

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

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

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

    
521

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

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

    
531

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
595

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

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

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

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

    
664
        normal_bands = [self._vhf_range, self._uhf_range]
665
        rax_bands = [self._vhf_range, self._220_range]
666

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

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

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

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

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

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

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

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

    
724
    def _get_nam(self, number):
725
        return self._memobj.names[number]
726

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

    
731
        mem = chirp_common.Memory()
732
        mem.number = number
733

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

    
738
        mem.freq = int(_mem.rxfreq) * 10
739

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

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

    
759
        dtcs_pol = ["N", "N"]
760

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

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

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

    
803
        mem.dtcs_polarity = "".join(dtcs_pol)
804

    
805
        if not _mem.scan:
806
            mem.skip = "S"
807

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

    
819
        mem.mode = _mem.wide and "FM" or "NFM"
820

    
821
        mem.extra = RadioSettingGroup("Extra", "extra")
822

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

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

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

    
837
        return mem
838

    
839
    def _set_mem(self, number):
840
        return self._memobj.memory[number]
841

    
842
    def _set_nam(self, number):
843
        return self._memobj.names[number]
844

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

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

    
853
        _mem.set_raw("\x00" * 16)
854

    
855
        _mem.rxfreq = mem.freq / 10
856

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

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

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

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

    
910
        _mem.scan = mem.skip != "S"
911
        _mem.wide = mem.mode == "FM"
912

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

    
922
        for setting in mem.extra:
923
            setattr(_mem, setting.get_name(), setting.value)
924

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

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

    
945
        raise Exception("Unrecognized firmware version string")
946

    
947
    def _my_upper_band(self):
948
        band_tag = _upper_band_from_image(self)
949
        return band_tag
950

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

    
961
        group = RadioSettings(basic, advanced)
962

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1146
        other = RadioSettingGroup("other", "Other Settings")
1147
        group.append(other)
1148

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1393
        fm_preset = RadioSettingGroup("fm_preset", "FM Radio Preset")
1394
        group.append(fm_preset)
1395

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1507
        return group
1508

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

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

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

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

    
1565

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

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

    
1577

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

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

    
1590

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

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

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

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

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

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

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

    
1622

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

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

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

    
1641

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

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

    
1656
    def _is_orig(self):
1657
        # Override this for BFF8HP to always return False
1658
        return False
(1-1/7)