Project

General

Profile

Bug #3513 » uv5r_a58_test.py

Jim Unroe, 04/07/2016 05:45 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; // 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"]
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(8)
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
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
# Uncomment this to actually register this radio in CHIRP
576
@directory.register
577
class BaofengUV5R(chirp_common.CloneModeRadio,
578
                  chirp_common.ExperimentalRadio):
579
    """Baofeng UV-5R"""
580
    VENDOR = "Baofeng"
581
    MODEL = "UV-5R"
582
    BAUD_RATE = 9600
583

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

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

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

    
642
        normal_bands = [self._vhf_range, self._uhf_range]
643
        rax_bands = [self._vhf_range, self._220_range]
644

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

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

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

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

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

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

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

    
699
    def _get_mem(self, number):
700
        return self._memobj.memory[number]
701

    
702
    def _get_nam(self, number):
703
        return self._memobj.names[number]
704

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

    
709
        mem = chirp_common.Memory()
710
        mem.number = number
711

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

    
716
        mem.freq = int(_mem.rxfreq) * 10
717

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

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

    
737
        dtcs_pol = ["N", "N"]
738

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

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

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

    
781
        mem.dtcs_polarity = "".join(dtcs_pol)
782

    
783
        if not _mem.scan:
784
            mem.skip = "S"
785

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

    
797
        mem.mode = _mem.wide and "FM" or "NFM"
798

    
799
        mem.extra = RadioSettingGroup("Extra", "extra")
800

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

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

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

    
815
        return mem
816

    
817
    def _set_mem(self, number):
818
        return self._memobj.memory[number]
819

    
820
    def _set_nam(self, number):
821
        return self._memobj.names[number]
822

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

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

    
832
        _mem.set_raw("\x00" * 16)
833

    
834
        _mem.rxfreq = mem.freq / 10
835

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

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

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

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

    
889
        _mem.scan = mem.skip != "S"
890
        _mem.wide = mem.mode == "FM"
891

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

    
901
        for setting in mem.extra:
902
            setattr(_mem, setting.get_name(), setting.value)
903

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

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

    
924
        raise Exception("Unrecognized firmware version string")
925

    
926
    def _my_upper_band(self):
927
        band_tag = _upper_band_from_image(self)
928
        return band_tag
929

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

    
941
        group = RadioSettings(basic, advanced)
942

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1512
        return group
1513

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

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

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

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

    
1573

    
1574
@directory.register
1575
class BaofengF11Radio(BaofengUV5R):
1576
    VENDOR = "Baofeng"
1577
    MODEL = "F-11"
1578
    _basetype = BASETYPE_F11
1579
    _idents = [UV5R_MODEL_F11]
1580

    
1581
    def _is_orig(self):
1582
        # Override this for F11 to always return False
1583
        return False
1584

    
1585

    
1586
@directory.register
1587
class BaofengUV82Radio(BaofengUV5R):
1588
    MODEL = "UV-82"
1589
    _basetype = BASETYPE_UV82
1590
    _idents = [UV5R_MODEL_UV82]
1591
    _vhf_range = (130000000, 176000000)
1592
    _uhf_range = (400000000, 521000000)
1593

    
1594
    def _is_orig(self):
1595
        # Override this for UV82 to always return False
1596
        return False
1597

    
1598

    
1599
@directory.register
1600
class BaofengUV6Radio(BaofengUV5R):
1601
    """Baofeng UV-6/UV-7"""
1602
    VENDOR = "Baofeng"
1603
    MODEL = "UV-6"
1604
    _basetype = BASETYPE_UV6
1605
    _idents = [UV5R_MODEL_UV6,
1606
               UV5R_MODEL_UV6_ORIG
1607
               ]
1608

    
1609
    def get_features(self):
1610
        rf = BaofengUV5R.get_features(self)
1611
        rf.memory_bounds = (1, 128)
1612
        return rf
1613

    
1614
    def _get_mem(self, number):
1615
        return self._memobj.memory[number - 1]
1616

    
1617
    def _get_nam(self, number):
1618
        return self._memobj.names[number - 1]
1619

    
1620
    def _set_mem(self, number):
1621
        return self._memobj.memory[number - 1]
1622

    
1623
    def _set_nam(self, number):
1624
        return self._memobj.names[number - 1]
1625

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

    
1630

    
1631
@directory.register
1632
class IntekKT980Radio(BaofengUV5R):
1633
    VENDOR = "Intek"
1634
    MODEL = "KT-980HP"
1635
    _basetype = BASETYPE_KT980HP
1636
    _idents = [UV5R_MODEL_291]
1637
    _vhf_range = (130000000, 180000000)
1638
    _uhf_range = (400000000, 521000000)
1639

    
1640
    def get_features(self):
1641
        rf = BaofengUV5R.get_features(self)
1642
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1643
        return rf
1644

    
1645
    def _is_orig(self):
1646
        # Override this for KT980HP to always return False
1647
        return False
1648

    
1649

    
1650
@directory.register
1651
class BaofengBFF8HPRadio(BaofengUV5R):
1652
    VENDOR = "Baofeng"
1653
    MODEL = "BF-F8HP"
1654
    _basetype = BASETYPE_F8HP
1655
    _idents = [UV5R_MODEL_A58,
1656
               UV5R_MODEL_291
1657
               ]
1658
    _vhf_range = (130000000, 180000000)
1659
    _uhf_range = (400000000, 521000000)
1660

    
1661
    def get_features(self):
1662
        rf = BaofengUV5R.get_features(self)
1663
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1664
        return rf
1665

    
1666
    def _is_orig(self):
1667
        # Override this for BFF8HP to always return False
1668
        return False
1669

    
1670

    
1671
@directory.register
1672
class BaofengUV82HPRadio(BaofengUV5R):
1673
    VENDOR = "Baofeng"
1674
    MODEL = "UV-82HP"
1675
    _basetype = BASETYPE_UV82HP
1676
    _idents = [UV5R_MODEL_UV82]
1677
    _vhf_range = (136000000, 175000000)
1678
    _uhf_range = (400000000, 521000000)
1679

    
1680
    def get_features(self):
1681
        rf = BaofengUV5R.get_features(self)
1682
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1683
        return rf
1684

    
1685
    def _is_orig(self):
1686
        # Override this for UV82HP to always return False
1687
        return False
(3-3/4)