uv5r.py

Marcus van Dam, 08/07/2016 11:10 am

Download (55.5 kB)

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

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

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

    
29
LOG = logging.getLogger(__name__)
30

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

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

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

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

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

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

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

    
200
#seekto 0x0F56;
201
u16 fm_presets;
202

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

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

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

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

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

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

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

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

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

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

    
277
"""
278

    
279
# 0x1EC0 - 0x2000
280

    
281
vhf_220_radio = "\x02"
282

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

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

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

    
360

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

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

    
376

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

    
380

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

    
384

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

    
389

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

    
397

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

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

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

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

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

    
418
    serial.write("\x06")
419
    ack = serial.read(1)
420
    if ack != "\x06":
421
        raise errors.RadioError("Radio refused clone")
422

    
423
    return ident[:8]
424

    
425

    
426
def _read_block(radio, start, size, first_command=False):
427
    msg = struct.pack(">BHB", ord("S"), start, size)
428
    radio.pipe.write(msg)
429

    
430
    if first_command is False:
431
        ack = radio.pipe.read(1)
432
        if ack != "\x06":
433
            raise errors.RadioError(
434
                "Radio refused to send second block 0x%04x" % start)
435

    
436
    answer = radio.pipe.read(4)
437
    if len(answer) != 4:
438
        raise errors.RadioError("Radio refused to send block 0x%04x" % start)
439

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

    
446
    chunk = radio.pipe.read(0x40)
447
    if not chunk:
448
        raise errors.RadioError("Radio did not send block 0x%04x" % start)
449
    elif len(chunk) != size:
450
        LOG.error("Chunk length was 0x%04i" % len(chunk))
451
        raise errors.RadioError("Radio sent incomplete block 0x%04x" % start)
452

    
453
    radio.pipe.write("\x06")
454
    time.sleep(0.05)
455

    
456
    return chunk
457

    
458

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

    
470

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

    
485

    
486
def _do_download(radio):
487
    data = _ident_radio(radio)
488

    
489
    radio_version = _get_radio_firmware_version(radio)
490
    LOG.info("Radio Version is %s" % repr(radio_version))
491

    
492
    if not any(type in radio_version for type in radio._basetype):
493
        raise errors.RadioError("Incorrect 'Model' selected.")
494

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

    
509

    
510
def _send_block(radio, addr, data):
511
    msg = struct.pack(">BHB", ord("X"), addr, len(data))
512
    radio.pipe.write(msg + data)
513
    time.sleep(0.05)
514

    
515
    ack = radio.pipe.read(1)
516
    if ack != "\x06":
517
        raise errors.RadioError("Radio refused to accept block 0x%04x" % addr)
518

    
519

    
520
def _do_upload(radio):
521
    ident = _ident_radio(radio)
522
    radio_upper_band = ident[3:4]
523
    image_upper_band = _upper_band_from_image(radio)
524

    
525
    if image_upper_band == vhf_220_radio or radio_upper_band == vhf_220_radio:
526
        if image_upper_band != radio_upper_band:
527
            raise errors.RadioError("Image not supported by radio")
528

    
529
    image_version = _firmware_version_from_image(radio)
530
    radio_version = _get_radio_firmware_version(radio)
531
    LOG.info("Image Version is %s" % repr(image_version))
532
    LOG.info("Radio Version is %s" % repr(radio_version))
533

    
534
    if image_version != radio_version:
535
        msg = ("The upload was stopped because the firmware "
536
               "version of the image (%s) does not match that "
537
               "of the radio (%s).")
538
        raise errors.RadioError(msg % (image_version, radio_version))
539

    
540
    # Main block
541
    for i in range(0x08, 0x1808, 0x10):
542
        _send_block(radio, i - 0x08, radio.get_mmap()[i:i + 0x10])
543
        _do_status(radio, i)
544
    _do_status(radio, radio.get_memsize())
545

    
546
    if len(radio.get_mmap().get_packed()) == 0x1808:
547
        LOG.info("Old image, not writing aux block")
548
        return  # Old image, no aux block
549

    
550
    if image_version != radio_version:
551
        msg = ("Upload finished, but the 'Other Settings' "
552
               "could not be sent because the firmware "
553
               "version of the image (%s) does not match "
554
               "that of the radio (%s).")
555
        raise errors.RadioError(msg % (image_version, radio_version))
556

    
557
    # Auxiliary block at radio address 0x1EC0, our offset 0x1808
558
    for i in range(0x1EC0, 0x2000, 0x10):
559
        addr = 0x1808 + (i - 0x1EC0)
560
        _send_block(radio, i, radio.get_mmap()[addr:addr + 0x10])
561

    
562
UV5R_POWER_LEVELS = [chirp_common.PowerLevel("High", watts=4.00),
563
                     chirp_common.PowerLevel("Low",  watts=1.00)]
564

    
565
UV5R_POWER_LEVELS3 = [chirp_common.PowerLevel("High", watts=8.00),
566
                      chirp_common.PowerLevel("Med",  watts=4.00),
567
                      chirp_common.PowerLevel("Low",  watts=1.00)]
568

    
569
UV5R_DTCS = sorted(chirp_common.DTCS_CODES + [645])
570

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

    
574

    
575
class BaofengUV5R(chirp_common.CloneModeRadio,
576
                  chirp_common.ExperimentalRadio):
577
    """Baofeng UV-5R"""
578
    VENDOR = "Baofeng"
579
    MODEL = "UV-5R"
580
    BAUD_RATE = 9600
581

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

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

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

    
640
        normal_bands = [self._vhf_range, self._uhf_range]
641
        rax_bands = [self._vhf_range, self._220_range]
642

    
643
        if self._mmap is None:
644
            rf.valid_bands = [normal_bands[0], rax_bands[1], normal_bands[1]]
645
        elif not self._is_orig() and self._my_upper_band() == vhf_220_radio:
646
            rf.valid_bands = rax_bands
647
        else:
648
            rf.valid_bands = normal_bands
649
        rf.memory_bounds = (0, 127)
650
        return rf
651

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

    
668
    def process_mmap(self):
669
        self._memobj = bitwise.parse(MEM_FORMAT % self._mem_params, self._mmap)
670

    
671
    def sync_in(self):
672
        try:
673
            self._mmap = _do_download(self)
674
        except errors.RadioError:
675
            raise
676
        except Exception, e:
677
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
678
        self.process_mmap()
679

    
680
    def sync_out(self):
681
        try:
682
            _do_upload(self)
683
        except errors.RadioError:
684
            raise
685
        except Exception, e:
686
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
687

    
688
    def get_raw_memory(self, number):
689
        return repr(self._memobj.memory[number])
690

    
691
    def _is_txinh(self, _mem):
692
        raw_tx = ""
693
        for i in range(0, 4):
694
            raw_tx += _mem.txfreq[i].get_raw()
695
        return raw_tx == "\xFF\xFF\xFF\xFF"
696

    
697
    def _get_mem(self, number):
698
        return self._memobj.memory[number]
699

    
700
    def _get_nam(self, number):
701
        return self._memobj.names[number]
702

    
703
    def get_memory(self, number):
704
        _mem = self._get_mem(number)
705
        _nam = self._get_nam(number)
706

    
707
        mem = chirp_common.Memory()
708
        mem.number = number
709

    
710
        if _mem.get_raw()[0] == "\xff":
711
            mem.empty = True
712
            return mem
713

    
714
        mem.freq = int(_mem.rxfreq) * 10
715

    
716
        if self._is_txinh(_mem):
717
            mem.duplex = "off"
718
            mem.offset = 0
719
        elif int(_mem.rxfreq) == int(_mem.txfreq):
720
            mem.duplex = ""
721
            mem.offset = 0
722
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 70000000:
723
            mem.duplex = "split"
724
            mem.offset = int(_mem.txfreq) * 10
725
        else:
726
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
727
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
728

    
729
        for char in _nam.name:
730
            if str(char) == "\xFF":
731
                char = " "  # The UV-5R software may have 0xFF mid-name
732
            mem.name += str(char)
733
        mem.name = mem.name.rstrip()
734

    
735
        dtcs_pol = ["N", "N"]
736

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

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

    
769
        if txmode == "Tone" and not rxmode:
770
            mem.tmode = "Tone"
771
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
772
            mem.tmode = "TSQL"
773
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
774
            mem.tmode = "DTCS"
775
        elif rxmode or txmode:
776
            mem.tmode = "Cross"
777
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
778

    
779
        mem.dtcs_polarity = "".join(dtcs_pol)
780

    
781
        if not _mem.scan:
782
            mem.skip = "S"
783

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

    
795
        mem.mode = _mem.wide and "FM" or "NFM"
796

    
797
        mem.extra = RadioSettingGroup("Extra", "extra")
798

    
799
        rs = RadioSetting("bcl", "BCL",
800
                          RadioSettingValueBoolean(_mem.bcl))
801
        mem.extra.append(rs)
802

    
803
        rs = RadioSetting("pttid", "PTT ID",
804
                          RadioSettingValueList(PTTID_LIST,
805
                                                PTTID_LIST[_mem.pttid]))
806
        mem.extra.append(rs)
807

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

    
813
        return mem
814

    
815
    def _set_mem(self, number):
816
        return self._memobj.memory[number]
817

    
818
    def _set_nam(self, number):
819
        return self._memobj.names[number]
820

    
821
    def set_memory(self, mem):
822
        _mem = self._get_mem(mem.number)
823
        _nam = self._get_nam(mem.number)
824

    
825
        if mem.empty:
826
            _mem.set_raw("\xff" * 16)
827
            _nam.set_raw("\xff" * 16)
828
            return
829

    
830
        _mem.set_raw("\x00" * 16)
831

    
832
        _mem.rxfreq = mem.freq / 10
833

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

    
846
        _namelength = self.get_features().valid_name_length
847
        for i in range(_namelength):
848
            try:
849
                _nam.name[i] = mem.name[i]
850
            except IndexError:
851
                _nam.name[i] = "\xFF"
852

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

    
882
        if txmode == "DTCS" and mem.dtcs_polarity[0] == "R":
883
            _mem.txtone += 0x69
884
        if rxmode == "DTCS" and mem.dtcs_polarity[1] == "R":
885
            _mem.rxtone += 0x69
886

    
887
        _mem.scan = mem.skip != "S"
888
        _mem.wide = mem.mode == "FM"
889

    
890
        if mem.power:
891
            if self.MODEL in ("KT-980HP", "BF-F8HP", "UV-82HP"):
892
                levels = [str(l) for l in UV5R_POWER_LEVELS3]
893
                _mem.lowpower = levels.index(str(mem.power))
894
            else:
895
                _mem.lowpower = UV5R_POWER_LEVELS.index(mem.power)
896
        else:
897
            _mem.lowpower = 0
898

    
899
        for setting in mem.extra:
900
            setattr(_mem, setting.get_name(), setting.value)
901

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

    
916
    def _my_version(self):
917
        version_tag = _firmware_version_from_image(self)
918
        if 'BFB' in version_tag:
919
            idx = version_tag.index("BFB") + 3
920
            return int(version_tag[idx:idx + 3])
921

    
922
        raise Exception("Unrecognized firmware version string")
923

    
924
    def _my_upper_band(self):
925
        band_tag = _upper_band_from_image(self)
926
        return band_tag
927

    
928
    def _get_settings(self):
929
        _ani = self._memobj.ani
930
        _fm_presets = self._memobj.fm_presets
931
        _settings = self._memobj.settings
932
        _squelch = self._memobj.squelch_new
933
        _vfoa = self._memobj.vfoa
934
        _vfob = self._memobj.vfob
935
        _wmchannel = self._memobj.wmchannel
936
        basic = RadioSettingGroup("basic", "Basic Settings")
937
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
938

    
939
        group = RadioSettings(basic, advanced)
940

    
941
        rs = RadioSetting("squelch", "Carrier Squelch Level",
942
                          RadioSettingValueInteger(0, 9, _settings.squelch))
943
        basic.append(rs)
944

    
945
        rs = RadioSetting("save", "Battery Saver",
946
                          RadioSettingValueList(
947
                              SAVE_LIST, SAVE_LIST[_settings.save]))
948
        basic.append(rs)
949

    
950
        rs = RadioSetting("vox", "VOX Sensitivity",
951
                          RadioSettingValueList(
952
                              VOX_LIST, VOX_LIST[_settings.vox]))
953
        advanced.append(rs)
954

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

    
963
        if self.MODEL != "UV-6":
964
            rs = RadioSetting("abr", "Backlight Timeout",
965
                              RadioSettingValueInteger(0, 24, _settings.abr))
966
            basic.append(rs)
967

    
968
        rs = RadioSetting("tdr", "Dual Watch",
969
                          RadioSettingValueBoolean(_settings.tdr))
970
        advanced.append(rs)
971

    
972
        if self.MODEL == "UV-6":
973
            rs = RadioSetting("tdrch", "Dual Watch Channel",
974
                              RadioSettingValueList(
975
                                  TDRCH_LIST, TDRCH_LIST[_settings.tdrch]))
976
            advanced.append(rs)
977

    
978
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
979
                              RadioSettingValueBoolean(_settings.tdrab))
980
            advanced.append(rs)
981
        else:
982
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
983
                              RadioSettingValueList(
984
                                  TDRAB_LIST, TDRAB_LIST[_settings.tdrab]))
985
            advanced.append(rs)
986

    
987
        if self.MODEL == "UV-6":
988
            rs = RadioSetting("alarm", "Alarm Sound",
989
                              RadioSettingValueBoolean(_settings.alarm))
990
            advanced.append(rs)
991

    
992
        if _settings.almod > 0x02:
993
            val = 0x01
994
        else:
995
            val = _settings.almod
996
        rs = RadioSetting("almod", "Alarm Mode",
997
                          RadioSettingValueList(
998
                              ALMOD_LIST, ALMOD_LIST[val]))
999
        advanced.append(rs)
1000

    
1001
        rs = RadioSetting("beep", "Beep",
1002
                          RadioSettingValueBoolean(_settings.beep))
1003
        basic.append(rs)
1004

    
1005
        rs = RadioSetting("timeout", "Timeout Timer",
1006
                          RadioSettingValueList(
1007
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
1008
        basic.append(rs)
1009

    
1010
        if self._is_orig() and self._my_version() < 251:
1011
            rs = RadioSetting("voice", "Voice",
1012
                              RadioSettingValueBoolean(_settings.voice))
1013
            advanced.append(rs)
1014
        else:
1015
            rs = RadioSetting("voice", "Voice",
1016
                              RadioSettingValueList(
1017
                                  VOICE_LIST, VOICE_LIST[_settings.voice]))
1018
            advanced.append(rs)
1019

    
1020
        rs = RadioSetting("screv", "Scan Resume",
1021
                          RadioSettingValueList(
1022
                              RESUME_LIST, RESUME_LIST[_settings.screv]))
1023
        advanced.append(rs)
1024

    
1025
        if self.MODEL != "UV-6":
1026
            rs = RadioSetting("mdfa", "Display Mode (A)",
1027
                              RadioSettingValueList(
1028
                                  MODE_LIST, MODE_LIST[_settings.mdfa]))
1029
            basic.append(rs)
1030

    
1031
            rs = RadioSetting("mdfb", "Display Mode (B)",
1032
                              RadioSettingValueList(
1033
                                  MODE_LIST, MODE_LIST[_settings.mdfb]))
1034
            basic.append(rs)
1035

    
1036
        rs = RadioSetting("bcl", "Busy Channel Lockout",
1037
                          RadioSettingValueBoolean(_settings.bcl))
1038
        advanced.append(rs)
1039

    
1040
        if self.MODEL != "UV-6":
1041
            rs = RadioSetting("autolk", "Automatic Key Lock",
1042
                              RadioSettingValueBoolean(_settings.autolk))
1043
            advanced.append(rs)
1044

    
1045
        rs = RadioSetting("fmradio", "Broadcast FM Radio",
1046
                          RadioSettingValueBoolean(_settings.fmradio))
1047
        advanced.append(rs)
1048

    
1049
        if self.MODEL != "UV-6":
1050
            rs = RadioSetting("wtled", "Standby LED Color",
1051
                              RadioSettingValueList(
1052
                                  COLOR_LIST, COLOR_LIST[_settings.wtled]))
1053
            basic.append(rs)
1054

    
1055
            rs = RadioSetting("rxled", "RX LED Color",
1056
                              RadioSettingValueList(
1057
                                  COLOR_LIST, COLOR_LIST[_settings.rxled]))
1058
            basic.append(rs)
1059

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

    
1065
        if self.MODEL == "UV-82":
1066
            rs = RadioSetting("roger", "Roger Beep (TX)",
1067
                              RadioSettingValueBoolean(_settings.roger))
1068
            basic.append(rs)
1069
            rs = RadioSetting("rogerrx", "Roger Beep (RX)",
1070
                              RadioSettingValueList(
1071
                                  ROGERRX_LIST,
1072
                                  ROGERRX_LIST[_settings.rogerrx]))
1073
            basic.append(rs)
1074
        else:
1075
            rs = RadioSetting("roger", "Roger Beep",
1076
                              RadioSettingValueBoolean(_settings.roger))
1077
            basic.append(rs)
1078

    
1079
        rs = RadioSetting("ste", "Squelch Tail Eliminate (HT to HT)",
1080
                          RadioSettingValueBoolean(_settings.ste))
1081
        advanced.append(rs)
1082

    
1083
        rs = RadioSetting("rpste", "Squelch Tail Eliminate (repeater)",
1084
                          RadioSettingValueList(
1085
                              RPSTE_LIST, RPSTE_LIST[_settings.rpste]))
1086
        advanced.append(rs)
1087

    
1088
        rs = RadioSetting("rptrl", "STE Repeater Delay",
1089
                          RadioSettingValueList(
1090
                              STEDELAY_LIST, STEDELAY_LIST[_settings.rptrl]))
1091
        advanced.append(rs)
1092

    
1093
        if self.MODEL != "UV-6":
1094
            rs = RadioSetting("reset", "RESET Menu",
1095
                              RadioSettingValueBoolean(_settings.reset))
1096
            advanced.append(rs)
1097

    
1098
            rs = RadioSetting("menu", "All Menus",
1099
                              RadioSettingValueBoolean(_settings.menu))
1100
            advanced.append(rs)
1101

    
1102
        if self.MODEL == "F-11":
1103
            # this is an F-11 only feature
1104
            rs = RadioSetting("vfomrlock", "VFO/MR Button",
1105
                              RadioSettingValueBoolean(_settings.vfomrlock))
1106
            advanced.append(rs)
1107

    
1108
        if self.MODEL == "UV-82":
1109
            # this is a UV-82C only feature
1110
            rs = RadioSetting("vfomrlock", "VFO/MR Switching (UV-82C only)",
1111
                              RadioSettingValueBoolean(_settings.vfomrlock))
1112
            advanced.append(rs)
1113

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

    
1120
        if self.MODEL == "UV-82":
1121
            # this is an UV-82C only feature
1122
            rs = RadioSetting("singleptt", "Single PTT (UV-82C only)",
1123
                              RadioSettingValueBoolean(_settings.singleptt))
1124
            advanced.append(rs)
1125

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

    
1132
        if self.MODEL == "UV-82HP":
1133
            # this is an UV-82HP only feature
1134
            rs = RadioSetting("tdrch", "Tone Burst Frequency",
1135
                              RadioSettingValueList(
1136
                                  RTONE_LIST, RTONE_LIST[_settings.tdrch]))
1137
            advanced.append(rs)
1138

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1488
        rs = RadioSetting("pttlt", "PTT ID Delay",
1489
                          RadioSettingValueInteger(0, 30, _settings.pttlt))
1490
        dtmf.append(rs)
1491

    
1492
        if not self._is_orig():
1493
            service = RadioSettingGroup("service", "Service Settings")
1494
            group.append(service)
1495

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

    
1510
        return group
1511

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

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

    
1547
                    if element.has_apply_callback():
1548
                        LOG.debug("Using apply callback")
1549
                        element.run_apply_callback()
1550
                    elif element.value.get_mutable():
1551
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1552
                        setattr(obj, setting, element.value)
1553
                except Exception, e:
1554
                    LOG.debug(element.get_name())
1555
                    raise
1556

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

    
1571

    
1572
class UV5XAlias(chirp_common.Alias):
1573
    VENDOR = "Baofeng"
1574
    MODEL = "UV-5X"
1575

    
1576

    
1577
@directory.register
1578
class BaofengUV5RGeneric(BaofengUV5R):
1579
    ALIASES = [UV5XAlias]
1580

    
1581

    
1582
@directory.register
1583
class BaofengF11Radio(BaofengUV5R):
1584
    VENDOR = "Baofeng"
1585
    MODEL = "F-11"
1586
    _basetype = BASETYPE_F11
1587
    _idents = [UV5R_MODEL_F11]
1588

    
1589
    def _is_orig(self):
1590
        # Override this for F11 to always return False
1591
        return False
1592

    
1593

    
1594
@directory.register
1595
class BaofengUV82Radio(BaofengUV5R):
1596
    MODEL = "UV-82"
1597
    _basetype = BASETYPE_UV82
1598
    _idents = [UV5R_MODEL_UV82]
1599
    _vhf_range = (130000000, 176000000)
1600
    _uhf_range = (400000000, 521000000)
1601

    
1602
    def _is_orig(self):
1603
        # Override this for UV82 to always return False
1604
        return False
1605

    
1606

    
1607
@directory.register
1608
class BaofengUV6Radio(BaofengUV5R):
1609
    """Baofeng UV-6/UV-7"""
1610
    VENDOR = "Baofeng"
1611
    MODEL = "UV-6"
1612
    _basetype = BASETYPE_UV6
1613
    _idents = [UV5R_MODEL_UV6,
1614
               UV5R_MODEL_UV6_ORIG
1615
               ]
1616

    
1617
    def get_features(self):
1618
        rf = BaofengUV5R.get_features(self)
1619
        rf.memory_bounds = (1, 128)
1620
        return rf
1621

    
1622
    def _get_mem(self, number):
1623
        return self._memobj.memory[number - 1]
1624

    
1625
    def _get_nam(self, number):
1626
        return self._memobj.names[number - 1]
1627

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

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

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

    
1638

    
1639
@directory.register
1640
class IntekKT980Radio(BaofengUV5R):
1641
    VENDOR = "Intek"
1642
    MODEL = "KT-980HP"
1643
    _basetype = BASETYPE_KT980HP
1644
    _idents = [UV5R_MODEL_291]
1645
    _vhf_range = (130000000, 180000000)
1646
    _uhf_range = (400000000, 521000000)
1647

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

    
1653
    def _is_orig(self):
1654
        # Override this for KT980HP to always return False
1655
        return False
1656

    
1657

    
1658
@directory.register
1659
class BaofengBFF8HPRadio(BaofengUV5R):
1660
    VENDOR = "Baofeng"
1661
    MODEL = "BF-F8HP"
1662
    _basetype = BASETYPE_F8HP
1663
    _idents = [UV5R_MODEL_291,
1664
               UV5R_MODEL_A58
1665
               ]
1666
    _vhf_range = (130000000, 180000000)
1667
    _uhf_range = (400000000, 521000000)
1668

    
1669
    def get_features(self):
1670
        rf = BaofengUV5R.get_features(self)
1671
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1672
        return rf
1673

    
1674
    def _is_orig(self):
1675
        # Override this for BFF8HP to always return False
1676
        return False
1677

    
1678

    
1679
@directory.register
1680
class BaofengUV82HPRadio(BaofengUV5R):
1681
    VENDOR = "Baofeng"
1682
    MODEL = "UV-82HP"
1683
    _basetype = BASETYPE_UV82HP
1684
    _idents = [UV5R_MODEL_UV82]
1685
    _vhf_range = (136000000, 175000000)
1686
    _uhf_range = (400000000, 521000000)
1687

    
1688
    def get_features(self):
1689
        rf = BaofengUV5R.get_features(self)
1690
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1691
        return rf
1692

    
1693
    def _is_orig(self):
1694
        # Override this for UV82HP to always return False
1695
        return False