Project

General

Profile

New Model #9661 ยป ra85-ra685_rough_draft_#1.py

Jim Unroe, 03/04/2022 09:59 PM

 
1
import logging
2
import struct
3

    
4
from chirp import bitwise
5
from chirp import chirp_common
6
from chirp import directory
7
from chirp import errors
8
from chirp import memmap
9
from chirp.settings import RadioSetting, RadioSettingGroup, RadioSettings
10
from chirp.settings import RadioSettingValueBoolean, RadioSettingValueList
11
from chirp.settings import RadioSettingValueInteger, RadioSettingValueString
12

    
13
LOG = logging.getLogger(__name__)
14

    
15
try:
16
    from builtins import bytes
17
    has_future = True
18
except ImportError:
19
    has_future = False
20
    LOG.debug('python-future package is not available; '
21
              '%s requires it' % __name__)
22

    
23
# GA510 also has DTCS code 645
24
DTCS_CODES = list(sorted(chirp_common.DTCS_CODES + [645]))
25

    
26
##POWER_LEVELS = [
27
##    chirp_common.PowerLevel('H', watts=10),
28
##    chirp_common.PowerLevel('L', watts=1),
29
##    chirp_common.PowerLevel('M', watts=5)]
30
DTMFCHARS = '0123456789ABCD*#'
31

    
32
#SKEY_CHOICES = ['OFF', 'LAMP', 'SOS', 'FM', 'NOAA', 'MONI', 'SEARCH']
33
#SKEY_VALUES = [0xFF, 0x08, 0x03, 0x07, 0x0C, 0x05, 0x1D]
34

    
35

    
36
def reset(radio):
37
    radio.pipe.write(b'E')
38

    
39

    
40
def start_program(radio):
41
    reset(radio)
42
    radio.pipe.read(256)
43
    ##radio.pipe.write(b'PROGROMBFHU')  ##GA510
44
    ##radio.pipe.write(b'PROGROMWLTU') ##RA85 & RA685
45
    radio.pipe.write(radio._magic) ##RA85 & RA685
46
    ack = radio.pipe.read(256)
47
    if not ack.endswith(b'\x06'):
48
        LOG.debug('Ack was %r' % ack)
49
        raise errors.RadioError('Radio did not respond to clone request')
50

    
51
    radio.pipe.write(b'F')
52

    
53
    ident = radio.pipe.read(8)
54
    LOG.debug('Radio ident string is %r' % ident)
55

    
56
    return ident
57

    
58

    
59
def do_download(radio):
60
    ident = start_program(radio)
61

    
62
    s = chirp_common.Status()
63
    s.msg = 'Downloading'
64
    s.max = 0x1C00
65

    
66
    data = bytes()
67
    for addr in range(0, 0x1C40, 0x40):
68
        cmd = struct.pack('>cHB', b'R', addr, 0x40)
69
        LOG.debug('Reading block at %04x: %r' % (addr, cmd))
70
        radio.pipe.write(cmd)
71

    
72
        block = radio.pipe.read(0x44)
73
        header = block[:4]
74
        rcmd, raddr, rlen = struct.unpack('>BHB', header)
75
        block = block[4:]
76
        if raddr != addr:
77
            raise errors.RadioError('Radio send address %04x, expected %04x' %
78
                                    (raddr, addr))
79
        if rlen != 0x40 or len(block) != 0x40:
80
            raise errors.RadioError('Radio sent %02x (%02x) bytes, '
81
                                    'expected %02x' % (rlen, len(block), 0x40))
82

    
83
        data += block
84

    
85
        s.cur = addr
86
        radio.status_fn(s)
87

    
88
    reset(radio)
89

    
90
    return data
91

    
92

    
93
def do_upload(radio):
94
    ident = start_program(radio)
95

    
96
    s = chirp_common.Status()
97
    s.msg = 'Uploading'
98
    s.max = 0x1C00
99

    
100
    # The factory software downloads 0x40 for the block
101
    # at 0x1C00, but only uploads 0x20 there. Mimic that
102
    # here.
103
    for addr in range(0, 0x1C20, 0x20):
104
        cmd = struct.pack('>cHB', b'W', addr, 0x20)
105
        LOG.debug('Writing block at %04x: %r' % (addr, cmd))
106
        block = radio._mmap[addr:addr + 0x20]
107
        radio.pipe.write(cmd)
108
        radio.pipe.write(block)
109

    
110
        ack = radio.pipe.read(1)
111
        if ack != b'\x06':
112
            raise errors.RadioError('Radio refused block at addr %04x' % addr)
113

    
114
        s.cur = addr
115
        radio.status_fn(s)
116

    
117

    
118
MEM_FORMAT = """
119
struct {
120
  lbcd rxfreq[4];
121
  lbcd txfreq[4];
122
  ul16 rxtone;
123
  ul16 txtone;
124
  u8 signal;
125
  u8 unknown1:6,
126
     pttid:2;
127
  u8 unknown2:6,
128
     power:2;
129
  u8 unknown3_0:1,
130
     narrow:1,
131
     unknown3_1:2,
132
     bcl:1,
133
     scan:1,
134
     unknown3_2:1,
135
     fhss:1;
136
} memories[128];
137

    
138
#seekto 0x0C00;
139
struct {
140
  char name[10];
141
  u8 pad[6];
142
} names[128];
143

    
144
#seekto 0x1A00;
145
struct {
146
  // 0x1A00
147
  u8 squelch;
148
  u8 savemode; // [off, mode1, mode2, mode3]
149
  u8 vox; // off=0
150
  u8 backlight;
151
  u8 tdr; // bool
152
  u8 timeout; // n*15 = seconds
153
  u8 beep; // bool
154
  u8 voice;
155

    
156
  // 0x1A08
157
  u8 language; // [eng, chin]
158
  u8 dtmfst;
159
  u8 scanmode; // [TO, CO, SE]
160
  u8 pttid; // [off, BOT, EOT, Both]
161
  u8 pttdelay; // 0-30
162
  u8 cha_disp; // [ch-name, ch-freq]
163
               // [ch, ch-name]; retevis
164
  u8 chb_disp;
165
  u8 bcl; // bool
166

    
167
  // 0x1A10
168
  u8 autolock; // bool
169
  u8 alarm_mode; // [site, tone, code]
170
  u8 alarmsound; // bool
171
  u8 txundertdr; // [off, bandA, bandB]
172
  u8 tailnoiseclear; // [off, on]
173
  u8 rptnoiseclr; // 10*ms, 0-1000
174
  u8 rptnoisedet;
175
  u8 roger; // bool
176

    
177
  // 0x1A18
178
  u8 unknown1a10;
179
  u8 fmradio; // boolean, inverted
180
  u8 workmode; // [vfo, chan]; 1A30-1A31 related?
181
  u8 kblock; // boolean
182
} settings;
183

    
184
#seekto 0x1A80;
185
struct {
186
  u8 skey1sp; // [off, lamp, sos, fm, noaa, moni, search]
187
  u8 skey1lp; // [off, lamp, sos, fm, noaa, moni, search]
188
  u8 skey2sp; // [off, lamp, sos, fm, noaa, moni, search]
189
  u8 skey2lp; // [off, lamp, sos, fm, noaa, moni, search]
190
} skey;
191

    
192
struct dtmfcode {
193
  u8 code[5];
194
  u8 ffpad[11]; // always 0xFF
195
};
196
#seekto 0x1B00;
197
struct dtmfcode dtmfgroup[15];
198
struct {
199
  u8 code[5];
200
  u8 groupcode; // 0->D, *, #
201
  u8 nothing:6,
202
     releasetosend:1,
203
     presstosend:1;
204
  u8 dtmfspeedon; // 80 + n*10, up to [194]
205
  u8 dtmfspeedoff;
206
} anicode;
207

    
208
//dtmf on -> 90ms
209
//dtmf off-> 120ms
210
//group code *->0
211
//press 0->1
212
//release 1->0
213

    
214
"""
215

    
216

    
217
PTTID = ['Off', 'BOT', 'EOT', 'Both']
218
SIGNAL = [str(i) for i in range(1, 16)]
219

    
220
GMRS_FREQS1 = [462.5625, 462.5875, 462.6125, 462.6375, 462.6625,
221
              462.6875, 462.7125]
222
GMRS_FREQS2 = [467.5625, 467.5875, 467.6125, 467.6375, 467.6625,
223
              467.6875, 467.7125]
224
GMRS_FREQS3 = [462.5500, 462.5750, 462.6000, 462.6250, 462.6500,
225
              462.6750, 462.7000, 462.7250]
226
GMRS_FREQS = GMRS_FREQS1 + GMRS_FREQS2 + GMRS_FREQS3 * 2
227

    
228

    
229
class TDH6Radio(chirp_common.Alias):
230
    VENDOR = "TIDRADIO"
231
    MODEL = "TD-H6"
232

    
233

    
234
@directory.register
235
class RadioddityGA510Radio(chirp_common.CloneModeRadio):
236
    VENDOR = 'Radioddity'
237
    MODEL = 'GA-510'
238
    BAUD_RATE = 9600
239
    NEEDS_COMPAT_SERIAL = False
240
    ALIASES = [TDH6Radio]
241
    POWER_LEVELS = [
242
        chirp_common.PowerLevel('H', watts=10),
243
        chirp_common.PowerLevel('L', watts=1),
244
        chirp_common.PowerLevel('M', watts=5)]
245

    
246
    _magic = (b'PROGROMBFHU')
247

    
248
    _gmrs = False
249

    
250
    def sync_in(self):
251
        try:
252
            data = do_download(self)
253
            self._mmap = memmap.MemoryMapBytes(data)
254
        except errors.RadioError:
255
            raise
256
        except Exception as e:
257
            LOG.exception('General failure')
258
            raise errors.RadioError('Failed to download from radio: %s' % e)
259
        self.process_mmap()
260

    
261
    def sync_out(self):
262
        try:
263
            do_upload(self)
264
        except errors.RadioError:
265
            raise
266
        except Exception as e:
267
            LOG.exception('General failure')
268
            raise errors.RadioError('Failed to upload to radio: %s' % e)
269

    
270
    def process_mmap(self):
271
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
272

    
273
    def get_features(self):
274
        rf = chirp_common.RadioFeatures()
275
        rf.memory_bounds = (0, 127)
276
        rf.has_ctone = True
277
        rf.has_cross = True
278
        rf.has_tuning_step = False
279
        rf.has_settings = True
280
        rf.has_bank = False
281
        rf.has_sub_devices = False
282
        rf.has_dtcs_polarity = True
283
        rf.has_rx_dtcs = True
284
        rf.can_odd_split = True
285
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
286
        rf.valid_cross_modes = ['Tone->Tone', 'DTCS->', '->DTCS', 'Tone->DTCS',
287
                                'DTCS->Tone', '->Tone', 'DTCS->DTCS']
288
        rf.valid_modes = ['FM', 'NFM']
289
        rf.valid_tuning_steps = [2.5, 5.0, 6.25, 12.5, 10.0, 15.0, 20.0,
290
                                 25.0, 50.0, 100.0]
291
        rf.valid_dtcs_codes = DTCS_CODES
292
        rf.valid_duplexes = ['', '-', '+', 'split', 'off']
293
        rf.valid_power_levels = self.POWER_LEVELS
294
        rf.valid_name_length = 10
295
        rf.valid_characters = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
296
                               'abcdefghijklmnopqrstuvwxyz'
297
                               '0123456789'
298
                               '!"#$%&\'()~+-,./:;<=>?@[\\]^`{}*| ')
299
        rf.valid_bands = [(136000000, 174000000),
300
                          (400000000, 480000000)]
301
        return rf
302

    
303
    def get_raw_memory(self, num):
304
        return repr(self._memobj.memories[num]) + repr(self._memobj.names[num])
305

    
306
    @staticmethod
307
    def _decode_tone(toneval):
308
        if toneval in (0, 0xFFFF):
309
            LOG.debug('no tone value: %s' % toneval)
310
            return '', None, None
311
        elif toneval < 670:
312
            toneval = toneval - 1
313
            index = toneval % len(DTCS_CODES)
314
            if index != int(toneval):
315
                pol = 'R'
316
                # index -= 1
317
            else:
318
                pol = 'N'
319
            return 'DTCS', DTCS_CODES[index], pol
320
        else:
321
            return 'Tone', toneval / 10.0, 'N'
322

    
323
    @staticmethod
324
    def _encode_tone(mode, val, pol):
325
        if not mode:
326
            return 0x0000
327
        elif mode == 'Tone':
328
            return int(val * 10)
329
        elif mode == 'DTCS':
330
            index = DTCS_CODES.index(val)
331
            if pol == 'R':
332
                index += len(DTCS_CODES)
333
            index += 1
334
            LOG.debug('Encoded dtcs %s/%s to %04x' % (val, pol, index))
335
            return index
336
        else:
337
            raise errors.RadioError('Unsupported tone mode %r' % mode)
338

    
339
    def _get_extra(self, _mem):
340
        group = RadioSettingGroup('extra', 'Extra')
341

    
342
        s = RadioSetting('bcl', 'Busy Channel Lockout',
343
                         RadioSettingValueBoolean(_mem.bcl))
344
        group.append(s)
345

    
346
        s = RadioSetting('fhss', 'FHSS',
347
                         RadioSettingValueBoolean(_mem.fhss))
348
        group.append(s)
349

    
350
        # pttid, signal
351

    
352
        cur = PTTID[int(_mem.pttid)]
353
        s = RadioSetting('pttid', 'PTTID',
354
                         RadioSettingValueList(PTTID, cur))
355
        group.append(s)
356

    
357
        cur = SIGNAL[int(_mem.signal)]
358
        s = RadioSetting('signal', 'Signal',
359
                         RadioSettingValueList(SIGNAL, cur))
360
        group.append(s)
361

    
362
        return group
363

    
364
    def _set_extra(self, _mem, mem):
365
        _mem.bcl = int(mem.extra['bcl'].value)
366
        _mem.fhss = int(mem.extra['fhss'].value)
367
        _mem.pttid = int(mem.extra['pttid'].value)
368
        _mem.signal = int(mem.extra['signal'].value)
369

    
370
    def _is_txinh(self, _mem):
371
        raw_tx = ""
372
        for i in range(0, 4):
373
            raw_tx += _mem.txfreq[i].get_raw()
374
        return raw_tx == "\xFF\xFF\xFF\xFF"
375

    
376
    def _get_mem(self, num):
377
        return self._memobj.memories[num]
378

    
379
    def get_memory(self, num):
380
        ##_mem = self._memobj.memories[num]
381
        _mem = self._get_mem(num)
382
        mem = chirp_common.Memory()
383
        mem.number = num
384
        if int(_mem.rxfreq) == 166666665:
385
            mem.empty = True
386
            return mem
387

    
388
        mem.name = ''.join([str(c) for c in self._memobj.names[num].name
389
                            if ord(str(c)) < 127]).rstrip()
390
        mem.freq = int(_mem.rxfreq) * 10
391
        offset = (int(_mem.txfreq) - int(_mem.rxfreq)) * 10
392
        if self._is_txinh(_mem):
393
            mem.duplex = 'off'
394
            mem.offset = 0
395
        elif offset == 0:
396
            mem.duplex = ''
397
        elif abs(offset) < 100000000:
398
            mem.duplex = offset < 0 and '-' or '+'
399
            mem.offset = abs(offset)
400
        else:
401
            mem.duplex = 'split'
402
            mem.offset = int(_mem.txfreq) * 10
403

    
404
        mem.power = self.POWER_LEVELS[_mem.power]
405
        mem.mode = 'NFM' if _mem.narrow else 'FM'
406
        mem.skip = '' if _mem.scan else 'S'
407

    
408
        LOG.debug('got txtone: %s' % repr(self._decode_tone(_mem.txtone)))
409
        LOG.debug('got rxtone: %s' % repr(self._decode_tone(_mem.rxtone)))
410
        chirp_common.split_tone_decode(mem,
411
                                       self._decode_tone(_mem.txtone),
412
                                       self._decode_tone(_mem.rxtone))
413
        try:
414
            mem.extra = self._get_extra(_mem)
415
        except:
416
            LOG.exception('Failed to get extra for %i' % num)
417
        return mem
418

    
419
    def _set_mem(self, number):
420
        return self._memobj.memories[number]
421

    
422
    def _set_nam(self, number):
423
        return self._memobj.names[number]
424

    
425
    def set_memory(self, mem):
426
        ##_mem = self._memobj.memories[mem.number]
427
        ##_nam = self._memobj.names[mem.number]
428
        _mem = self._set_mem(mem.number)
429
        _nam = self._set_nam(mem.number)
430

    
431
        if mem.empty:
432
            _mem.set_raw(b'\xff' * 16)
433
            _nam.set_raw(b'\xff' * 16)
434
            return
435

    
436
        if int(_mem.rxfreq) == 166666665:
437
            LOG.debug('Initializing new memory %i' % mem.number)
438
            _mem.set_raw(b'\x00' * 16)
439

    
440
        if self._gmrs:
441
            if float(mem.freq) / 1000000 in GMRS_FREQS:
442
                if float(mem.freq) / 1000000 in GMRS_FREQS1:
443
                    mem.duplex = ''
444
                    mem.offset = 0
445
                if float(mem.freq) / 1000000 in GMRS_FREQS2:
446
                    mem.duplex = ''
447
                    mem.offset = 0
448
                    mem.mode = "NFM"
449
                    mem.power = self.POWER_LEVELS[1]
450
                if float(mem.freq) / 1000000 in GMRS_FREQS3:
451
                    if mem.duplex == '+':
452
                        mem.offset = 5000000
453
                    else:
454
                        mem.duplex = ''
455
                        mem.offset = 0
456
            else:
457
                mem.duplex = 'off'
458
                mem.offset = 0
459

    
460
        _nam.name = mem.name.ljust(10)
461

    
462
        _mem.rxfreq = mem.freq // 10
463
        if mem.duplex == '':
464
            _mem.txfreq = mem.freq // 10
465
        elif mem.duplex == 'split':
466
            _mem.txfreq = mem.offset // 10
467
        elif mem.duplex == 'off':
468
            for i in range(0, 4):
469
                _mem.txfreq[i].set_raw(b'\xFF')
470
        elif mem.duplex == '-':
471
            _mem.txfreq = (mem.freq - mem.offset) // 10
472
        elif mem.duplex == '+':
473
            _mem.txfreq = (mem.freq + mem.offset) // 10
474
        else:
475
            raise errors.RadioError('Unsupported duplex mode %r' % mem.duplex)
476

    
477
        txtone, rxtone = chirp_common.split_tone_encode(mem)
478
        LOG.debug('tx tone is %s' % repr(txtone))
479
        LOG.debug('rx tone is %s' % repr(rxtone))
480
        _mem.txtone = self._encode_tone(*txtone)
481
        _mem.rxtone = self._encode_tone(*rxtone)
482

    
483
        try:
484
            _mem.power = self.POWER_LEVELS.index(mem.power)
485
        except ValueError:
486
            _mem.power = 0
487
        _mem.narrow = mem.mode == 'NFM'
488
        _mem.scan = mem.skip != 'S'
489
        if mem.extra:
490
            self._set_extra(_mem, mem)
491

    
492
    def get_settings(self):
493
        _set = self._memobj.settings
494
        
495
        basic = RadioSettingGroup('basic', 'Basic')
496
        adv = RadioSettingGroup('advanced', 'Advanced')
497
        dtmf = RadioSettingGroup('dtmf', 'DTMF')
498

    
499
        radioddity_settings = {
500
            'savemode': ['Off', 'Mode 1', 'Mode 2', 'Mode 3'],
501
            'cha_disp': ['CH+Name', 'CH+Freq'],
502
            'chb_disp': ['CH+Name', 'CH+Freq'],
503
            'txundertdr': ['Off', 'Band A', 'Band B'],
504
            'rptnoiseclr': ['Off'] + ['%i' % i for i in range(100, 1001, 100)],
505
            'rptnoisedet': ['Off'] + ['%i' % i for i in range(100, 1001, 100)],
506
        }
507

    
508
        retevis_settings = {
509
            'savemode': ['Off', 'On'],
510
            'cha_disp': ['CH', 'CH+Name'],
511
            'chb_disp': ['CH', 'CH+Name'],
512
        }
513

    
514
        choice_settings = {
515
            'vox': ['Off'] + ['%i' % i for i in range(1, 11)],
516
            'backlight': ['Off'] + ['%i' % i for i in range(1, 11)],
517
            'timeout': ['Off'] + ['%i' % i for i in range(15, 615, 15)],
518
            'language': ['English', 'Chinese'],
519
            'dtmfst': ['OFF', 'KB Side Tone', 'ANI Side Tone',
520
                       'KB ST+ANI ST', 'Both'],
521
            'scanmode': ['TO', 'CO', 'SE'],
522
            'pttid': ['Off', 'BOT', 'EOT', 'Both'],
523
            'alarm_mode': ['Site', 'Tone', 'Code'],
524
            'workmode': ['VFO', 'Chan'],
525
        }
526

    
527
        if self.VENDOR == "Retevis":
528
            choice_settings.update(retevis_settings)
529
        else:
530
            choice_settings.update(radioddity_settings)
531

    
532
        basic_settings = ['timeout', 'vox', 'backlight', 'language',
533
                          'cha_disp', 'chb_disp', 'workmode']
534
        titles = {
535
            'savemode': 'Save Mode',
536
            'vox': 'VOX',
537
            'backlight': 'Auto Backlight',
538
            'timeout': 'Time Out Timer (s)',
539
            'language': 'Language',
540
            'dtmfst': 'DTMF-ST',
541
            'scanmode': 'Scan Mode',
542
            'pttid': 'PTT-ID',
543
            'cha_disp': 'Channel A Display',
544
            'chb_disp': 'Channel B Display',
545
            'alarm_mode': 'Alarm Mode',
546
            'txundertdr': 'TX Under TDR',
547
            'rptnoiseclr': 'RPT Noise Clear (ms)',
548
            'rptnoisedet': 'RPT Noise Detect (ms)',
549
            'workmode': 'Work Mode',
550
        }
551

    
552
        basic.append(
553
            RadioSetting('squelch', 'Squelch Level',
554
                         RadioSettingValueInteger(0, 9, int(_set.squelch))))
555
        adv.append(
556
            RadioSetting('pttdelay', 'PTT Delay',
557
                         RadioSettingValueInteger(0, 30, int(_set.pttdelay))))
558
        adv.append(
559
            RadioSetting('tdr', 'TDR',
560
                         RadioSettingValueBoolean(
561
                             int(_set.tdr))))
562
        adv.append(
563
            RadioSetting('beep', 'Beep',
564
                         RadioSettingValueBoolean(
565
                             int(_set.beep))))
566
        basic.append(
567
            RadioSetting('voice', 'Voice Enable',
568
                         RadioSettingValueBoolean(
569
                             int(_set.voice))))
570
        adv.append(
571
            RadioSetting('bcl', 'BCL',
572
                         RadioSettingValueBoolean(
573
                             int(_set.bcl))))
574
        adv.append(
575
            RadioSetting('autolock', 'Auto Lock',
576
                         RadioSettingValueBoolean(
577
                             int(_set.autolock))))
578
        adv.append(
579
            RadioSetting('alarmsound', 'Alarm Sound',
580
                         RadioSettingValueBoolean(
581
                             int(_set.alarmsound))))
582
        adv.append(
583
            RadioSetting('tailnoiseclear', 'Tail Noise Clear',
584
                         RadioSettingValueBoolean(
585
                             int(_set.tailnoiseclear))))
586
        adv.append(
587
            RadioSetting('roger', 'Roger',
588
                         RadioSettingValueBoolean(
589
                             int(_set.roger))))
590
        adv.append(
591
            RadioSetting('fmradio', 'FM Radio Disabled',
592
                         RadioSettingValueBoolean(
593
                             int(_set.fmradio))))
594
        adv.append(
595
            RadioSetting('kblock', 'KB Lock',
596
                         RadioSettingValueBoolean(
597
                             int(_set.kblock))))
598

    
599
        for key in sorted(choice_settings):
600
            choices = choice_settings[key]
601
            title = titles[key]
602
            if key in basic_settings:
603
                group = basic
604
            else:
605
                group = adv
606

    
607
            val = int(getattr(_set, key))
608
            try:
609
                cur = choices[val]
610
            except IndexError:
611
                LOG.error('Value %i for %s out of range for list (%i): %s' % (
612
                    val, key, len(choices), choices))
613
                raise
614
            group.append(
615
                RadioSetting(key, title,
616
                             RadioSettingValueList(
617
                                 choices,
618
                                 choices[val])))
619

    
620
        # Side Keys
621
        _skey = self._memobj.skey
622
        SKEY_CHOICES = ['OFF', 'LAMP', 'SOS', 'FM', 'NOAA', 'MONI', 'SEARCH']
623
        SKEY_VALUES = [0xFF, 0x08, 0x03, 0x07, 0x0C, 0x05, 0x1D]
624

    
625
        def apply_skey_listvalue(setting, obj):
626
            LOG.debug("Setting value: " + str(setting.value) + " from list")
627
            val = str(setting.value)
628
            index = SKEY_CHOICES.index(val)
629
            val = SKEY_VALUES[index]
630
            obj.set_value(val)
631

    
632
        # Side Key 1 - Short Press
633
        if _skey.skey1sp in SKEY_VALUES:
634
            idx = SKEY_VALUES.index(_skey.skey1sp)
635
        else:
636
            idx = SKEY_VALUES.index(0x0C)
637
        rs = RadioSettingValueList(SKEY_CHOICES, SKEY_CHOICES[idx])
638
        rset = RadioSetting("skey.skey1sp", "Side Key (Short Press)", rs)
639
        rset.set_apply_callback(apply_skey_listvalue, _skey.skey1sp)
640
        adv.append(rset)
641

    
642
        ##rs = RadioSetting('settings.skey1sp', 'Side Key 1 - Short Press',
643
        ##                  RadioSettingValueList(SKEY_CHOICES,
644
        ##                                        SKEY_CHOICES[idx]))
645
        ##rs.set_apply_callback(apply_skey_listvalue, _set.skey1sp)
646
        ##adv.append(rs)
647

    
648
        ## Side Key 1 - Long Press
649
        #if _set.skey1lp in SK_VALUES:
650
        #    idx = SK_VALUES.index(_set.skey1lp)
651
        #else:
652
        #    idx = SK_VALUES.index(0xFF)
653
        #rs = RadioSetting('skey1lp', 'Side Key 1 - Long Press',
654
        #                  RadioSettingValueList(SK_CHOICES,
655
        #                                        SK_CHOICES[idx]))
656
        #rs.set_apply_callback(apply_sk_listvalue, _set.skey1lp)
657
        #adv.append(rs)
658

    
659
        ## Side Key 2 - Short Press
660
        #if _set.skey2sp in SK_VALUES:
661
        #    idx = SK_VALUES.index(_set.skey2sp)
662
        #else:
663
        #    idx = SK_VALUES.index(0xFF)
664
        #rs = RadioSetting('skey2sp', 'Side Key 2 - Short Press',
665
        #                  RadioSettingValueList(SK_CHOICES,
666
        #                                        SK_CHOICES[idx]))
667
        #rs.set_apply_callback(apply_sk_listvalue, _set.skey2sp)
668
        #adv.append(rs)
669

    
670
        ## Side Key 1 - Long Press
671
        #if _set.skey2lp in SK_VALUES:
672
        #    idx = SK_VALUES.index(_set.skey2lp)
673
        #else:
674
        #    idx = SK_VALUES.index(0xFF)
675
        #rs = RadioSetting('skey2lp', 'Side Key 2 - Long Press',
676
        #                  RadioSettingValueList(SK_CHOICES,
677
        #                                        SK_CHOICES[idx]))
678
        #rs.set_apply_callback(apply_sk_listvalue, _set.skey2lp)
679
        #adv.append(rs)
680

    
681
        for i in range(1, 16):
682
            cur = ''.join(
683
                DTMFCHARS[i]
684
                for i in self._memobj.dtmfgroup[i - 1].code if int(i) < 0xF)
685
            dtmf.append(
686
                RadioSetting(
687
                    'dtmf.code@%i' % i, 'DTMF Group %i' % i,
688
                    RadioSettingValueString(0, 5, cur,
689
                                            autopad=False,
690
                                            charset=DTMFCHARS)))
691
        cur = ''.join(
692
            '%X' % i
693
            for i in self._memobj.anicode.code if int(i) < 0xE)
694
        dtmf.append(
695
            RadioSetting(
696
                'anicode.code', 'ANI Code',
697
                RadioSettingValueString(0, 5, cur,
698
                                        autopad=False,
699
                                        charset=DTMFCHARS)))
700

    
701
        anicode = self._memobj.anicode
702

    
703
        dtmf.append(
704
            RadioSetting(
705
                'anicode.groupcode', 'Group Code',
706
                RadioSettingValueList(
707
                    list(DTMFCHARS),
708
                    DTMFCHARS[int(anicode.groupcode)])))
709

    
710
        dtmf.append(
711
            RadioSetting(
712
                'anicode.releasetosend', 'Release To Send',
713
                RadioSettingValueBoolean(
714
                    int(anicode.releasetosend))))
715
        dtmf.append(
716
            RadioSetting(
717
                'anicode.presstosend', 'Press To Send',
718
                RadioSettingValueBoolean(
719
                    int(anicode.presstosend))))
720
        cur = int(anicode.dtmfspeedon) * 10 + 80
721
        dtmf.append(
722
            RadioSetting(
723
                'anicode.dtmfspeedon', 'DTMF Speed (on time in ms)',
724
                RadioSettingValueInteger(60, 2000, cur, 10)))
725
        cur = int(anicode.dtmfspeedoff) * 10 + 80
726
        dtmf.append(
727
            RadioSetting(
728
                'anicode.dtmfspeedoff', 'DTMF Speed (off time in ms)',
729
                RadioSettingValueInteger(60, 2000, cur, 10)))
730

    
731
        top = RadioSettings(basic, adv, dtmf)
732
        return top
733

    
734
    def set_settings(self, settings):
735
        for element in settings:
736
            if element.get_name().startswith('anicode.'):
737
                self._set_anicode(element)
738
            elif element.get_name().startswith('dtmf.code'):
739
                self._set_dtmfcode(element)
740
            elif not isinstance(element, RadioSetting):
741
                self.set_settings(element)
742
                continue
743
            else:
744
                self._set_setting(element)
745

    
746
    def _set_setting(self, setting):
747
        key = setting.get_name()
748
        val = setting.value
749

    
750
        setattr(self._memobj.settings, key, int(val))
751

    
752
    def _set_anicode(self, setting):
753
        name = setting.get_name().split('.', 1)[1]
754
        if name == 'code':
755
            val = [DTMFCHARS.index(c) for c in str(setting.value)]
756
            for i in range(0, 5):
757
                try:
758
                    value = val[i]
759
                except IndexError:
760
                    value = 0xFF
761
                self._memobj.anicode.code[i] = value
762
        elif name.startswith('dtmfspeed'):
763
            setattr(self._memobj.anicode, name,
764
                    (int(setting.value) - 80) // 10)
765
        else:
766
            setattr(self._memobj.anicode, name, int(setting.value))
767

    
768
    def _set_dtmfcode(self, setting):
769
        index = int(setting.get_name().split('@', 1)[1]) - 1
770
        val = [DTMFCHARS.index(c) for c in str(setting.value)]
771
        for i in range(0, 5):
772
            try:
773
                value = val[i]
774
            except IndexError:
775
                value = 0xFF
776
            self._memobj.dtmfgroup[index].code[i] = value
777

    
778

    
779
@directory.register
780
class RetevisRA85Radio(RadioddityGA510Radio):
781
    VENDOR = 'Retevis'
782
    MODEL = 'RA85'
783
    ##BAUD_RATE = 9600
784
    ##NEEDS_COMPAT_SERIAL = False
785
    ##ALIASES = [TDH6Radio]
786
    POWER_LEVELS = [
787
        chirp_common.PowerLevel('H', watts=5),
788
        chirp_common.PowerLevel('L', watts=0.5),
789
        chirp_common.PowerLevel('M', watts=0.6)]
790

    
791
    _magic = b'PROGROMWLTU'
792
    _gmrs = True
793

    
794
    def get_features(self):
795
        rf = RadioddityGA510Radio.get_features(self)
796
        ##rf.memory_bounds = (1, 60)
797
        rf.memory_bounds = (1, 128)
798
        rf.valid_bands = [(136000000, 174000000),
799
                          (400000000, 520000000)]
800
        return rf
801

    
802
    def _get_mem(self, num):
803
        return self._memobj.memories[num - 1]
804

    
805
    def _set_mem(self, num):
806
        return self._memobj.memories[num - 1]
807

    
808

    
809
@directory.register
810
class RetevisRA685Radio(RadioddityGA510Radio):
811
    VENDOR = 'Retevis'
812
    MODEL = 'RA685'
813
    ##BAUD_RATE = 9600
814
    ##NEEDS_COMPAT_SERIAL = False
815
    ##ALIASES = [TDH6Radio]
816
    POWER_LEVELS = [
817
        chirp_common.PowerLevel('H', watts=5),
818
        chirp_common.PowerLevel('L', watts=1),
819
        chirp_common.PowerLevel('M', watts=3)]
820

    
821
    _magic = b'PROGROMWLTU'
822

    
823
    def get_features(self):
824
        rf = RadioddityGA510Radio.get_features(self)
825
        rf.memory_bounds = (1, 128)
826
        rf.valid_bands = [(136000000, 174000000),
827
                          (400000000, 520000000)]
828
        return rf
829

    
830
    def _get_mem(self, num):
831
        return self._memobj.memories[num - 1]
832

    
833
    ##def _get_nam(self, number):
834
    ##    return self._memobj.names[number - 1]
835

    
836
    def _set_mem(self, num):
837
        return self._memobj.memories[num - 1]
838

    
839
    def _set_nam(self, number):
840
        return self._memobj.names[number - 1]
841

    
842
    vhftx = [144000000, 146000000]
843
    uhftx = [430000000, 440000000]
844

    
845
    def set_memory(self, mem):
846
        # If memory is outside the TX limits, the radio will refuse
847
        # transmit. Radioddity asked for us to enforce this behavior
848
        # in chirp for consistency.
849
        if not (mem.freq >= self.vhftx[0] and mem.freq < self.vhftx[1]) and \
850
           not (mem.freq >= self.uhftx[0] and mem.freq < self.uhftx[1]):
851
            LOG.info('Memory frequency outside TX limits of radio; '
852
                     'forcing duplex=off')
853
            mem.duplex = 'off'
854
            mem.offset = 0
855
        RadioddityGA510Radio.set_memory(self, mem)
    (1-1/1)