Project

General

Profile

New Model #6129 » uv5r.py

Bad Job, 10/13/2018 11:18 AM

 
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 = ["US2S2", "B82S", "BF82", "N82-2", "N822"]
286
BASETYPE_BJ55 = ["BJ55"]  # needed for for the Baojie UV-55 in bjuv55.py
287
BASETYPE_UV6 = ["BF1", "UV6"]
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
QUANSHENG = "\x4B\x6B\x4E\x48\x53\x47\x30\x4E\x02"
369
UV5R_MODEL_291 = "\x4B\x6B\x4E\x48\x53\x47\x30\x4E\x02"
370
UV5R_MODEL_ORIG = "\x4B\x6B\x4E\x48\x53\x47\x30\x4E\x02"
371
UV5R_MODEL_F11 = "\x4B\x6B\x4E\x48\x53\x47\x30\x4E\x02"
372
UV5R_MODEL_UV82 = "\x4B\x6B\x4E\x48\x53\x47\x30\x4E\x02"
373
UV5R_MODEL_UV6 = "\x4B\x6B\x4E\x48\x53\x47\x30\x4E\x02"
374
UV5R_MODEL_UV6_ORIG = "\x4B\x6B\x4E\x48\x53\x47\x30\x4E\x02"
375
UV5R_MODEL_A58 = "\x4B\x6B\x4E\x48\x53\x47\x30\x4E\x02"
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, secondack=True):
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

    
415
    # Until recently, the "ident" returned by the radios supported by this
416
    # driver have always been 8 bytes long. The image sturcture is the 8 byte
417
    # "ident" followed by the downloaded memory data. So all of the settings
418
    # structures are offset by 8 bytes. The ident returned from a UV-6 radio
419
    # can be 8 bytes (original model) or now 12 bytes.
420
    #
421
    # To accomodate this, the "ident" is now read one byte at a time until the
422
    # last byte ("\xdd") is encountered. The bytes containing the value "\x01"
423
    # are discarded to shrink the "ident" length down to 8 bytes to keep the
424
    # image data aligned with the existing settings structures.
425

    
426
    # Ok, get the response
427
    response = ""
428
    for i in range(1, 20):
429
        byte = serial.read(1)
430
        response += byte
431
        # stop reading once the last byte ("\xdd") is encountered
432
        if byte == "\xf8":
433
            break
434

    
435
    # check if response is OK
436
    #if len(response) in [6, 20]:
437
    #    # DEBUG
438
    #    LOG.info("Valid response, got this:")
439
    #    LOG.debug(util.hexprint(response))
440
    ident = response
441
    #else:
442
    #    # bad response
443
     #   msg = "Unexpected response, got this:"
444
    #    msg += util.hexprint(response)
445
    #    LOG.debug(msg)
446
    #    raise errors.RadioError("Unexpected response from radio.")
447

    
448
    if secondack:
449
        serial.write("\x06")
450
        ack = serial.read(1)
451
        if ack != "\x06":
452
            raise errors.RadioError("Radio refused clone")
453

    
454
    return ident
455

    
456

    
457
def _read_block(radio, start, size, first_command=False):
458
    msg = struct.pack(">BHB", ord("R"), start, size)
459
    radio.pipe.write(msg)
460

    
461
   # if first_command is False:
462
      #  ack = radio.pipe.read(1)
463
       # if ack != "\x06":
464
       #     raise errors.RadioError(
465
       #         "Radio refused to send second block 0x%04x" % start)
466

    
467
    answer = radio.pipe.read(4)
468
    if len(answer) != 4:
469
        raise errors.RadioError("Radio refused to send block 0x%04x" % start)
470

    
471
    cmd, addr, length = struct.unpack(">BHB", answer)
472
    if cmd != ord("W") or addr != start or length != size:
473
        LOG.error("Invalid answer for block 0x%04x:" % start)
474
        LOG.debug("CMD: %s  ADDR: %04x  SIZE: %02x" % (cmd, addr, length))
475
        raise errors.RadioError("Unknown response from radio")
476

    
477
    chunk = radio.pipe.read(0x40)
478
    if not chunk:
479
        raise errors.RadioError("Radio did not send block 0x%04x" % start)
480
    elif len(chunk) != size:
481
        LOG.error("Chunk length was 0x%04i" % len(chunk))
482
        raise errors.RadioError("Radio sent incomplete block 0x%04x" % start)
483

    
484
    radio.pipe.write("\x06")
485
    time.sleep(0.05)
486
	#Peel off the secondary ACK.
487
    ack = radio.pipe.read(1)
488
    return chunk
489

    
490

    
491
def _get_radio_firmware_version(radio):
492
    #if radio.MODEL == "BJ-UV55":
493
    #block = _read_block(radio, 0x1FF0, 0x40, True)
494
    #version = block[0:6]
495
    #else:
496
   #     block1 = _read_block(radio, 0x1EC0, 0x40, True)
497
   #     block2 = _read_block(radio, 0x1F00, 0x40, False)
498
  #      block = block1 + block2
499
    #    version = block[48:62]
500
    #return version
501
    return 0;
502

    
503
IDENT_BLACKLIST = {
504
    "\x50\x0D\x0C\x20\x16\x03\x28": "Radio identifies as BTECH UV-5X3",
505
}
506

    
507

    
508
def _ident_radio(radio):
509
    for magic in radio._idents:
510
        error = None
511
        try:
512
            data = _do_ident(radio, magic)
513
            return data
514
        except errors.RadioError, e:
515
            LOG.error("uv5r._ident_radio: %s", e)
516
            error = e
517
            time.sleep(2)
518

    
519
    #for magic, reason in IDENT_BLACKLIST.items():
520
     #   try:
521
     #       _do_ident(radio, magic, secondack=False)
522
     #   except errors.RadioError as e:
523
            # No match, try the next one
524
     #       continue
525

    
526
        # If we got here, it means we identified the radio as
527
        # something other than one of our valid idents. Warn
528
        # the user so they can do the right thing.
529
    #    LOG.warning(('Identified radio as a blacklisted model '
530
    #                 '(details: %s)') % reason)
531
    #    raise errors.RadioError(('%s. Please choose the proper vendor/'
532
     #                            'model and try again.') % reason)
533

    
534
    if error:
535
        raise error
536
    raise errors.RadioError("Radio did not respond")
537

    
538

    
539
def _do_download(radio):
540
    data = _ident_radio(radio)
541

    
542
    radio_version = _get_radio_firmware_version(radio)
543
    LOG.info("Radio Version is %s" % repr(radio_version))
544

    
545
   # if "HN5RV" in radio_version:
546
        # A radio with HN5RV firmware has been detected. It could be a
547
        # UV-5R style radio with HIGH/LOW power levels or it could be a
548
        # BF-F8HP style radio with HIGH/MID/LOW power levels.
549
        # We are going to count on the user to make the right choice and
550
        # then append that model type to the end of the image so it can
551
        # be properly detected when loaded.
552
  #      append_model = True
553
 #   elif "\xFF" * 14 in radio_version:
554
        # A radio UV-5R style radio that reports no firmware version has
555
        # been detected.
556
        # We are going to count on the user to make the right choice and
557
        # then append that model type to the end of the image so it can
558
        # be properly detected when loaded.
559
   #     append_model = True
560
  #  elif not any(type in radio_version for type in radio._basetype):
561
        # This radio can't be properly detected by parsing its firmware
562
        # version.
563
  #      raise errors.RadioError("Incorrect 'Model' selected.")
564
  #  else:
565
        # This radio can be properly detected by parsing its firmware version.
566
        # There is no need to append its model type to the end of the image.
567
    append_model = False
568

    
569
    # Main block
570
    LOG.debug("downloading main block...")
571
    for i in range(0, 0x1800, 0x40):
572
        data += _read_block(radio, i, 0x40, False)
573
        _do_status(radio, i)
574
    #_do_status(radio, radio.get_memsize())
575
    LOG.debug("done.")
576
    LOG.debug("downloading aux block...")
577
    # Auxiliary block starts at 0x1ECO (?)
578
    for i in range(0x1F60, 0x2000, 0x40):
579
        data += _read_block(radio, i, 0x40, False)
580

    
581
    if append_model:
582
        data += radio.MODEL.ljust(8)
583

    
584
    LOG.debug("done.")
585
    return memmap.MemoryMap(data)
586

    
587

    
588
def _send_block(radio, addr, data):
589
    msg = struct.pack(">BHB", ord("X"), addr, len(data))
590
    radio.pipe.write(msg + data)
591
    time.sleep(0.05)
592

    
593
    ack = radio.pipe.read(1)
594
    if ack != "\x06":
595
        raise errors.RadioError("Radio refused to accept block 0x%04x" % addr)
596

    
597

    
598
def _do_upload(radio):
599
    ident = _ident_radio(radio)
600
    radio_upper_band = ident[3:4]
601
    image_upper_band = _upper_band_from_image(radio)
602

    
603
    if image_upper_band == vhf_220_radio or radio_upper_band == vhf_220_radio:
604
        if image_upper_band != radio_upper_band:
605
            raise errors.RadioError("Image not supported by radio")
606

    
607
    image_version = _firmware_version_from_image(radio)
608
    radio_version = _get_radio_firmware_version(radio)
609
    LOG.info("Image Version is %s" % repr(image_version))
610
    LOG.info("Radio Version is %s" % repr(radio_version))
611

    
612
    # default ranges
613
    _ranges_main_default = [
614
        (0x0008, 0x0CF8),
615
        (0x0D08, 0x0DF8),
616
        (0x0E08, 0x1808)
617
        ]
618
    _ranges_aux_default = [
619
        (0x1EC0, 0x1EF0),
620
        ]
621

    
622
    # extra aux ranges
623
    _ranges_aux_extra = [
624
        (0x1F60, 0x1F70),
625
        (0x1F80, 0x1F90),
626
        (0x1FC0, 0x1FD0)
627
        ]
628

    
629
    if image_version == radio_version:
630
        image_matched_radio = True
631
        if image_version.startswith("HN5RV"):
632
            ranges_main = _ranges_main_default
633
            ranges_aux = _ranges_aux_default + _ranges_aux_extra
634
        elif image_version == 0xFF * 14:
635
            ranges_main = _ranges_main_default
636
            ranges_aux = _ranges_aux_default + _ranges_aux_extra
637
        else:
638
            ranges_main = radio._ranges_main
639
            ranges_aux = radio._ranges_aux
640
    elif any(type in radio_version for type in radio._basetype):
641
        image_matched_radio = False
642
        ranges_main = _ranges_main_default
643
        ranges_aux = _ranges_aux_default
644
    else:
645
        msg = ("The upload was stopped because the firmware "
646
               "version of the image (%s) does not match that "
647
               "of the radio (%s).")
648
        raise errors.RadioError(msg % (image_version, radio_version))
649

    
650
    # Main block
651
    for start_addr, end_addr in ranges_main:
652
        for i in range(start_addr, end_addr, 0x10):
653
            _send_block(radio, i - 0x08, radio.get_mmap()[i:i + 0x10])
654
            _do_status(radio, i)
655
        _do_status(radio, radio.get_memsize())
656

    
657
    if len(radio.get_mmap().get_packed()) == 0x1808:
658
        LOG.info("Old image, not writing aux block")
659
        return  # Old image, no aux block
660

    
661
    # Auxiliary block at radio address 0x1EC0, our offset 0x1808
662
    for start_addr, end_addr in ranges_aux:
663
        for i in range(start_addr, end_addr, 0x10):
664
            addr = 0x1808 + (i - 0x1EC0)
665
            _send_block(radio, i, radio.get_mmap()[addr:addr + 0x10])
666

    
667
    if not image_matched_radio:
668
        msg = ("Upload finished, but the 'Other Settings' "
669
               "could not be sent because the firmware "
670
               "version of the image (%s) does not match "
671
               "that of the radio (%s).")
672
        raise errors.RadioError(msg % (image_version, radio_version))
673

    
674
UV5R_POWER_LEVELS = [chirp_common.PowerLevel("High", watts=4.00),
675
                     chirp_common.PowerLevel("Low",  watts=1.00)]
676

    
677
UV5R_POWER_LEVELS3 = [chirp_common.PowerLevel("High", watts=8.00),
678
                      chirp_common.PowerLevel("Med",  watts=4.00),
679
                      chirp_common.PowerLevel("Low",  watts=1.00)]
680

    
681
UV5R_DTCS = sorted(chirp_common.DTCS_CODES + [645])
682

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

    
686

    
687
def model_match(cls, data):
688
    """Match the opened/downloaded image to the correct version"""
689

    
690
    if len(data) == 0x1950:
691
        rid = data[0x1948:0x1950]
692
        return rid.startswith(cls.MODEL)
693
    elif len(data) == 0x1948:
694
        rid = data[cls._fw_ver_file_start:cls._fw_ver_file_stop]
695
        if any(type in rid for type in cls._basetype):
696
            return True
697
    else:
698
        return False
699

    
700

    
701
class BaofengUV5R(chirp_common.CloneModeRadio,
702
                  chirp_common.ExperimentalRadio):
703

    
704
    """Baofeng UV-5R"""
705
    VENDOR = "Baofeng"
706
    MODEL = "UV-5R"
707
    BAUD_RATE = 9600
708

    
709
    _memsize = 0x1808
710
    _basetype = BASETYPE_UV5R
711
    _idents = [UV5R_MODEL_291]
712
    _vhf_range = (136000000, 174000000)
713
    _220_range = (220000000, 260000000)
714
    _uhf_range = (400000000, 520000000)
715
    _mem_params = (0x1828  # poweron_msg offset
716
                   )
717
    # offset of fw version in image file
718
    _fw_ver_file_start = 0x1838
719
    _fw_ver_file_stop = 0x1846
720

    
721
    _ranges_main = [
722
                    (0x0008, 0x1808),
723
                   ]
724
    _ranges_aux = [
725
                   (0x1EC0, 0x2000),
726
                  ]
727
    _valid_chars = UV5R_CHARSET
728

    
729
    @classmethod
730
    def get_prompts(cls):
731
        rp = chirp_common.RadioPrompts()
732
        rp.experimental = \
733
            ('Due to the fact that the manufacturer continues to '
734
             'release new versions of the firmware with obscure and '
735
             'hard-to-track changes, this driver may not work with '
736
             'your device. Thus far and to the best knowledge of the '
737
             'author, no UV-5R radios have been harmed by using CHIRP. '
738
             'However, proceed at your own risk!')
739
        rp.pre_download = _(dedent("""\
740
            1. Turn radio off.
741
            2. Connect cable to mic/spkr connector.
742
            3. Make sure connector is firmly connected.
743
            4. Turn radio on (volume may need to be set at 100%).
744
            5. Ensure that the radio is tuned to channel with no activity.
745
            6. Click OK to download image from device."""))
746
        rp.pre_upload = _(dedent("""\
747
            1. Turn radio off.
748
            2. Connect cable to mic/spkr connector.
749
            3. Make sure connector is firmly connected.
750
            4. Turn radio on (volume may need to be set at 100%).
751
            5. Ensure that the radio is tuned to channel with no activity.
752
            6. Click OK to upload image to device."""))
753
        return rp
754

    
755
    def get_features(self):
756
        rf = chirp_common.RadioFeatures()
757
        rf.has_settings = True
758
        rf.has_bank = False
759
        rf.has_cross = True
760
        rf.has_rx_dtcs = True
761
        rf.has_tuning_step = False
762
        rf.can_odd_split = True
763
        rf.valid_name_length = 7
764
        rf.valid_characters = self._valid_chars
765
        rf.valid_skips = ["", "S"]
766
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
767
        rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone",
768
                                "->Tone", "->DTCS", "DTCS->", "DTCS->DTCS"]
769
        rf.valid_power_levels = UV5R_POWER_LEVELS
770
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
771
        rf.valid_modes = ["FM", "NFM"]
772

    
773
        normal_bands = [self._vhf_range, self._uhf_range, self._220_range]
774
        rax_bands = [self._vhf_range, self._220_range]
775

    
776
        if self._mmap is None:
777
            rf.valid_bands = [normal_bands[0], rax_bands[1], normal_bands[1]]
778
        elif not self._is_orig() and self._my_upper_band() == vhf_220_radio:
779
            rf.valid_bands = rax_bands
780
        else:
781
            rf.valid_bands = normal_bands
782
        rf.memory_bounds = (0, 127)
783
        return rf
784

    
785
    @classmethod
786
    def match_model(cls, filedata, filename):
787
        match_size = False
788
        match_model = False
789
        if len(filedata) in [0x1808, 0x1948, 0x1950]:
790
            match_size = True
791
        match_model = model_match(cls, filedata)
792

    
793
        if match_size and match_model:
794
            return True
795
        else:
796
            return False
797

    
798
    def process_mmap(self):
799
        self._memobj = bitwise.parse(MEM_FORMAT % self._mem_params, self._mmap)
800

    
801
    def sync_in(self):
802
        try:
803
            self._mmap = _do_download(self)
804
        except errors.RadioError:
805
            raise
806
        except Exception, e:
807
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
808
        self.process_mmap()
809

    
810
    def sync_out(self):
811
        try:
812
            _do_upload(self)
813
        except errors.RadioError:
814
            raise
815
        except Exception, e:
816
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
817

    
818
    def get_raw_memory(self, number):
819
        return repr(self._memobj.memory[number])
820

    
821
    def _is_txinh(self, _mem):
822
        raw_tx = ""
823
        for i in range(0, 4):
824
            raw_tx += _mem.txfreq[i].get_raw()
825
        return raw_tx == "\xFF\xFF\xFF\xFF"
826

    
827
    def _get_mem(self, number):
828
        return self._memobj.memory[number]
829

    
830
    def _get_nam(self, number):
831
        return self._memobj.names[number]
832

    
833
    def get_memory(self, number):
834
        _mem = self._get_mem(number)
835
        _nam = self._get_nam(number)
836

    
837
        mem = chirp_common.Memory()
838
        mem.number = number
839

    
840
        if _mem.get_raw()[0] == "\xff":
841
            mem.empty = True
842
            return mem
843

    
844
        mem.freq = int(_mem.rxfreq) * 10
845

    
846
        if self._is_txinh(_mem):
847
            mem.duplex = "off"
848
            mem.offset = 0
849
        elif int(_mem.rxfreq) == int(_mem.txfreq):
850
            mem.duplex = ""
851
            mem.offset = 0
852
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 70000000:
853
            mem.duplex = "split"
854
            mem.offset = int(_mem.txfreq) * 10
855
        else:
856
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
857
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
858

    
859
        for char in _nam.name:
860
            if str(char) == "\xFF":
861
                char = " "  # The UV-5R software may have 0xFF mid-name
862
            mem.name += str(char)
863
        mem.name = mem.name.rstrip()
864

    
865
        dtcs_pol = ["N", "N"]
866

    
867
        if _mem.txtone in [0, 0xFFFF]:
868
            txmode = ""
869
        elif _mem.txtone >= 0x0258:
870
            txmode = "Tone"
871
            mem.rtone = int(_mem.txtone) / 10.0
872
        elif _mem.txtone <= 0x0258:
873
            txmode = "DTCS"
874
            if _mem.txtone > 0x69:
875
                index = _mem.txtone - 0x6A
876
                dtcs_pol[0] = "R"
877
            else:
878
                index = _mem.txtone - 1
879
            mem.dtcs = UV5R_DTCS[index]
880
        else:
881
            LOG.warn("Bug: txtone is %04x" % _mem.txtone)
882

    
883
        if _mem.rxtone in [0, 0xFFFF]:
884
            rxmode = ""
885
        elif _mem.rxtone >= 0x0258:
886
            rxmode = "Tone"
887
            mem.ctone = int(_mem.rxtone) / 10.0
888
        elif _mem.rxtone <= 0x0258:
889
            rxmode = "DTCS"
890
            if _mem.rxtone >= 0x6A:
891
                index = _mem.rxtone - 0x6A
892
                dtcs_pol[1] = "R"
893
            else:
894
                index = _mem.rxtone - 1
895
            mem.rx_dtcs = UV5R_DTCS[index]
896
        else:
897
            LOG.warn("Bug: rxtone is %04x" % _mem.rxtone)
898

    
899
        if txmode == "Tone" and not rxmode:
900
            mem.tmode = "Tone"
901
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
902
            mem.tmode = "TSQL"
903
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
904
            mem.tmode = "DTCS"
905
        elif rxmode or txmode:
906
            mem.tmode = "Cross"
907
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
908

    
909
        mem.dtcs_polarity = "".join(dtcs_pol)
910

    
911
        if not _mem.scan:
912
            mem.skip = "S"
913

    
914
        if self.MODEL in ("KT-980HP", "BF-F8HP", "UV-82HP"):
915
            levels = UV5R_POWER_LEVELS3
916
        else:
917
            levels = UV5R_POWER_LEVELS
918
        try:
919
            mem.power = levels[_mem.lowpower]
920
        except IndexError:
921
            LOG.error("Radio reported invalid power level %s (in %s)" %
922
                      (_mem.lowpower, levels))
923
            mem.power = levels[0]
924

    
925
        mem.mode = _mem.wide and "FM" or "NFM"
926

    
927
        mem.extra = RadioSettingGroup("Extra", "extra")
928

    
929
        rs = RadioSetting("bcl", "BCL",
930
                          RadioSettingValueBoolean(_mem.bcl))
931
        mem.extra.append(rs)
932

    
933
        rs = RadioSetting("pttid", "PTT ID",
934
                          RadioSettingValueList(PTTID_LIST,
935
                                                PTTID_LIST[_mem.pttid]))
936
        mem.extra.append(rs)
937

    
938
        rs = RadioSetting("scode", "PTT ID Code",
939
                          RadioSettingValueList(PTTIDCODE_LIST,
940
                                                PTTIDCODE_LIST[_mem.scode]))
941
        mem.extra.append(rs)
942

    
943
        return mem
944

    
945
    def _set_mem(self, number):
946
        return self._memobj.memory[number]
947

    
948
    def _set_nam(self, number):
949
        return self._memobj.names[number]
950

    
951
    def set_memory(self, mem):
952
        _mem = self._get_mem(mem.number)
953
        _nam = self._get_nam(mem.number)
954

    
955
        if mem.empty:
956
            _mem.set_raw("\xff" * 16)
957
            _nam.set_raw("\xff" * 16)
958
            return
959

    
960
        was_empty = False
961
        # same method as used in get_memory to find
962
        # out whether a raw memory is empty
963
        if _mem.get_raw()[0] == "\xff":
964
            was_empty = True
965
            LOG.debug("UV5R: this mem was empty")
966
        else:
967
            # memorize old extra-values before erasing the whole memory
968
            # used to solve issue 4121
969
            LOG.debug("mem was not empty, memorize extra-settings")
970
            prev_bcl = _mem.bcl.get_value()
971
            prev_scode = _mem.scode.get_value()
972
            prev_pttid = _mem.pttid.get_value()
973

    
974
        _mem.set_raw("\x00" * 16)
975

    
976
        _mem.rxfreq = mem.freq / 10
977

    
978
        if mem.duplex == "off":
979
            for i in range(0, 4):
980
                _mem.txfreq[i].set_raw("\xFF")
981
        elif mem.duplex == "split":
982
            _mem.txfreq = mem.offset / 10
983
        elif mem.duplex == "+":
984
            _mem.txfreq = (mem.freq + mem.offset) / 10
985
        elif mem.duplex == "-":
986
            _mem.txfreq = (mem.freq - mem.offset) / 10
987
        else:
988
            _mem.txfreq = mem.freq / 10
989

    
990
        _namelength = self.get_features().valid_name_length
991
        for i in range(_namelength):
992
            try:
993
                _nam.name[i] = mem.name[i]
994
            except IndexError:
995
                _nam.name[i] = "\xFF"
996

    
997
        rxmode = txmode = ""
998
        if mem.tmode == "Tone":
999
            _mem.txtone = int(mem.rtone * 10)
1000
            _mem.rxtone = 0
1001
        elif mem.tmode == "TSQL":
1002
            _mem.txtone = int(mem.ctone * 10)
1003
            _mem.rxtone = int(mem.ctone * 10)
1004
        elif mem.tmode == "DTCS":
1005
            rxmode = txmode = "DTCS"
1006
            _mem.txtone = UV5R_DTCS.index(mem.dtcs) + 1
1007
            _mem.rxtone = UV5R_DTCS.index(mem.dtcs) + 1
1008
        elif mem.tmode == "Cross":
1009
            txmode, rxmode = mem.cross_mode.split("->", 1)
1010
            if txmode == "Tone":
1011
                _mem.txtone = int(mem.rtone * 10)
1012
            elif txmode == "DTCS":
1013
                _mem.txtone = UV5R_DTCS.index(mem.dtcs) + 1
1014
            else:
1015
                _mem.txtone = 0
1016
            if rxmode == "Tone":
1017
                _mem.rxtone = int(mem.ctone * 10)
1018
            elif rxmode == "DTCS":
1019
                _mem.rxtone = UV5R_DTCS.index(mem.rx_dtcs) + 1
1020
            else:
1021
                _mem.rxtone = 0
1022
        else:
1023
            _mem.rxtone = 0
1024
            _mem.txtone = 0
1025

    
1026
        if txmode == "DTCS" and mem.dtcs_polarity[0] == "R":
1027
            _mem.txtone += 0x69
1028
        if rxmode == "DTCS" and mem.dtcs_polarity[1] == "R":
1029
            _mem.rxtone += 0x69
1030

    
1031
        _mem.scan = mem.skip != "S"
1032
        _mem.wide = mem.mode == "FM"
1033

    
1034
        if mem.power:
1035
            if self.MODEL in ("KT-980HP", "BF-F8HP", "UV-82HP"):
1036
                levels = [str(l) for l in UV5R_POWER_LEVELS3]
1037
                _mem.lowpower = levels.index(str(mem.power))
1038
            else:
1039
                _mem.lowpower = UV5R_POWER_LEVELS.index(mem.power)
1040
        else:
1041
            _mem.lowpower = 0
1042

    
1043
        if not was_empty:
1044
            # restoring old extra-settings (issue 4121
1045
            _mem.bcl.set_value(prev_bcl)
1046
            _mem.scode.set_value(prev_scode)
1047
            _mem.pttid.set_value(prev_pttid)
1048

    
1049
        for setting in mem.extra:
1050
            setattr(_mem, setting.get_name(), setting.value)
1051

    
1052
    def _is_orig(self):
1053
        version_tag = _firmware_version_from_image(self)
1054
        LOG.debug("@_is_orig, version_tag: %s", util.hexprint(version_tag))
1055
        try:
1056
            if 'BFB' in version_tag:
1057
                idx = version_tag.index("BFB") + 3
1058
                version = int(version_tag[idx:idx + 3])
1059
                return version < 291
1060
            return False
1061
        except:
1062
            pass
1063
        raise errors.RadioError("Unable to parse version string %s" %
1064
                                version_tag)
1065

    
1066
    def _my_version(self):
1067
        version_tag = _firmware_version_from_image(self)
1068
        if 'BFB' in version_tag:
1069
            idx = version_tag.index("BFB") + 3
1070
            return int(version_tag[idx:idx + 3])
1071

    
1072
        raise Exception("Unrecognized firmware version string")
1073

    
1074
    def _my_upper_band(self):
1075
        band_tag = _upper_band_from_image(self)
1076
        return band_tag
1077

    
1078
    def _get_settings(self):
1079
        _ani = self._memobj.ani
1080
        _fm_presets = self._memobj.fm_presets
1081
        _settings = self._memobj.settings
1082
        _squelch = self._memobj.squelch_new
1083
        _vfoa = self._memobj.vfoa
1084
        _vfob = self._memobj.vfob
1085
        _wmchannel = self._memobj.wmchannel
1086
        basic = RadioSettingGroup("basic", "Basic Settings")
1087
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
1088

    
1089
        group = RadioSettings(basic, advanced)
1090

    
1091
        rs = RadioSetting("squelch", "Carrier Squelch Level",
1092
                          RadioSettingValueInteger(0, 9, _settings.squelch))
1093
        basic.append(rs)
1094

    
1095
        rs = RadioSetting("save", "Battery Saver",
1096
                          RadioSettingValueList(
1097
                              SAVE_LIST, SAVE_LIST[_settings.save]))
1098
        basic.append(rs)
1099

    
1100
        rs = RadioSetting("vox", "VOX Sensitivity",
1101
                          RadioSettingValueList(
1102
                              VOX_LIST, VOX_LIST[_settings.vox]))
1103
        advanced.append(rs)
1104

    
1105
        if self.MODEL == "UV-6":
1106
            # NOTE: The UV-6 calls this byte voxenable, but the UV-5R calls it
1107
            # autolk. Since this is a minor difference, it will be referred to
1108
            # by the wrong name for the UV-6.
1109
            rs = RadioSetting("autolk", "Vox",
1110
                              RadioSettingValueBoolean(_settings.autolk))
1111
            advanced.append(rs)
1112

    
1113
        if self.MODEL != "UV-6":
1114
            rs = RadioSetting("abr", "Backlight Timeout",
1115
                              RadioSettingValueInteger(0, 24, _settings.abr))
1116
            basic.append(rs)
1117

    
1118
        rs = RadioSetting("tdr", "Dual Watch",
1119
                          RadioSettingValueBoolean(_settings.tdr))
1120
        advanced.append(rs)
1121

    
1122
        if self.MODEL == "UV-6":
1123
            rs = RadioSetting("tdrch", "Dual Watch Channel",
1124
                              RadioSettingValueList(
1125
                                  TDRCH_LIST, TDRCH_LIST[_settings.tdrch]))
1126
            advanced.append(rs)
1127

    
1128
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1129
                              RadioSettingValueBoolean(_settings.tdrab))
1130
            advanced.append(rs)
1131
        else:
1132
            rs = RadioSetting("tdrab", "Dual Watch TX Priority",
1133
                              RadioSettingValueList(
1134
                                  TDRAB_LIST, TDRAB_LIST[_settings.tdrab]))
1135
            advanced.append(rs)
1136

    
1137
        if self.MODEL == "UV-6":
1138
            rs = RadioSetting("alarm", "Alarm Sound",
1139
                              RadioSettingValueBoolean(_settings.alarm))
1140
            advanced.append(rs)
1141

    
1142
        if _settings.almod > 0x02:
1143
            val = 0x01
1144
        else:
1145
            val = _settings.almod
1146
        rs = RadioSetting("almod", "Alarm Mode",
1147
                          RadioSettingValueList(
1148
                              ALMOD_LIST, ALMOD_LIST[val]))
1149
        advanced.append(rs)
1150

    
1151
        rs = RadioSetting("beep", "Beep",
1152
                          RadioSettingValueBoolean(_settings.beep))
1153
        basic.append(rs)
1154

    
1155
        rs = RadioSetting("timeout", "Timeout Timer",
1156
                          RadioSettingValueList(
1157
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
1158
        basic.append(rs)
1159

    
1160
        if self._is_orig() and self._my_version() < 251:
1161
            rs = RadioSetting("voice", "Voice",
1162
                              RadioSettingValueBoolean(_settings.voice))
1163
            advanced.append(rs)
1164
        else:
1165
            rs = RadioSetting("voice", "Voice",
1166
                              RadioSettingValueList(
1167
                                  VOICE_LIST, VOICE_LIST[_settings.voice]))
1168
            advanced.append(rs)
1169

    
1170
        rs = RadioSetting("screv", "Scan Resume",
1171
                          RadioSettingValueList(
1172
                              RESUME_LIST, RESUME_LIST[_settings.screv]))
1173
        advanced.append(rs)
1174

    
1175
        if self.MODEL != "UV-6":
1176
            rs = RadioSetting("mdfa", "Display Mode (A)",
1177
                              RadioSettingValueList(
1178
                                  MODE_LIST, MODE_LIST[_settings.mdfa]))
1179
            basic.append(rs)
1180

    
1181
            rs = RadioSetting("mdfb", "Display Mode (B)",
1182
                              RadioSettingValueList(
1183
                                  MODE_LIST, MODE_LIST[_settings.mdfb]))
1184
            basic.append(rs)
1185

    
1186
        rs = RadioSetting("bcl", "Busy Channel Lockout",
1187
                          RadioSettingValueBoolean(_settings.bcl))
1188
        advanced.append(rs)
1189

    
1190
        if self.MODEL != "UV-6":
1191
            rs = RadioSetting("autolk", "Automatic Key Lock",
1192
                              RadioSettingValueBoolean(_settings.autolk))
1193
            advanced.append(rs)
1194

    
1195
        rs = RadioSetting("fmradio", "Broadcast FM Radio",
1196
                          RadioSettingValueBoolean(_settings.fmradio))
1197
        advanced.append(rs)
1198

    
1199
        if self.MODEL != "UV-6":
1200
            rs = RadioSetting("wtled", "Standby LED Color",
1201
                              RadioSettingValueList(
1202
                                  COLOR_LIST, COLOR_LIST[_settings.wtled]))
1203
            basic.append(rs)
1204

    
1205
            rs = RadioSetting("rxled", "RX LED Color",
1206
                              RadioSettingValueList(
1207
                                  COLOR_LIST, COLOR_LIST[_settings.rxled]))
1208
            basic.append(rs)
1209

    
1210
            rs = RadioSetting("txled", "TX LED Color",
1211
                              RadioSettingValueList(
1212
                                  COLOR_LIST, COLOR_LIST[_settings.txled]))
1213
            basic.append(rs)
1214

    
1215
        if self.MODEL == "UV-82":
1216
            rs = RadioSetting("roger", "Roger Beep (TX)",
1217
                              RadioSettingValueBoolean(_settings.roger))
1218
            basic.append(rs)
1219
            rs = RadioSetting("rogerrx", "Roger Beep (RX)",
1220
                              RadioSettingValueList(
1221
                                  ROGERRX_LIST,
1222
                                  ROGERRX_LIST[_settings.rogerrx]))
1223
            basic.append(rs)
1224
        else:
1225
            rs = RadioSetting("roger", "Roger Beep",
1226
                              RadioSettingValueBoolean(_settings.roger))
1227
            basic.append(rs)
1228

    
1229
        rs = RadioSetting("ste", "Squelch Tail Eliminate (HT to HT)",
1230
                          RadioSettingValueBoolean(_settings.ste))
1231
        advanced.append(rs)
1232

    
1233
        rs = RadioSetting("rpste", "Squelch Tail Eliminate (repeater)",
1234
                          RadioSettingValueList(
1235
                              RPSTE_LIST, RPSTE_LIST[_settings.rpste]))
1236
        advanced.append(rs)
1237

    
1238
        rs = RadioSetting("rptrl", "STE Repeater Delay",
1239
                          RadioSettingValueList(
1240
                              STEDELAY_LIST, STEDELAY_LIST[_settings.rptrl]))
1241
        advanced.append(rs)
1242

    
1243
        if self.MODEL != "UV-6":
1244
            rs = RadioSetting("reset", "RESET Menu",
1245
                              RadioSettingValueBoolean(_settings.reset))
1246
            advanced.append(rs)
1247

    
1248
            rs = RadioSetting("menu", "All Menus",
1249
                              RadioSettingValueBoolean(_settings.menu))
1250
            advanced.append(rs)
1251

    
1252
        if self.MODEL == "F-11":
1253
            # this is an F-11 only feature
1254
            rs = RadioSetting("vfomrlock", "VFO/MR Button",
1255
                              RadioSettingValueBoolean(_settings.vfomrlock))
1256
            advanced.append(rs)
1257

    
1258
        if self.MODEL == "UV-82":
1259
            # this is a UV-82C only feature
1260
            rs = RadioSetting("vfomrlock", "VFO/MR Switching (UV-82C only)",
1261
                              RadioSettingValueBoolean(_settings.vfomrlock))
1262
            advanced.append(rs)
1263

    
1264
        if self.MODEL == "UV-82HP":
1265
            # this is a UV-82HP only feature
1266
            rs = RadioSetting(
1267
                "vfomrlock", "VFO/MR Switching (BTech UV-82HP only)",
1268
                RadioSettingValueBoolean(_settings.vfomrlock))
1269
            advanced.append(rs)
1270

    
1271
        if self.MODEL == "UV-82":
1272
            # this is an UV-82C only feature
1273
            rs = RadioSetting("singleptt", "Single PTT (UV-82C only)",
1274
                              RadioSettingValueBoolean(_settings.singleptt))
1275
            advanced.append(rs)
1276

    
1277
        if self.MODEL == "UV-82HP":
1278
            # this is an UV-82HP only feature
1279
            rs = RadioSetting("singleptt", "Single PTT (BTech UV-82HP only)",
1280
                              RadioSettingValueBoolean(_settings.singleptt))
1281
            advanced.append(rs)
1282

    
1283
        if self.MODEL == "UV-82HP":
1284
            # this is an UV-82HP only feature
1285
            rs = RadioSetting(
1286
                "tdrch", "Tone Burst Frequency (BTech UV-82HP only)",
1287
                RadioSettingValueList(RTONE_LIST, RTONE_LIST[_settings.tdrch]))
1288
            advanced.append(rs)
1289

    
1290
        if len(self._mmap.get_packed()) == 0x1808:
1291
            # Old image, without aux block
1292
            return group
1293

    
1294
        other = RadioSettingGroup("other", "Other Settings")
1295
        group.append(other)
1296

    
1297
        def _filter(name):
1298
            filtered = ""
1299
            for char in str(name):
1300
                if char in chirp_common.CHARSET_ASCII:
1301
                    filtered += char
1302
                else:
1303
                    filtered += " "
1304
            return filtered
1305

    
1306
        _msg = self._memobj.firmware_msg
1307
        val = RadioSettingValueString(0, 7, _filter(_msg.line1))
1308
        val.set_mutable(False)
1309
        rs = RadioSetting("firmware_msg.line1", "Firmware Message 1", val)
1310
        other.append(rs)
1311

    
1312
        val = RadioSettingValueString(0, 7, _filter(_msg.line2))
1313
        val.set_mutable(False)
1314
        rs = RadioSetting("firmware_msg.line2", "Firmware Message 2", val)
1315
        other.append(rs)
1316

    
1317
        if self.MODEL != "UV-6":
1318
            _msg = self._memobj.sixpoweron_msg
1319
            rs = RadioSetting("sixpoweron_msg.line1", "6+Power-On Message 1",
1320
                              RadioSettingValueString(
1321
                                  0, 7, _filter(_msg.line1)))
1322
            other.append(rs)
1323
            rs = RadioSetting("sixpoweron_msg.line2", "6+Power-On Message 2",
1324
                              RadioSettingValueString(
1325
                                  0, 7, _filter(_msg.line2)))
1326
            other.append(rs)
1327

    
1328
            _msg = self._memobj.poweron_msg
1329
            rs = RadioSetting("poweron_msg.line1", "Power-On Message 1",
1330
                              RadioSettingValueString(
1331
                                  0, 7, _filter(_msg.line1)))
1332
            other.append(rs)
1333
            rs = RadioSetting("poweron_msg.line2", "Power-On Message 2",
1334
                              RadioSettingValueString(
1335
                                  0, 7, _filter(_msg.line2)))
1336
            other.append(rs)
1337

    
1338
            rs = RadioSetting("ponmsg", "Power-On Message",
1339
                              RadioSettingValueList(
1340
                                  PONMSG_LIST, PONMSG_LIST[_settings.ponmsg]))
1341
            other.append(rs)
1342

    
1343
            if self._is_orig():
1344
                limit = "limits_old"
1345
            else:
1346
                limit = "limits_new"
1347

    
1348
            vhf_limit = getattr(self._memobj, limit).vhf
1349
            rs = RadioSetting("%s.vhf.lower" % limit, "VHF Lower Limit (MHz)",
1350
                              RadioSettingValueInteger(1, 1000,
1351
                                                       vhf_limit.lower))
1352
            other.append(rs)
1353

    
1354
            rs = RadioSetting("%s.vhf.upper" % limit, "VHF Upper Limit (MHz)",
1355
                              RadioSettingValueInteger(1, 1000,
1356
                                                       vhf_limit.upper))
1357
            other.append(rs)
1358

    
1359
            rs = RadioSetting("%s.vhf.enable" % limit, "VHF TX Enabled",
1360
                              RadioSettingValueBoolean(vhf_limit.enable))
1361
            other.append(rs)
1362

    
1363
            uhf_limit = getattr(self._memobj, limit).uhf
1364
            rs = RadioSetting("%s.uhf.lower" % limit, "UHF Lower Limit (MHz)",
1365
                              RadioSettingValueInteger(1, 1000,
1366
                                                       uhf_limit.lower))
1367
            other.append(rs)
1368
            rs = RadioSetting("%s.uhf.upper" % limit, "UHF Upper Limit (MHz)",
1369
                              RadioSettingValueInteger(1, 1000,
1370
                                                       uhf_limit.upper))
1371
            other.append(rs)
1372
            rs = RadioSetting("%s.uhf.enable" % limit, "UHF TX Enabled",
1373
                              RadioSettingValueBoolean(uhf_limit.enable))
1374
            other.append(rs)
1375

    
1376
        if self.MODEL != "UV-6":
1377
            workmode = RadioSettingGroup("workmode", "Work Mode Settings")
1378
            group.append(workmode)
1379

    
1380
            rs = RadioSetting("displayab", "Display",
1381
                              RadioSettingValueList(
1382
                                  AB_LIST, AB_LIST[_settings.displayab]))
1383
            workmode.append(rs)
1384

    
1385
            rs = RadioSetting("workmode", "VFO/MR Mode",
1386
                              RadioSettingValueList(
1387
                                  WORKMODE_LIST,
1388
                                  WORKMODE_LIST[_settings.workmode]))
1389
            workmode.append(rs)
1390

    
1391
            rs = RadioSetting("keylock", "Keypad Lock",
1392
                              RadioSettingValueBoolean(_settings.keylock))
1393
            workmode.append(rs)
1394

    
1395
            rs = RadioSetting("wmchannel.mrcha", "MR A Channel",
1396
                              RadioSettingValueInteger(0, 127,
1397
                                                       _wmchannel.mrcha))
1398
            workmode.append(rs)
1399

    
1400
            rs = RadioSetting("wmchannel.mrchb", "MR B Channel",
1401
                              RadioSettingValueInteger(0, 127,
1402
                                                       _wmchannel.mrchb))
1403
            workmode.append(rs)
1404

    
1405
            def convert_bytes_to_freq(bytes):
1406
                real_freq = 0
1407
                for byte in bytes:
1408
                    real_freq = (real_freq * 10) + byte
1409
                return chirp_common.format_freq(real_freq * 10)
1410

    
1411
            def my_validate(value):
1412
                value = chirp_common.parse_freq(value)
1413
                if 17400000 <= value and value < 40000000:
1414
                    msg = ("Can't be between 174.00000-400.00000")
1415
                    raise InvalidValueError(msg)
1416
                return chirp_common.format_freq(value)
1417

    
1418
            def apply_freq(setting, obj):
1419
                value = chirp_common.parse_freq(str(setting.value)) / 10
1420
                obj.band = value >= 40000000
1421
                for i in range(7, -1, -1):
1422
                    obj.freq[i] = value % 10
1423
                    value /= 10
1424

    
1425
            val1a = RadioSettingValueString(0, 10,
1426
                                            convert_bytes_to_freq(_vfoa.freq))
1427
            val1a.set_validate_callback(my_validate)
1428
            rs = RadioSetting("vfoa.freq", "VFO A Frequency", val1a)
1429
            rs.set_apply_callback(apply_freq, _vfoa)
1430
            workmode.append(rs)
1431

    
1432
            val1b = RadioSettingValueString(0, 10,
1433
                                            convert_bytes_to_freq(_vfob.freq))
1434
            val1b.set_validate_callback(my_validate)
1435
            rs = RadioSetting("vfob.freq", "VFO B Frequency", val1b)
1436
            rs.set_apply_callback(apply_freq, _vfob)
1437
            workmode.append(rs)
1438

    
1439
            rs = RadioSetting("vfoa.sftd", "VFO A Shift",
1440
                              RadioSettingValueList(
1441
                                  SHIFTD_LIST, SHIFTD_LIST[_vfoa.sftd]))
1442
            workmode.append(rs)
1443

    
1444
            rs = RadioSetting("vfob.sftd", "VFO B Shift",
1445
                              RadioSettingValueList(
1446
                                  SHIFTD_LIST, SHIFTD_LIST[_vfob.sftd]))
1447
            workmode.append(rs)
1448

    
1449
            def convert_bytes_to_offset(bytes):
1450
                real_offset = 0
1451
                for byte in bytes:
1452
                    real_offset = (real_offset * 10) + byte
1453
                return chirp_common.format_freq(real_offset * 10000)
1454

    
1455
            def apply_offset(setting, obj):
1456
                value = chirp_common.parse_freq(str(setting.value)) / 10000
1457
                for i in range(3, -1, -1):
1458
                    obj.offset[i] = value % 10
1459
                    value /= 10
1460

    
1461
            val1a = RadioSettingValueString(
1462
                0, 10, convert_bytes_to_offset(_vfoa.offset))
1463
            rs = RadioSetting("vfoa.offset",
1464
                              "VFO A Offset (0.00-69.95)", val1a)
1465
            rs.set_apply_callback(apply_offset, _vfoa)
1466
            workmode.append(rs)
1467

    
1468
            val1b = RadioSettingValueString(
1469
                0, 10, convert_bytes_to_offset(_vfob.offset))
1470
            rs = RadioSetting("vfob.offset",
1471
                              "VFO B Offset (0.00-69.95)", val1b)
1472
            rs.set_apply_callback(apply_offset, _vfob)
1473
            workmode.append(rs)
1474

    
1475
            if self.MODEL in ("KT-980HP", "BF-F8HP", "UV-82HP"):
1476
                rs = RadioSetting("vfoa.txpower3", "VFO A Power",
1477
                                  RadioSettingValueList(
1478
                                      TXPOWER3_LIST,
1479
                                      TXPOWER3_LIST[_vfoa.txpower3]))
1480
                workmode.append(rs)
1481

    
1482
                rs = RadioSetting("vfob.txpower3", "VFO B Power",
1483
                                  RadioSettingValueList(
1484
                                      TXPOWER3_LIST,
1485
                                      TXPOWER3_LIST[_vfob.txpower3]))
1486
                workmode.append(rs)
1487
            else:
1488
                rs = RadioSetting("vfoa.txpower", "VFO A Power",
1489
                                  RadioSettingValueList(
1490
                                      TXPOWER_LIST,
1491
                                      TXPOWER_LIST[_vfoa.txpower]))
1492
                workmode.append(rs)
1493

    
1494
                rs = RadioSetting("vfob.txpower", "VFO B Power",
1495
                                  RadioSettingValueList(
1496
                                      TXPOWER_LIST,
1497
                                      TXPOWER_LIST[_vfob.txpower]))
1498
                workmode.append(rs)
1499

    
1500
            rs = RadioSetting("vfoa.widenarr", "VFO A Bandwidth",
1501
                              RadioSettingValueList(
1502
                                  BANDWIDTH_LIST,
1503
                                  BANDWIDTH_LIST[_vfoa.widenarr]))
1504
            workmode.append(rs)
1505

    
1506
            rs = RadioSetting("vfob.widenarr", "VFO B Bandwidth",
1507
                              RadioSettingValueList(
1508
                                  BANDWIDTH_LIST,
1509
                                  BANDWIDTH_LIST[_vfob.widenarr]))
1510
            workmode.append(rs)
1511

    
1512
            rs = RadioSetting("vfoa.scode", "VFO A PTT-ID",
1513
                              RadioSettingValueList(
1514
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfoa.scode]))
1515
            workmode.append(rs)
1516

    
1517
            rs = RadioSetting("vfob.scode", "VFO B PTT-ID",
1518
                              RadioSettingValueList(
1519
                                  PTTIDCODE_LIST, PTTIDCODE_LIST[_vfob.scode]))
1520
            workmode.append(rs)
1521

    
1522
            if not self._is_orig():
1523
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1524
                                  RadioSettingValueList(
1525
                                      STEP291_LIST, STEP291_LIST[_vfoa.step]))
1526
                workmode.append(rs)
1527
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1528
                                  RadioSettingValueList(
1529
                                      STEP291_LIST, STEP291_LIST[_vfob.step]))
1530
                workmode.append(rs)
1531
            else:
1532
                rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
1533
                                  RadioSettingValueList(
1534
                                      STEP_LIST, STEP_LIST[_vfoa.step]))
1535
                workmode.append(rs)
1536
                rs = RadioSetting("vfob.step", "VFO B Tuning Step",
1537
                                  RadioSettingValueList(
1538
                                      STEP_LIST, STEP_LIST[_vfob.step]))
1539
                workmode.append(rs)
1540

    
1541
        fm_preset = RadioSettingGroup("fm_preset", "FM Radio Preset")
1542
        group.append(fm_preset)
1543

    
1544
        if _fm_presets <= 108.0 * 10 - 650:
1545
            preset = _fm_presets / 10.0 + 65
1546
        elif _fm_presets >= 65.0 * 10 and _fm_presets <= 108.0 * 10:
1547
            preset = _fm_presets / 10.0
1548
        else:
1549
            preset = 76.0
1550
        rs = RadioSetting("fm_presets", "FM Preset(MHz)",
1551
                          RadioSettingValueFloat(65, 108.0, preset, 0.1, 1))
1552
        fm_preset.append(rs)
1553

    
1554
        dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
1555
        group.append(dtmf)
1556
        dtmfchars = "0123456789 *#ABCD"
1557

    
1558
        for i in range(0, 15):
1559
            _codeobj = self._memobj.pttid[i].code
1560
            _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1561
            val = RadioSettingValueString(0, 5, _code, False)
1562
            val.set_charset(dtmfchars)
1563
            rs = RadioSetting("pttid/%i.code" % i,
1564
                              "PTT ID Code %i" % (i + 1), val)
1565

    
1566
            def apply_code(setting, obj):
1567
                code = []
1568
                for j in range(0, 5):
1569
                    try:
1570
                        code.append(dtmfchars.index(str(setting.value)[j]))
1571
                    except IndexError:
1572
                        code.append(0xFF)
1573
                obj.code = code
1574
            rs.set_apply_callback(apply_code, self._memobj.pttid[i])
1575
            dtmf.append(rs)
1576

    
1577
        _codeobj = self._memobj.ani.code
1578
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1579
        val = RadioSettingValueString(0, 5, _code, False)
1580
        val.set_charset(dtmfchars)
1581
        rs = RadioSetting("ani.code", "ANI Code", val)
1582

    
1583
        def apply_code(setting, obj):
1584
            code = []
1585
            for j in range(0, 5):
1586
                try:
1587
                    code.append(dtmfchars.index(str(setting.value)[j]))
1588
                except IndexError:
1589
                    code.append(0xFF)
1590
            obj.code = code
1591
        rs.set_apply_callback(apply_code, _ani)
1592
        dtmf.append(rs)
1593

    
1594
        rs = RadioSetting("ani.aniid", "ANI ID",
1595
                          RadioSettingValueList(PTTID_LIST,
1596
                                                PTTID_LIST[_ani.aniid]))
1597
        dtmf.append(rs)
1598

    
1599
        _codeobj = self._memobj.ani.alarmcode
1600
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x1F])
1601
        val = RadioSettingValueString(0, 3, _code, False)
1602
        val.set_charset(dtmfchars)
1603
        rs = RadioSetting("ani.alarmcode", "Alarm Code", val)
1604

    
1605
        def apply_code(setting, obj):
1606
            alarmcode = []
1607
            for j in range(0, 3):
1608
                try:
1609
                    alarmcode.append(dtmfchars.index(str(setting.value)[j]))
1610
                except IndexError:
1611
                    alarmcode.append(0xFF)
1612
            obj.alarmcode = alarmcode
1613
        rs.set_apply_callback(apply_code, _ani)
1614
        dtmf.append(rs)
1615

    
1616
        rs = RadioSetting("dtmfst", "DTMF Sidetone",
1617
                          RadioSettingValueList(DTMFST_LIST,
1618
                                                DTMFST_LIST[_settings.dtmfst]))
1619
        dtmf.append(rs)
1620

    
1621
        if _ani.dtmfon > 0xC3:
1622
            val = 0x00
1623
        else:
1624
            val = _ani.dtmfon
1625
        rs = RadioSetting("ani.dtmfon", "DTMF Speed (on)",
1626
                          RadioSettingValueList(DTMFSPEED_LIST,
1627
                                                DTMFSPEED_LIST[val]))
1628
        dtmf.append(rs)
1629

    
1630
        if _ani.dtmfoff > 0xC3:
1631
            val = 0x00
1632
        else:
1633
            val = _ani.dtmfoff
1634
        rs = RadioSetting("ani.dtmfoff", "DTMF Speed (off)",
1635
                          RadioSettingValueList(DTMFSPEED_LIST,
1636
                                                DTMFSPEED_LIST[val]))
1637
        dtmf.append(rs)
1638

    
1639
        rs = RadioSetting("pttlt", "PTT ID Delay",
1640
                          RadioSettingValueInteger(0, 50, _settings.pttlt))
1641
        dtmf.append(rs)
1642

    
1643
        if not self._is_orig():
1644
            service = RadioSettingGroup("service", "Service Settings")
1645
            group.append(service)
1646

    
1647
            for band in ["vhf", "uhf"]:
1648
                for index in range(0, 10):
1649
                    key = "squelch_new.%s.sql%i" % (band, index)
1650
                    if band == "vhf":
1651
                        _obj = self._memobj.squelch_new.vhf
1652
                    elif band == "uhf":
1653
                        _obj = self._memobj.squelch_new.uhf
1654
                    name = "%s Squelch %i" % (band.upper(), index)
1655
                    rs = RadioSetting(key, name,
1656
                                      RadioSettingValueInteger(
1657
                                          0, 123,
1658
                                          getattr(_obj, "sql%i" % (index))))
1659
                    service.append(rs)
1660

    
1661
        return group
1662

    
1663
    def get_settings(self):
1664
        try:
1665
            return self._get_settings()
1666
        except:
1667
            import traceback
1668
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1669
            return None
1670

    
1671
    def set_settings(self, settings):
1672
        _settings = self._memobj.settings
1673
        for element in settings:
1674
            if not isinstance(element, RadioSetting):
1675
                if element.get_name() == "fm_preset":
1676
                    self._set_fm_preset(element)
1677
                else:
1678
                    self.set_settings(element)
1679
                    continue
1680
            else:
1681
                try:
1682
                    name = element.get_name()
1683
                    if "." in name:
1684
                        bits = name.split(".")
1685
                        obj = self._memobj
1686
                        for bit in bits[:-1]:
1687
                            if "/" in bit:
1688
                                bit, index = bit.split("/", 1)
1689
                                index = int(index)
1690
                                obj = getattr(obj, bit)[index]
1691
                            else:
1692
                                obj = getattr(obj, bit)
1693
                        setting = bits[-1]
1694
                    else:
1695
                        obj = _settings
1696
                        setting = element.get_name()
1697

    
1698
                    if element.has_apply_callback():
1699
                        LOG.debug("Using apply callback")
1700
                        element.run_apply_callback()
1701
                    elif element.value.get_mutable():
1702
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1703
                        setattr(obj, setting, element.value)
1704
                except Exception, e:
1705
                    LOG.debug(element.get_name())
1706
                    raise
1707

    
1708
    def _set_fm_preset(self, settings):
1709
        for element in settings:
1710
            try:
1711
                val = element.value
1712
                if self._memobj.fm_presets <= 108.0 * 10 - 650:
1713
                    value = int(val.get_value() * 10 - 650)
1714
                else:
1715
                    value = int(val.get_value() * 10)
1716
                LOG.debug("Setting fm_presets = %s" % (value))
1717
                self._memobj.fm_presets = value
1718
            except Exception, e:
1719
                LOG.debug(element.get_name())
1720
                raise
1721

    
1722

    
1723
class UV5XAlias(chirp_common.Alias):
1724
    VENDOR = "Baofeng"
1725
    MODEL = "UV-5X"
1726

    
1727

    
1728
class RT5RAlias(chirp_common.Alias):
1729
    VENDOR = "Retevis"
1730
    MODEL = "RT-5R"
1731

    
1732

    
1733
class RT5RVAlias(chirp_common.Alias):
1734
    VENDOR = "Retevis"
1735
    MODEL = "RT-5RV"
1736

    
1737

    
1738
class RT5Alias(chirp_common.Alias):
1739
    VENDOR = "Retevis"
1740
    MODEL = "RT5"
1741

    
1742

    
1743
class RT5_TPAlias(chirp_common.Alias):
1744
    VENDOR = "Retevis"
1745
    MODEL = "RT5(tri-power)"
1746

    
1747

    
1748
class RH5RAlias(chirp_common.Alias):
1749
    VENDOR = "Rugged"
1750
    MODEL = "RH5R"
1751

    
1752

    
1753
class ROUV5REXAlias(chirp_common.Alias):
1754
    VENDOR = "Radioddity"
1755
    MODEL = "UV-5R EX"
1756

    
1757

    
1758
@directory.register
1759
class BaofengUV5RGeneric(BaofengUV5R):
1760
    ALIASES = [UV5XAlias, RT5RAlias, RT5RVAlias, RT5Alias, RH5RAlias,
1761
               ROUV5REXAlias]
1762

    
1763

    
1764
@directory.register
1765
class BaofengF11Radio(BaofengUV5R):
1766
    VENDOR = "Baofeng"
1767
    MODEL = "F-11"
1768
    _basetype = BASETYPE_F11
1769
    _idents = [UV5R_MODEL_291]
1770

    
1771
    def _is_orig(self):
1772
        # Override this for F11 to always return False
1773
        return False
1774

    
1775

    
1776
@directory.register
1777
class BaofengUV82Radio(BaofengUV5R):
1778
    MODEL = "UV-82"
1779
    _basetype = BASETYPE_UV82
1780
    _idents = [UV5R_MODEL_291]
1781
    _vhf_range = (130000000, 176000000)
1782
    _uhf_range = (400000000, 521000000)
1783
    _valid_chars = chirp_common.CHARSET_ASCII
1784

    
1785
    def _is_orig(self):
1786
        # Override this for UV82 to always return False
1787
        return False
1788

    
1789

    
1790
@directory.register
1791
class BaofengUV6Radio(BaofengUV5R):
1792

    
1793
    """Baofeng UV-6/UV-7"""
1794
    VENDOR = "Baofeng"
1795
    MODEL = "UV-6"
1796
    _basetype = BASETYPE_UV6
1797
    _idents = [UV5R_MODEL_291]
1798

    
1799
    def get_features(self):
1800
        rf = BaofengUV5R.get_features(self)
1801
        rf.memory_bounds = (1, 128)
1802
        return rf
1803

    
1804
    def _get_mem(self, number):
1805
        return self._memobj.memory[number - 1]
1806

    
1807
    def _get_nam(self, number):
1808
        return self._memobj.names[number - 1]
1809

    
1810
    def _set_mem(self, number):
1811
        return self._memobj.memory[number - 1]
1812

    
1813
    def _set_nam(self, number):
1814
        return self._memobj.names[number - 1]
1815

    
1816
    def _is_orig(self):
1817
        # Override this for UV6 to always return False
1818
        return False
1819

    
1820

    
1821
@directory.register
1822
class IntekKT980Radio(BaofengUV5R):
1823
    VENDOR = "Intek"
1824
    MODEL = "KT-980HP"
1825
    _basetype = BASETYPE_KT980HP
1826
    _idents = [UV5R_MODEL_291]
1827
    _vhf_range = (130000000, 180000000)
1828
    _uhf_range = (400000000, 521000000)
1829

    
1830
    def get_features(self):
1831
        rf = BaofengUV5R.get_features(self)
1832
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1833
        return rf
1834

    
1835
    def _is_orig(self):
1836
        # Override this for KT980HP to always return False
1837
        return False
1838

    
1839

    
1840
class ROGA5SAlias(chirp_common.Alias):
1841
    VENDOR = "Radioddity"
1842
    MODEL = "GA-5S"
1843

    
1844

    
1845
@directory.register
1846
class BaofengBFF8HPRadio(BaofengUV5R):
1847
    VENDOR = "Baofeng"
1848
    MODEL = "BF-F8HP"
1849
    ALIASES = [RT5_TPAlias, ROGA5SAlias]
1850
    _basetype = BASETYPE_F8HP
1851
    _idents = [UV5R_MODEL_291]
1852
    _vhf_range = (130000000, 180000000)
1853
    _uhf_range = (400000000, 521000000)
1854

    
1855
    def get_features(self):
1856
        rf = BaofengUV5R.get_features(self)
1857
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1858
        return rf
1859

    
1860
    def _is_orig(self):
1861
        # Override this for BFF8HP to always return False
1862
        return False
1863

    
1864

    
1865
@directory.register
1866
class BaofengUV82HPRadio(BaofengUV5R):
1867
    VENDOR = "Baofeng"
1868
    MODEL = "UV-82HP"
1869
    _basetype = BASETYPE_UV82HP
1870
    _idents = [UV5R_MODEL_291]
1871
    _vhf_range = (136000000, 175000000)
1872
    _uhf_range = (400000000, 521000000)
1873

    
1874
    def get_features(self):
1875
        rf = BaofengUV5R.get_features(self)
1876
        rf.valid_power_levels = UV5R_POWER_LEVELS3
1877
        return rf
1878

    
1879
    def _is_orig(self):
1880
        # Override this for UV82HP to always return False
1881
        return False
1882

    
1883

    
1884
@directory.register
1885
class RadioddityUV5RX3Radio(BaofengUV5R):
1886
    VENDOR = "Radioddity"
1887
    MODEL = "UV-5RX3"
1888

    
1889
    def get_features(self):
1890
        rf = BaofengUV5R.get_features(self)
1891
        rf.valid_bands = [self._vhf_range,
1892
                          (200000000, 260000000),
1893
                          self._uhf_range]
1894
        return rf
1895

    
1896
    @classmethod
1897
    def match_model(cls, filename, filedata):
1898
        return False
(2-2/4)