Project

General

Profile

New Model #9551 » bf-t8_1 rb27b - frs.py

test driver #2 - Jim Unroe, 12/20/2021 07:03 PM

 
1
# Copyright 2021 Jim Unroe <rock.unroe@gmail.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 time
17
import os
18
import struct
19
import logging
20

    
21
from chirp import (
22
    bitwise,
23
    chirp_common,
24
    directory,
25
    errors,
26
    memmap,
27
    util,
28
)
29
from chirp.settings import (
30
    RadioSetting,
31
    RadioSettingGroup,
32
    RadioSettings,
33
    RadioSettingValueBoolean,
34
    RadioSettingValueFloat,
35
    RadioSettingValueInteger,
36
    RadioSettingValueList,
37
    RadioSettingValueString,
38
)
39

    
40
LOG = logging.getLogger(__name__)
41

    
42
MEM_FORMAT = """
43
#seekto 0x0000;
44
struct {
45
  lbcd rxfreq[4];       // RX Frequency
46
  lbcd txfreq[4];       // TX Frequency
47
  u8 rx_tmode;          // RX Tone Mode
48
  u8 rx_tone;           // PL/DPL Decode
49
  u8 tx_tmode;          // TX Tone Mode
50
  u8 tx_tone;           // PL/DPL Encode
51
  u8 unknown1:3,        //
52
     skip:1,            // Scan Add: 1 = Skip, 0 = Scan
53
     unknown2:2,
54
     isnarrow:1,        // W/N: 1 = Narrow, 0 = Wide
55
     lowpower:1;        // TX Power: 1 = Low, 0 = High
56
  u8 unknown3[3];       //
57
} memory[%d];
58

    
59
#seekto 0x0630;
60
struct {
61
  u8 squelch;           // SQL
62
  u8 vox;               // Vox Lv
63
  u8 tot;               // TOT
64
  u8 unk1:3,            //
65
     ste:1,             // Tail Clear
66
     bcl:1,             // BCL
67
     save:1,            // Save
68
     tdr:1,             // TDR
69
     beep:1;            // Beep
70
  u8 voice;             // Voice
71
  u8 abr;               // Back Light
72
  u8 ring;              // Ring
73
  u8 unknown;           //
74
  u8 mra;               // MR Channel A
75
  u8 mrb;               // MR Channel B
76
  u8 disp_ab;           // Display A/B Selected
77
  u16 fmcur;            // Broadcast FM station
78
  u8 workmode;          // Work Mode
79
  u8 wx;                // NOAA WX ch#
80
  u8 area;              // Area Selected
81
} settings;
82

    
83
#seekto 0x0D00;
84
struct {
85
  char name[6];
86
  u8 unknown1[2];
87
} names[%d];
88
"""
89

    
90
CMD_ACK = "\x06"
91

    
92
TONES = chirp_common.TONES
93
TMODES = ["", "Tone", "DTCS", "DTCS"]
94

    
95
AB_LIST = ["A", "B"]
96
ABR_LIST = ["OFF", "ON", "Key"]
97
AREA_LIST = ["China", "Japan", "Korea", "Malaysia", "American",
98
             "Australia", "Iran", "Taiwan", "Europe", "Russia"]
99
MDF_LIST = ["Frequency", "Channel #", "Name"]
100
RING_LIST = ["OFF"] + ["%s" % x for x in range(1, 11)]
101
TOT_LIST = ["OFF"] + ["%s seconds" % x for x in range(30, 210, 30)]
102
TOT2_LIST = TOT_LIST[1:]
103
VOICE_LIST = ["Off", "Chinese", "English"]
104
VOX_LIST = ["OFF"] + ["%s" % x for x in range(1, 6)]
105
WORKMODE_LIST = ["General", "PMR"]
106
WX_LIST = ["CH01 - 162.550",
107
           "CH02 - 162.400",
108
           "CH03 - 162.475",
109
           "CH04 - 162.425",
110
           "CH05 - 162.450",
111
           "CH06 - 162.500",
112
           "CH07 - 162.525",
113
           "CH08 - 161.650",
114
           "CH09 - 161.775",
115
           "CH10 - 161.750",
116
           "CH11 - 162.000"
117
           ]
118

    
119
SETTING_LISTS = {
120
    "ab": AB_LIST,
121
    "abr": ABR_LIST,
122
    "area": AREA_LIST,
123
    "mdf": MDF_LIST,
124
    "ring": RING_LIST,
125
    "tot": TOT_LIST,
126
    "tot": TOT2_LIST,
127
    "voice": VOICE_LIST,
128
    "vox": VOX_LIST,
129
    "workmode": WORKMODE_LIST,
130
    "wx": WX_LIST,
131
    }
132

    
133
FRS_FREQS1 = [462.5625, 462.5875, 462.6125, 462.6375, 462.6625,
134
              462.6875, 462.7125]
135
FRS_FREQS2 = [467.5625, 467.5875, 467.6125, 467.6375, 467.6625,
136
              467.6875, 467.7125]
137
FRS_FREQS3 = [462.5500, 462.5750, 462.6000, 462.6250, 462.6500,
138
              462.6750, 462.7000, 462.7250]
139
FRS_FREQS = FRS_FREQS1 + FRS_FREQS2 + FRS_FREQS3
140

    
141

    
142
def _enter_programming_mode(radio):
143
    serial = radio.pipe
144

    
145
    exito = False
146
    for i in range(0, 5):
147
        serial.write(radio._magic)
148
        ack = serial.read(1)
149

    
150
        try:
151
            if ack == CMD_ACK:
152
                exito = True
153
                break
154
        except:
155
            LOG.debug("Attempt #%s, failed, trying again" % i)
156
            pass
157

    
158
    # check if we had EXITO
159
    if exito is False:
160
        _exit_programming_mode(radio)
161
        msg = "The radio did not accept program mode after five tries.\n"
162
        msg += "Check you interface cable and power cycle your radio."
163
        raise errors.RadioError(msg)
164

    
165
    try:
166
        serial.write("\x02")
167
        ident = serial.read(len(radio._fingerprint))
168
    except:
169
        _exit_programming_mode(radio)
170
        raise errors.RadioError("Error communicating with radio")
171

    
172
    if not ident == radio._fingerprint:
173
        _exit_programming_mode(radio)
174
        LOG.debug(util.hexprint(ident))
175
        raise errors.RadioError("Radio returned unknown identification string")
176

    
177
    try:
178
        serial.write(CMD_ACK)
179
        ack = serial.read(1)
180
    except:
181
        _exit_programming_mode(radio)
182
        raise errors.RadioError("Error communicating with radio")
183

    
184
    if ack != CMD_ACK:
185
        _exit_programming_mode(radio)
186
        raise errors.RadioError("Radio refused to enter programming mode")
187

    
188

    
189
def _exit_programming_mode(radio):
190
    serial = radio.pipe
191
    try:
192
        serial.write("E")
193
    except:
194
        raise errors.RadioError("Radio refused to exit programming mode")
195

    
196

    
197
def _read_block(radio, block_addr, block_size):
198
    serial = radio.pipe
199

    
200
    cmd = struct.pack(">cHb", 'R', block_addr, block_size)
201
    expectedresponse = "W" + cmd[1:]
202
    LOG.debug("Reading block %04x..." % (block_addr))
203

    
204
    try:
205
        serial.write(cmd)
206
        response = serial.read(4 + block_size)
207
        if response[:4] != expectedresponse:
208
            raise Exception("Error reading block %04x." % (block_addr))
209

    
210
        block_data = response[4:]
211

    
212
        serial.write(CMD_ACK)
213
        ack = serial.read(1)
214
    except:
215
        _exit_programming_mode(radio)
216
        raise errors.RadioError("Failed to read block at %04x" % block_addr)
217

    
218
    if ack != CMD_ACK:
219
        _exit_programming_mode(radio)
220
        raise Exception("No ACK reading block %04x." % (block_addr))
221

    
222
    return block_data
223

    
224

    
225
def _write_block(radio, block_addr, block_size):
226
    serial = radio.pipe
227

    
228
    cmd = struct.pack(">cHb", 'W', block_addr, block_size)
229
    data = radio.get_mmap()[block_addr:block_addr + block_size]
230

    
231
    LOG.debug("Writing Data:")
232
    LOG.debug(util.hexprint(cmd + data))
233

    
234
    try:
235
        serial.write(cmd + data)
236
        if serial.read(1) != CMD_ACK:
237
            raise Exception("No ACK")
238
    except:
239
        _exit_programming_mode(radio)
240
        raise errors.RadioError("Failed to send block "
241
                                "to radio at %04x" % block_addr)
242

    
243

    
244
def do_download(radio):
245
    LOG.debug("download")
246
    _enter_programming_mode(radio)
247

    
248
    data = ""
249

    
250
    status = chirp_common.Status()
251
    status.msg = "Cloning from radio"
252

    
253
    status.cur = 0
254
    status.max = radio._memsize
255

    
256
    for addr in range(0, radio._memsize, radio.BLOCK_SIZE):
257
        status.cur = addr + radio.BLOCK_SIZE
258
        radio.status_fn(status)
259

    
260
        block = _read_block(radio, addr, radio.BLOCK_SIZE)
261
        data += block
262

    
263
        LOG.debug("Address: %04x" % addr)
264
        LOG.debug(util.hexprint(block))
265

    
266
    _exit_programming_mode(radio)
267

    
268
    return memmap.MemoryMap(data)
269

    
270

    
271
def do_upload(radio):
272
    status = chirp_common.Status()
273
    status.msg = "Uploading to radio"
274

    
275
    _enter_programming_mode(radio)
276

    
277
    status.cur = 0
278
    status.max = radio._memsize
279

    
280
    for start_addr, end_addr in radio._ranges:
281
        for addr in range(start_addr, end_addr, radio.BLOCK_SIZE_UP):
282
            status.cur = addr + radio.BLOCK_SIZE_UP
283
            radio.status_fn(status)
284
            _write_block(radio, addr, radio.BLOCK_SIZE_UP)
285

    
286
    _exit_programming_mode(radio)
287

    
288

    
289
class BFT8Radio(chirp_common.CloneModeRadio):
290
    """Baofeng BF-T8"""
291
    VENDOR = "Baofeng"
292
    MODEL = "BF-T8"
293
    BAUD_RATE = 9600
294
    BLOCK_SIZE = BLOCK_SIZE_UP = 0x10
295
    ODD_SPLIT = True
296
    HAS_NAMES = False
297
    NAME_LENGTH = 0
298
    VALID_CHARS = []
299
    CH_OFFSET = False
300
    SKIP_VALUES = []
301
    DTCS_CODES = sorted(chirp_common.DTCS_CODES)
302

    
303
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=2.00),
304
                    chirp_common.PowerLevel("Low", watts=0.50)]
305
    VALID_BANDS = [(400000000, 470000000)]
306

    
307
    _magic = "\x02" + "PROGRAM"
308
    _fingerprint = "\x2E" + "BF-T6" + "\x2E"
309
    _upper = 99
310
    _mem_params = (_upper,  # number of channels
311
                   _upper   # number of names
312
                   )
313
    _frs = False
314

    
315
    _ranges = [
316
               (0x0000, 0x0B60),
317
              ]
318
    _memsize = 0x0B60
319

    
320
    def get_features(self):
321
        rf = chirp_common.RadioFeatures()
322
        rf.has_settings = True
323
        rf.has_bank = False
324
        rf.has_ctone = True
325
        rf.has_cross = True
326
        rf.has_rx_dtcs = True
327
        rf.has_tuning_step = False
328
        rf.has_name = self.HAS_NAMES
329
        rf.can_odd_split = self.ODD_SPLIT
330
        rf.valid_name_length = self.NAME_LENGTH
331
        rf.valid_characters = self.VALID_CHARS
332
        rf.valid_skips = self.SKIP_VALUES
333
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
334
        rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone",
335
                                "->Tone", "->DTCS", "DTCS->", "DTCS->DTCS"]
336
        rf.valid_dtcs_codes = self.DTCS_CODES
337
        rf.valid_power_levels = self.POWER_LEVELS
338
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
339
        rf.valid_modes = ["FM", "NFM"]  # 25 kHz, 12.5 KHz.
340
        rf.memory_bounds = (1, self._upper)
341
        rf.valid_tuning_steps = [2.5, 5., 6.25, 10., 12.5, 25.]
342
        rf.valid_bands = self.VALID_BANDS
343

    
344
        return rf
345

    
346
    def process_mmap(self):
347
        self._memobj = bitwise.parse(MEM_FORMAT % self._mem_params, self._mmap)
348

    
349
    def validate_memory(self, mem):
350
        msgs = ""
351
        msgs = chirp_common.CloneModeRadio.validate_memory(self, mem)
352

    
353
        _msg_freq = 'Memory location cannot change frequency'
354
        _msg_simplex = 'Memory location only supports Duplex:(None)'
355
        _msg_nfm = 'Memory location only supports Mode: NFM'
356
        _msg_txp = 'Memory location only supports Power: Low'
357

    
358
        # FRS only models
359
        if self._frs:
360
            # range of memories with values set by FCC rules
361
            if mem.freq != int(FRS_FREQS[mem.number - 1] * 1000000):
362
                # warn user can't change frequency
363
                msgs.append(chirp_common.ValidationError(_msg_freq))
364

    
365
            # channels 1 - 22 are simplex only
366
            if str(mem.duplex) != "":
367
                # warn user can't change duplex
368
                msgs.append(chirp_common.ValidationError(_msg_simplex))
369

    
370
            # channels 1 - 22 are NFM only
371
            if str(mem.mode) != "NFM":
372
                # warn user can't change mode
373
                msgs.append(chirp_common.ValidationError(_msg_nfm))
374

    
375
            # channels 8 - 14 are low power only
376
            if mem.number >= 8 and mem.number <= 14:
377
                if str(mem.power) != "Low":
378
                    # warn user can't change power
379
                    msgs.append(chirp_common.ValidationError(_msg_txp))
380

    
381
        return msgs
382

    
383
    def sync_in(self):
384
        """Download from radio"""
385
        try:
386
            data = do_download(self)
387
        except errors.RadioError:
388
            # Pass through any real errors we raise
389
            raise
390
        except:
391
            # If anything unexpected happens, make sure we raise
392
            # a RadioError and log the problem
393
            LOG.exception('Unexpected error during download')
394
            raise errors.RadioError('Unexpected error communicating '
395
                                    'with the radio')
396
        self._mmap = data
397
        self.process_mmap()
398

    
399
    def sync_out(self):
400
        """Upload to radio"""
401
        try:
402
            do_upload(self)
403
        except:
404
            # If anything unexpected happens, make sure we raise
405
            # a RadioError and log the problem
406
            LOG.exception('Unexpected error during upload')
407
            raise errors.RadioError('Unexpected error communicating '
408
                                    'with the radio')
409

    
410
    def get_raw_memory(self, number):
411
        return repr(self._memobj.memory[number - 1])
412

    
413
    def _get_tone(self, mem, _mem):
414
        rx_tone = tx_tone = None
415

    
416
        tx_tmode = TMODES[_mem.tx_tmode]
417
        rx_tmode = TMODES[_mem.rx_tmode]
418

    
419
        if tx_tmode == "Tone":
420
            tx_tone = TONES[_mem.tx_tone]
421
        elif tx_tmode == "DTCS":
422
            tx_tone = self.DTCS_CODES[_mem.tx_tone]
423

    
424
        if rx_tmode == "Tone":
425
            rx_tone = TONES[_mem.rx_tone]
426
        elif rx_tmode == "DTCS":
427
            rx_tone = self.DTCS_CODES[_mem.rx_tone]
428

    
429
        tx_pol = _mem.tx_tmode == 0x03 and "R" or "N"
430
        rx_pol = _mem.rx_tmode == 0x03 and "R" or "N"
431

    
432
        chirp_common.split_tone_decode(mem, (tx_tmode, tx_tone, tx_pol),
433
                                       (rx_tmode, rx_tone, rx_pol))
434

    
435
    def _get_mem(self, number):
436
        return self._memobj.memory[number - 1]
437

    
438
    def _get_nam(self, number):
439
        return self._memobj.names[number - 1]
440

    
441
    def get_memory(self, number):
442
        _mem = self._get_mem(number)
443
        if self.HAS_NAMES:
444
            _nam = self._get_nam(number)
445

    
446
        mem = chirp_common.Memory()
447

    
448
        mem.number = number
449
        mem.freq = int(_mem.rxfreq) * 10
450

    
451
        # We'll consider any blank (i.e. 0MHz frequency) to be empty
452
        if mem.freq == 0:
453
            mem.empty = True
454
            return mem
455

    
456
        if _mem.rxfreq.get_raw() == "\xFF\xFF\xFF\xFF":
457
            mem.freq = 0
458
            mem.empty = True
459
            return mem
460

    
461
        if _mem.get_raw() == ("\xFF" * 16):
462
            LOG.debug("Initializing empty memory")
463
            _mem.set_raw("\x00" * 13 + "\xFF" * 3)
464

    
465
        if int(_mem.rxfreq) == int(_mem.txfreq):
466
            mem.duplex = ""
467
            mem.offset = 0
468
        else:
469
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
470
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
471

    
472
        # wide/narrow
473
        mem.mode = _mem.isnarrow and "NFM" or "FM"
474

    
475
        mem.skip = _mem.skip and "S" or ""
476

    
477
        if self.HAS_NAMES:
478
            for char in _nam.name:
479
                if str(char) == "\xFF":
480
                    char = " "  # The OEM software may have 0xFF mid-name
481
                mem.name += str(char)
482
            mem.name = mem.name.rstrip()
483

    
484
        # tone data
485
        self._get_tone(mem, _mem)
486

    
487
        # tx power
488
        levels = self.POWER_LEVELS
489
        try:
490
            mem.power = levels[_mem.lowpower]
491
        except IndexError:
492
            LOG.error("Radio reported invalid power level %s (in %s)" %
493
                      (_mem.lowpower, levels))
494
            mem.power = levels[0]
495

    
496
        if mem.number <= 22 and self._frs:
497
            FRS_IMMUTABLE = ["freq", "duplex", "offset", "mode"]
498
            if mem.number >= 8 and mem.number <= 14:
499
                mem.immutable = FRS_IMMUTABLE + ["power"]
500
            else:
501
                mem.immutable = FRS_IMMUTABLE
502

    
503
        return mem
504

    
505
    def _set_tone(self, mem, _mem):
506
        ((txmode, txtone, txpol),
507
         (rxmode, rxtone, rxpol)) = chirp_common.split_tone_encode(mem)
508

    
509
        _mem.tx_tmode = TMODES.index(txmode)
510
        _mem.rx_tmode = TMODES.index(rxmode)
511
        if txmode == "Tone":
512
            _mem.tx_tone = TONES.index(txtone)
513
        elif txmode == "DTCS":
514
            _mem.tx_tmode = txpol == "R" and 0x03 or 0x02
515
            _mem.tx_tone = self.DTCS_CODES.index(txtone)
516
        if rxmode == "Tone":
517
            _mem.rx_tone = TONES.index(rxtone)
518
        elif rxmode == "DTCS":
519
            _mem.rx_tmode = rxpol == "R" and 0x03 or 0x02
520
            _mem.rx_tone = self.DTCS_CODES.index(rxtone)
521

    
522
    def _set_mem(self, number):
523
        return self._memobj.memory[number - 1]
524

    
525
    def _set_nam(self, number):
526
        return self._memobj.names[number - 1]
527

    
528
    def set_memory(self, mem):
529
        _mem = self._set_mem(mem.number)
530
        if self.HAS_NAMES:
531
            _nam = self._set_nam(mem.number)
532

    
533
        # if empty memmory
534
        if mem.empty:
535
            if self.HAS_NAMES:
536
                for i in range(0, self.NAME_LENGTH):
537
                    _nam.name[i].set_raw("\xFF")
538
            if self._frs:
539
                if mem.number <= 22:
540
                    _mem.set_raw("\xFF" * 8 + "\x00" * 5 + "\xFF" * 3)
541
                    FRS_FREQ = int(FRS_FREQS[mem.number - 1] * 100000)
542
                    _mem.rxfreq = _mem.txfreq = FRS_FREQ
543
                    _mem.isnarrow = True
544
                    if mem.number >= 8 and mem.number <= 14:
545
                        _mem.lowpower = True
546
                    else:
547
                        _mem.lowpower = False
548
                else:
549
                    _mem.set_raw("\xff" * 16)
550
            else:
551
                _mem.set_raw("\xFF" * 8 + "\x00" * 4 + "\x03" + "\xFF" * 3)
552

    
553
            return mem
554

    
555
        _mem.set_raw("\x00" * 13 + "\xFF" * 3)
556

    
557
        # frequency
558
        _mem.rxfreq = mem.freq / 10
559

    
560
        if mem.duplex == "off":
561
            for i in range(0, 4):
562
                _mem.txfreq[i].set_raw("\xFF")
563
        elif mem.duplex == "split":
564
            _mem.txfreq = mem.offset / 10
565
        elif mem.duplex == "+":
566
            _mem.txfreq = (mem.freq + mem.offset) / 10
567
        elif mem.duplex == "-":
568
            _mem.txfreq = (mem.freq - mem.offset) / 10
569
        else:
570
            _mem.txfreq = mem.freq / 10
571

    
572
        # wide/narrow
573
        _mem.isnarrow = mem.mode == "NFM"
574

    
575
        _mem.skip = mem.skip == "S"
576

    
577
        if self.HAS_NAMES:
578
            for i in range(self.NAME_LENGTH):
579
                try:
580
                    _nam.name[i] = mem.name[i]
581
                except IndexError:
582
                    _nam.name[i] = "\xFF"
583

    
584
        # tone data
585
        self._set_tone(mem, _mem)
586

    
587
        # tx power
588
        if mem.power:
589
            _mem.lowpower = self.POWER_LEVELS.index(mem.power)
590
        else:
591
            _mem.lowpower = 0
592

    
593
        return mem
594

    
595
    def get_settings(self):
596
        _settings = self._memobj.settings
597
        basic = RadioSettingGroup("basic", "Basic Settings")
598
        top = RadioSettings(basic)
599

    
600
        # Menu 03
601
        rs = RadioSettingValueInteger(0, 9, _settings.squelch)
602
        rset = RadioSetting("squelch", "Squelch Level", rs)
603
        basic.append(rset)
604

    
605
        model_list = ["RB27B", ]
606
        if self.MODEL in model_list:
607
            # Menu 09 (RB27x)
608
            rs = RadioSettingValueList(TOT2_LIST, TOT2_LIST[_settings.tot])
609
        else:
610
            # Menu 11
611
            rs = RadioSettingValueList(TOT_LIST, TOT_LIST[_settings.tot])
612
        rset = RadioSetting("tot", "Time-out timer", rs)
613
        basic.append(rset)
614

    
615
        # Menu 06
616
        rs = RadioSettingValueList(VOX_LIST, VOX_LIST[_settings.vox])
617
        rset = RadioSetting("vox", "VOX Level", rs)
618
        basic.append(rset)
619

    
620
        # Menu 15 (BF-T8) / 12 (RB-27/RB627)
621
        rs = RadioSettingValueList(VOICE_LIST, VOICE_LIST[_settings.voice])
622
        rset = RadioSetting("voice", "Voice", rs)
623
        basic.append(rset)
624

    
625
        # Menu 12
626
        rs = RadioSettingValueBoolean(_settings.bcl)
627
        rset = RadioSetting("bcl", "Busy Channel Lockout", rs)
628
        basic.append(rset)
629

    
630
        # Menu 10 / 08 (RB27/RB627)
631
        rs = RadioSettingValueBoolean(_settings.save)
632
        rset = RadioSetting("save", "Battery Saver", rs)
633
        basic.append(rset)
634

    
635
        # Menu 08 / 07 (RB-27/RB627)
636
        rs = RadioSettingValueBoolean(_settings.tdr)
637
        rset = RadioSetting("tdr", "Dual Watch", rs)
638
        basic.append(rset)
639

    
640
        # Menu 05
641
        rs = RadioSettingValueBoolean(_settings.beep)
642
        rset = RadioSetting("beep", "Beep", rs)
643
        basic.append(rset)
644

    
645
        # Menu 04
646
        rs = RadioSettingValueList(ABR_LIST, ABR_LIST[_settings.abr])
647
        rset = RadioSetting("abr", "Back Light", rs)
648
        basic.append(rset)
649

    
650
        # Menu 13 / 11 (RB-27/RB627)
651
        rs = RadioSettingValueList(RING_LIST, RING_LIST[_settings.ring])
652
        rset = RadioSetting("ring", "Ring", rs)
653
        basic.append(rset)
654

    
655
        rs = RadioSettingValueBoolean(not _settings.ste)
656
        rset = RadioSetting("ste", "Squelch Tail Eliminate", rs)
657
        basic.append(rset)
658

    
659
        #
660

    
661
        if self.CH_OFFSET:
662
            rs = RadioSettingValueInteger(1, self._upper, _settings.mra + 1)
663
        else:
664
            rs = RadioSettingValueInteger(1, self._upper, _settings.mra)
665
        rset = RadioSetting("mra", "MR A Channel #", rs)
666
        basic.append(rset)
667

    
668
        if self.CH_OFFSET:
669
            rs = RadioSettingValueInteger(1, self._upper, _settings.mrb + 1)
670
        else:
671
            rs = RadioSettingValueInteger(1, self._upper, _settings.mrb)
672
        rset = RadioSetting("mrb", "MR B Channel #", rs)
673
        basic.append(rset)
674

    
675
        rs = RadioSettingValueList(AB_LIST, AB_LIST[_settings.disp_ab])
676
        rset = RadioSetting("disp_ab", "Selected Display Line", rs)
677
        basic.append(rset)
678

    
679
        rs = RadioSettingValueList(WX_LIST, WX_LIST[_settings.wx])
680
        rset = RadioSetting("wx", "NOAA WX Radio", rs)
681
        basic.append(rset)
682

    
683
        def myset_freq(setting, obj, atrb, mult):
684
            """ Callback to set frequency by applying multiplier"""
685
            value = int(float(str(setting.value)) * mult)
686
            setattr(obj, atrb, value)
687
            return
688

    
689
        # FM Broadcast Settings
690
        val = _settings.fmcur
691
        val = val / 10.0
692
        val_low = 76.0
693
        if val < val_low or val > 108.0:
694
            val = 90.4
695
        rx = RadioSettingValueFloat(val_low, 108.0, val, 0.1, 1)
696
        rset = RadioSetting("settings.fmcur", "Broadcast FM Radio (MHz)", rx)
697
        rset.set_apply_callback(myset_freq, _settings, "fmcur", 10)
698
        basic.append(rset)
699

    
700
        model_list = ["BF-T8", "BF-U9", "AR-8"]
701
        if self.MODEL in model_list:
702
            rs = RadioSettingValueList(WORKMODE_LIST,
703
                                       WORKMODE_LIST[_settings.workmode])
704
            rset = RadioSetting("workmode", "Work Mode", rs)
705
            basic.append(rset)
706

    
707
            rs = RadioSettingValueList(AREA_LIST, AREA_LIST[_settings.area])
708
            rs.set_mutable(False)
709
            rset = RadioSetting("area", "Area", rs)
710
            basic.append(rset)
711

    
712
        return top
713

    
714
    def set_settings(self, settings):
715
        for element in settings:
716
            if not isinstance(element, RadioSetting):
717
                self.set_settings(element)
718
                continue
719
            else:
720
                try:
721
                    if "." in element.get_name():
722
                        bits = element.get_name().split(".")
723
                        obj = self._memobj
724
                        for bit in bits[:-1]:
725
                            obj = getattr(obj, bit)
726
                        setting = bits[-1]
727
                    else:
728
                        obj = self._memobj.settings
729
                        setting = element.get_name()
730

    
731
                    if element.has_apply_callback():
732
                        LOG.debug("Using apply callback")
733
                        element.run_apply_callback()
734
                    elif setting == "mra" and self.CH_OFFSET:
735
                        setattr(obj, setting, int(element.value) - 1)
736
                    elif setting == "mrb" and self.CH_OFFSET:
737
                        setattr(obj, setting, int(element.value) - 1)
738
                    elif setting == "ste":
739
                        setattr(obj, setting, not int(element.value))
740
                    elif element.value.get_mutable():
741
                        LOG.debug("Setting %s = %s" % (setting, element.value))
742
                        setattr(obj, setting, element.value)
743
                except Exception, e:
744
                    LOG.debug(element.get_name())
745
                    raise
746

    
747
    @classmethod
748
    def match_model(cls, filedata, filename):
749
        # This radio has always been post-metadata, so never do
750
        # old-school detection
751
        return False
752

    
753

    
754
class BFU9Alias(chirp_common.Alias):
755
    VENDOR = "Baofeng"
756
    MODEL = "BF-U9"
757

    
758

    
759
class AR8Alias(chirp_common.Alias):
760
    VENDOR = "Arcshell"
761
    MODEL = "AR-8"
762

    
763

    
764
@directory.register
765
class BaofengBFT8Generic(BFT8Radio):
766
    ALIASES = [BFU9Alias, AR8Alias, ]
767

    
768

    
769
@directory.register
770
class RetevisRT16(BFT8Radio):
771
    VENDOR = "Retevis"
772
    MODEL = "RT16"
773

    
774
    _upper = 22
775
    _frs = True
776

    
777

    
778
@directory.register
779
class RetevisRT27B(BFT8Radio):
780
    VENDOR = "Retevis"
781
    MODEL = "RB27B"
782
    DTCS_CODES = sorted(chirp_common.DTCS_CODES + [645])
783
    HAS_NAMES = True
784
    NAME_LENGTH = 6
785
    VALID_CHARS = chirp_common.CHARSET_UPPER_NUMERIC + "-"
786
    CH_OFFSET = True
787
    SKIP_VALUES = ["", "S"]
788
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=2.00),
789
                    chirp_common.PowerLevel("Low", watts=0.50)]
790
    VALID_BANDS = [(400000000, 520000000)]
791

    
792
    _upper = 22
793
    _frs = True
794

    
795
    _ranges = [
796
               (0x0000, 0x0640),
797
               (0x0D00, 0x1040),
798
              ]
799
    _memsize = 0x1040
(2-2/2)