bf-t8_2 rb27 - gmrs.py

Jim Unroe, 12/20/2021 02:11 pm

Download (28.9 kB)

 
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
  ul16 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
           ]
114

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

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

    
137
GMRS_FREQS = FRS_FREQS + FRS_FREQS3
138

    
139

    
140
def _enter_programming_mode(radio):
141
    serial = radio.pipe
142

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

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

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

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

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

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

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

    
186

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

    
194

    
195
def _read_block(radio, block_addr, block_size):
196
    serial = radio.pipe
197

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

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

    
208
        block_data = response[4:]
209

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

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

    
220
    return block_data
221

    
222

    
223
def _write_block(radio, block_addr, block_size):
224
    serial = radio.pipe
225

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

    
229
    LOG.debug("Writing Data:")
230
    LOG.debug(util.hexprint(cmd + data))
231

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

    
241

    
242
def do_download(radio):
243
    LOG.debug("download")
244
    _enter_programming_mode(radio)
245

    
246
    data = ""
247

    
248
    status = chirp_common.Status()
249
    status.msg = "Cloning from radio"
250

    
251
    status.cur = 0
252
    status.max = radio._memsize
253

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

    
258
        block = _read_block(radio, addr, radio.BLOCK_SIZE)
259
        data += block
260

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

    
264
    _exit_programming_mode(radio)
265

    
266
    return memmap.MemoryMap(data)
267

    
268

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

    
273
    _enter_programming_mode(radio)
274

    
275
    status.cur = 0
276
    status.max = radio._memsize
277

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

    
284
    _exit_programming_mode(radio)
285

    
286

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

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

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

    
313
    _ranges = [
314
               (0x0000, 0x0B60),
315
              ]
316
    _memsize = 0x0B60
317

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

    
342
        return rf
343

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

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

    
351
        _msg_freq = 'Memory location cannot change frequency'
352
        _msg_simplex = 'Memory location only supports Duplex:(None)'
353
        _msg_duplex = 'Memory location only supports Duplex: +'
354
        _msg_duplex2 = 'Memory location only supports "(None)" or "off"'
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
        # GMRS only models
382
        if self._gmrs and mem.number <= 30:
383
            # range of memories with values set by FCC rules
384
            if mem.freq != int(GMRS_FREQS[mem.number - 1] * 1000000):
385
                # warn user can't change frequency
386
                msgs.append(chirp_common.ValidationError(_msg_freq))
387

    
388
            # channels 1 - 22 are simplex only
389
            if mem.number >= 1 and mem.number <= 22:
390
                if str(mem.duplex) != "":
391
                    # warn user can't change duplex
392
                    msgs.append(chirp_common.ValidationError(_msg_simplex))
393

    
394
            # channels 21 - 30 are + duplex only
395
            if mem.number >= 21 and mem.number <= 30:
396
                if str(mem.duplex) != "+":
397
                    # warn user can't change duplex
398
                    msgs.append(chirp_common.ValidationError(_msg_duplex))
399

    
400
            # channels 8 - 14 are low power NFM only
401
            if mem.number >= 8 and mem.number <= 14:
402
                if str(mem.power) != "Low":
403
                    # warn user can't change power
404
                    msgs.append(chirp_common.ValidationError(_msg_txp))
405

    
406
                if str(mem.mode) != "NFM":
407
                    # warn user can't change mode
408
                    msgs.append(chirp_common.ValidationError(_msg_nfm))
409

    
410
        return msgs
411

    
412
    def sync_in(self):
413
        """Download from radio"""
414
        try:
415
            data = do_download(self)
416
        except errors.RadioError:
417
            # Pass through any real errors we raise
418
            raise
419
        except:
420
            # If anything unexpected happens, make sure we raise
421
            # a RadioError and log the problem
422
            LOG.exception('Unexpected error during download')
423
            raise errors.RadioError('Unexpected error communicating '
424
                                    'with the radio')
425
        self._mmap = data
426
        self.process_mmap()
427

    
428
    def sync_out(self):
429
        """Upload to radio"""
430
        try:
431
            do_upload(self)
432
        except:
433
            # If anything unexpected happens, make sure we raise
434
            # a RadioError and log the problem
435
            LOG.exception('Unexpected error during upload')
436
            raise errors.RadioError('Unexpected error communicating '
437
                                    'with the radio')
438

    
439
    def get_raw_memory(self, number):
440
        return repr(self._memobj.memory[number - 1])
441

    
442
    def _get_tone(self, mem, _mem):
443
        rx_tone = tx_tone = None
444

    
445
        tx_tmode = TMODES[_mem.tx_tmode]
446
        rx_tmode = TMODES[_mem.rx_tmode]
447

    
448
        if tx_tmode == "Tone":
449
            tx_tone = TONES[_mem.tx_tone]
450
        elif tx_tmode == "DTCS":
451
            tx_tone = self.DTCS_CODES[_mem.tx_tone]
452

    
453
        if rx_tmode == "Tone":
454
            rx_tone = TONES[_mem.rx_tone]
455
        elif rx_tmode == "DTCS":
456
            rx_tone = self.DTCS_CODES[_mem.rx_tone]
457

    
458
        tx_pol = _mem.tx_tmode == 0x03 and "R" or "N"
459
        rx_pol = _mem.rx_tmode == 0x03 and "R" or "N"
460

    
461
        chirp_common.split_tone_decode(mem, (tx_tmode, tx_tone, tx_pol),
462
                                       (rx_tmode, rx_tone, rx_pol))
463

    
464
    def _is_txinh(self, _mem):
465
        raw_tx = ""
466
        for i in range(0, 4):
467
            raw_tx += _mem.txfreq[i].get_raw()
468
        return raw_tx == "\xFF\xFF\xFF\xFF"
469

    
470
    def _get_mem(self, number):
471
        return self._memobj.memory[number - 1]
472

    
473
    def _get_nam(self, number):
474
        return self._memobj.names[number - 1]
475

    
476
    def get_memory(self, number):
477
        _mem = self._get_mem(number)
478
        if self.HAS_NAMES:
479
            _nam = self._get_nam(number)
480

    
481
        mem = chirp_common.Memory()
482

    
483
        mem.number = number
484
        mem.freq = int(_mem.rxfreq) * 10
485

    
486
        # We'll consider any blank (i.e. 0MHz frequency) to be empty
487
        if mem.freq == 0:
488
            mem.empty = True
489
            return mem
490

    
491
        if _mem.rxfreq.get_raw() == "\xFF\xFF\xFF\xFF":
492
            mem.freq = 0
493
            mem.empty = True
494
            return mem
495

    
496
        if _mem.get_raw() == ("\xFF" * 16):
497
            LOG.debug("Initializing empty memory")
498
            _mem.set_raw("\x00" * 13 + "\xFF" * 3)
499

    
500
        if self._is_txinh(_mem):
501
            mem.duplex = "off"
502
            mem.offset = 0
503
        elif int(_mem.rxfreq) == int(_mem.txfreq):
504
            mem.duplex = ""
505
            mem.offset = 0
506
        else:
507
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
508
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
509

    
510
        # wide/narrow
511
        mem.mode = _mem.isnarrow and "NFM" or "FM"
512

    
513
        mem.skip = _mem.skip and "S" or ""
514

    
515
        if self.HAS_NAMES:
516
            for char in _nam.name:
517
                if str(char) == "\xFF":
518
                    char = " "  # The OEM software may have 0xFF mid-name
519
                mem.name += str(char)
520
            mem.name = mem.name.rstrip()
521

    
522
        # tone data
523
        self._get_tone(mem, _mem)
524

    
525
        # tx power
526
        levels = self.POWER_LEVELS
527
        try:
528
            mem.power = levels[_mem.lowpower]
529
        except IndexError:
530
            LOG.error("Radio reported invalid power level %s (in %s)" %
531
                      (_mem.lowpower, levels))
532
            mem.power = levels[0]
533

    
534
        if mem.number <= 22 and self._frs:
535
            FRS_IMMUTABLE = ["freq", "duplex", "offset", "mode"]
536
            if mem.number >= 8 and mem.number <= 14:
537
                mem.immutable = FRS_IMMUTABLE + ["power"]
538
            else:
539
                mem.immutable = FRS_IMMUTABLE
540

    
541
        if mem.number <= 30 and self._gmrs:
542
            GMRS_IMMUTABLE = ["freq", "duplex", "offset"]
543
            if mem.number >= 8 and mem.number <= 14:
544
                mem.immutable = GMRS_IMMUTABLE + ["mode", "power"]
545
            else:
546
                mem.immutable = GMRS_IMMUTABLE
547

    
548
        return mem
549

    
550
    def _set_tone(self, mem, _mem):
551
        ((txmode, txtone, txpol),
552
         (rxmode, rxtone, rxpol)) = chirp_common.split_tone_encode(mem)
553

    
554
        _mem.tx_tmode = TMODES.index(txmode)
555
        _mem.rx_tmode = TMODES.index(rxmode)
556
        if txmode == "Tone":
557
            _mem.tx_tone = TONES.index(txtone)
558
        elif txmode == "DTCS":
559
            _mem.tx_tmode = txpol == "R" and 0x03 or 0x02
560
            _mem.tx_tone = self.DTCS_CODES.index(txtone)
561
        if rxmode == "Tone":
562
            _mem.rx_tone = TONES.index(rxtone)
563
        elif rxmode == "DTCS":
564
            _mem.rx_tmode = rxpol == "R" and 0x03 or 0x02
565
            _mem.rx_tone = self.DTCS_CODES.index(rxtone)
566

    
567
    def _set_mem(self, number):
568
        return self._memobj.memory[number - 1]
569

    
570
    def _set_nam(self, number):
571
        return self._memobj.names[number - 1]
572

    
573
    def set_memory(self, mem):
574
        _mem = self._set_mem(mem.number)
575
        if self.HAS_NAMES:
576
            _nam = self._set_nam(mem.number)
577

    
578
        # if empty memmory
579
        if mem.empty:
580
            if self.HAS_NAMES:
581
                for i in range(0, self.NAME_LENGTH):
582
                    _nam.name[i].set_raw("\xFF")
583
            if self._frs:
584
                if mem.number <= 22:
585
                    _mem.set_raw("\xFF" * 8 + "\x00" * 5 + "\xFF" * 3)
586
                    FRS_FREQ = int(FRS_FREQS[mem.number - 1] * 100000)
587
                    _mem.rxfreq = _mem.txfreq = FRS_FREQ
588
                    _mem.isnarrow = True
589
                    if mem.number >= 8 and mem.number <= 14:
590
                        _mem.lowpower = True
591
                    else:
592
                        _mem.lowpower = False
593
                else:
594
                    _mem.set_raw("\xff" * 16)
595
            elif self._gmrs:
596
                if mem.number <= 30:
597
                    _mem.set_raw("\xFF" * 8 + "\x00" * 5 + "\xFF" * 3)
598
                    GMRS_FREQ = int(GMRS_FREQS[mem.number - 1] * 100000)
599
                    _mem.rxfreq = GMRS_FREQ
600
                    if mem.number >= 21 and mem.number <= 30:
601
                        _mem.txfreq = GMRS_FREQ + 500000
602
                    else:
603
                        _mem.txfreq = GMRS_FREQ
604
                    if mem.number >= 8 and mem.number <= 14:
605
                        _mem.isnarrow = True
606
                        _mem.lowpower = True
607
                    else:
608
                        _mem.isnarrow = False
609
                        _mem.lowpower = False
610
                else:
611
                    _mem.set_raw("\xFF" * 8 + "\x00" * 4 + "\x02" + "\xFF" * 3)
612
            else:
613
                _mem.set_raw("\xFF" * 8 + "\x00" * 4 + "\x03" + "\xFF" * 3)
614

    
615
            return mem
616

    
617
        _mem.set_raw("\x00" * 13 + "\xFF" * 3)
618

    
619
        if self._gmrs:
620
            if mem.number >= 1 and mem.number <= 30:
621
                GMRS_FREQ = int(GMRS_FREQS[mem.number - 1] * 1000000)
622
                mem.freq = GMRS_FREQ
623
                if mem.number <= 22:
624
                    mem.duplex = ''
625
                    mem.offset = 0
626
                    if mem.number >= 8 and mem.number <= 14:
627
                        mem.mode = "NFM"
628
                        mem.power = self.POWER_LEVELS[1]
629
                if mem.number > 22:
630
                    mem.duplex = '+'
631
                    mem.offset = 5000000
632
            if mem.number > 30:
633
                if float(mem.freq) / 1000000 in GMRS_FREQS:
634
                    if float(mem.freq) / 1000000 in FRS_FREQS2:
635
                        mem.offset = 0
636
                        mem.mode = "NFM"
637
                        mem.power = self.POWER_LEVELS[1]
638
                    if float(mem.freq) / 1000000 in FRS_FREQS3:
639
                        if mem.duplex == '+':
640
                            mem.offset = 5000000
641
                        else:
642
                            mem.duplex = ''
643
                            mem.offset = 0
644
                else:
645
                    mem.duplex = 'off'
646
                    mem.offset = 0
647

    
648
        # frequency
649
        _mem.rxfreq = mem.freq / 10
650

    
651
        if mem.duplex == "off":
652
            for i in range(0, 4):
653
                _mem.txfreq[i].set_raw("\xFF")
654
        elif mem.duplex == "split":
655
            _mem.txfreq = mem.offset / 10
656
        elif mem.duplex == "+":
657
            _mem.txfreq = (mem.freq + mem.offset) / 10
658
        elif mem.duplex == "-":
659
            _mem.txfreq = (mem.freq - mem.offset) / 10
660
        else:
661
            _mem.txfreq = mem.freq / 10
662

    
663
        # wide/narrow
664
        _mem.isnarrow = mem.mode == "NFM"
665

    
666
        _mem.skip = mem.skip == "S"
667

    
668
        if self.HAS_NAMES:
669
            for i in range(self.NAME_LENGTH):
670
                try:
671
                    _nam.name[i] = mem.name[i]
672
                except IndexError:
673
                    _nam.name[i] = "\xFF"
674

    
675
        # tone data
676
        self._set_tone(mem, _mem)
677

    
678
        # tx power
679
        if mem.power:
680
            _mem.lowpower = self.POWER_LEVELS.index(mem.power)
681
        else:
682
            _mem.lowpower = 0
683

    
684
        return mem
685

    
686
    def get_settings(self):
687
        _settings = self._memobj.settings
688
        basic = RadioSettingGroup("basic", "Basic Settings")
689
        top = RadioSettings(basic)
690

    
691
        # Menu 03
692
        rs = RadioSettingValueInteger(0, 9, _settings.squelch)
693
        rset = RadioSetting("squelch", "Squelch Level", rs)
694
        basic.append(rset)
695

    
696
        model_list = ["RB27B", ]
697
        if self.MODEL in model_list:
698
            # Menu 09 (RB27x)
699
            rs = RadioSettingValueList(TOT2_LIST, TOT2_LIST[_settings.tot])
700
        else:
701
            # Menu 11 / 09 (RB27)
702
            rs = RadioSettingValueList(TOT_LIST, TOT_LIST[_settings.tot])
703
        rset = RadioSetting("tot", "Time-out timer", rs)
704
        basic.append(rset)
705

    
706
        # Menu 06
707
        rs = RadioSettingValueList(VOX_LIST, VOX_LIST[_settings.vox])
708
        rset = RadioSetting("vox", "VOX Level", rs)
709
        basic.append(rset)
710

    
711
        # Menu 15 (BF-T8) / 12 (RB-27/RB627)
712
        rs = RadioSettingValueList(VOICE_LIST, VOICE_LIST[_settings.voice])
713
        rset = RadioSetting("voice", "Voice", rs)
714
        basic.append(rset)
715

    
716
        # Menu 12
717
        rs = RadioSettingValueBoolean(_settings.bcl)
718
        rset = RadioSetting("bcl", "Busy Channel Lockout", rs)
719
        basic.append(rset)
720

    
721
        # Menu 10 / 08 (RB27/RB627)
722
        rs = RadioSettingValueBoolean(_settings.save)
723
        rset = RadioSetting("save", "Battery Saver", rs)
724
        basic.append(rset)
725

    
726
        # Menu 08 / 07 (RB-27/RB627)
727
        rs = RadioSettingValueBoolean(_settings.tdr)
728
        rset = RadioSetting("tdr", "Dual Watch", rs)
729
        basic.append(rset)
730

    
731
        # Menu 05
732
        rs = RadioSettingValueBoolean(_settings.beep)
733
        rset = RadioSetting("beep", "Beep", rs)
734
        basic.append(rset)
735

    
736
        # Menu 04
737
        rs = RadioSettingValueList(ABR_LIST, ABR_LIST[_settings.abr])
738
        rset = RadioSetting("abr", "Back Light", rs)
739
        basic.append(rset)
740

    
741
        # Menu 13 / 11 (RB-27/RB627)
742
        rs = RadioSettingValueList(RING_LIST, RING_LIST[_settings.ring])
743
        rset = RadioSetting("ring", "Ring", rs)
744
        basic.append(rset)
745

    
746
        rs = RadioSettingValueBoolean(not _settings.ste)
747
        rset = RadioSetting("ste", "Squelch Tail Eliminate", rs)
748
        basic.append(rset)
749

    
750
        #
751

    
752
        if self.CH_OFFSET:
753
            rs = RadioSettingValueInteger(1, self._upper, _settings.mra + 1)
754
        else:
755
            rs = RadioSettingValueInteger(1, self._upper, _settings.mra)
756
        rset = RadioSetting("mra", "MR A Channel #", rs)
757
        basic.append(rset)
758

    
759
        if self.CH_OFFSET:
760
            rs = RadioSettingValueInteger(1, self._upper, _settings.mrb + 1)
761
        else:
762
            rs = RadioSettingValueInteger(1, self._upper, _settings.mrb)
763
        rset = RadioSetting("mrb", "MR B Channel #", rs)
764
        basic.append(rset)
765

    
766
        rs = RadioSettingValueList(AB_LIST, AB_LIST[_settings.disp_ab])
767
        rset = RadioSetting("disp_ab", "Selected Display Line", rs)
768
        basic.append(rset)
769

    
770
        rs = RadioSettingValueList(WX_LIST, WX_LIST[_settings.wx])
771
        rset = RadioSetting("wx", "NOAA WX Radio", rs)
772
        basic.append(rset)
773

    
774
        def myset_freq(setting, obj, atrb, mult):
775
            """ Callback to set frequency by applying multiplier"""
776
            value = int(float(str(setting.value)) * mult)
777
            setattr(obj, atrb, value)
778
            return
779

    
780
        # FM Broadcast Settings
781
        val = _settings.fmcur
782
        val = val / 10.0
783
        val_low = 76.0
784
        if val < val_low or val > 108.0:
785
            val = 90.4
786
        rx = RadioSettingValueFloat(val_low, 108.0, val, 0.1, 1)
787
        rset = RadioSetting("settings.fmcur", "Broadcast FM Radio (MHz)", rx)
788
        rset.set_apply_callback(myset_freq, _settings, "fmcur", 10)
789
        basic.append(rset)
790

    
791
        model_list = ["BF-T8", "BF-U9", "AR-8"]
792
        if self.MODEL in model_list:
793
            rs = RadioSettingValueList(WORKMODE_LIST,
794
                                       WORKMODE_LIST[_settings.workmode])
795
            rset = RadioSetting("workmode", "Work Mode", rs)
796
            basic.append(rset)
797

    
798
            rs = RadioSettingValueList(AREA_LIST, AREA_LIST[_settings.area])
799
            rs.set_mutable(False)
800
            rset = RadioSetting("area", "Area", rs)
801
            basic.append(rset)
802

    
803
        return top
804

    
805
    def set_settings(self, settings):
806
        for element in settings:
807
            if not isinstance(element, RadioSetting):
808
                self.set_settings(element)
809
                continue
810
            else:
811
                try:
812
                    if "." in element.get_name():
813
                        bits = element.get_name().split(".")
814
                        obj = self._memobj
815
                        for bit in bits[:-1]:
816
                            obj = getattr(obj, bit)
817
                        setting = bits[-1]
818
                    else:
819
                        obj = self._memobj.settings
820
                        setting = element.get_name()
821

    
822
                    if element.has_apply_callback():
823
                        LOG.debug("Using apply callback")
824
                        element.run_apply_callback()
825
                    elif setting == "mra" and self.CH_OFFSET:
826
                        setattr(obj, setting, int(element.value) - 1)
827
                    elif setting == "mrb" and self.CH_OFFSET:
828
                        setattr(obj, setting, int(element.value) - 1)
829
                    elif setting == "ste":
830
                        setattr(obj, setting, not int(element.value))
831
                    elif element.value.get_mutable():
832
                        LOG.debug("Setting %s = %s" % (setting, element.value))
833
                        setattr(obj, setting, element.value)
834
                except Exception, e:
835
                    LOG.debug(element.get_name())
836
                    raise
837

    
838
    @classmethod
839
    def match_model(cls, filedata, filename):
840
        # This radio has always been post-metadata, so never do
841
        # old-school detection
842
        return False
843

    
844

    
845
class BFU9Alias(chirp_common.Alias):
846
    VENDOR = "Baofeng"
847
    MODEL = "BF-U9"
848

    
849

    
850
class AR8Alias(chirp_common.Alias):
851
    VENDOR = "Arcshell"
852
    MODEL = "AR-8"
853

    
854

    
855
@directory.register
856
class BaofengBFT8Generic(BFT8Radio):
857
    ALIASES = [BFU9Alias, AR8Alias, ]
858

    
859

    
860
@directory.register
861
class RetevisRT16(BFT8Radio):
862
    VENDOR = "Retevis"
863
    MODEL = "RT16"
864

    
865
    _upper = 22
866
    _frs = True
867

    
868

    
869
@directory.register
870
class RetevisRT27B(BFT8Radio):
871
    VENDOR = "Retevis"
872
    MODEL = "RB27B"
873
    DTCS_CODES = sorted(chirp_common.DTCS_CODES + [645])
874
    HAS_NAMES = True
875
    NAME_LENGTH = 6
876
    VALID_CHARS = chirp_common.CHARSET_UPPER_NUMERIC + "-"
877
    CH_OFFSET = True
878
    SKIP_VALUES = ["", "S"]
879
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=2.00),
880
                    chirp_common.PowerLevel("Low", watts=0.50)]
881
    VALID_BANDS = [(400000000, 520000000)]
882

    
883
    _upper = 22
884
    _frs = True
885
    _gmrs = False
886

    
887
    _ranges = [
888
               (0x0000, 0x0640),
889
               (0x0D00, 0x1040),
890
              ]
891
    _memsize = 0x1040
892

    
893

    
894
@directory.register
895
class RetevisRT27(RetevisRT27B):
896
    VENDOR = "Retevis"
897
    MODEL = "RB27"
898
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=5.00),
899
                    chirp_common.PowerLevel("Low", watts=0.50)]
900
    VALID_BANDS = [(136000000, 174000000),
901
                   (400000000, 520000000)]
902

    
903
    _upper = 99
904
    _gmrs = True
905
    _frs = False