Project

General

Profile

Bug #7067 » h777_test_new_model.py

h777 with additional 'Y' command - Tony Fuller, 10/22/2019 06:34 PM

 
1
# -*- coding: utf-8 -*-
2
# Copyright 2013 Andrew Morgan <ziltro@ziltro.com>
3
#
4
# This program is free software: you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation, either version 2 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16

    
17
import time
18
import os
19
import struct
20
import unittest
21
import logging
22

    
23
from chirp import chirp_common, directory, memmap
24
from chirp import bitwise, errors, util
25
from chirp.settings import RadioSetting, RadioSettingGroup, \
26
    RadioSettingValueInteger, RadioSettingValueList, \
27
    RadioSettingValueBoolean, RadioSettings
28

    
29
LOG = logging.getLogger(__name__)
30

    
31
MEM_FORMAT = """
32
#seekto 0x0010;
33
struct {
34
    lbcd rxfreq[4];
35
    lbcd txfreq[4];
36
    lbcd rxtone[2];
37
    lbcd txtone[2];
38
    u8 unknown3:1,
39
       unknown2:1,
40
       unknown1:1,
41
       skip:1,
42
       highpower:1,
43
       narrow:1,
44
       beatshift:1,
45
       bcl:1;
46
    u8 unknown4[3];
47
} memory[16];
48
#seekto 0x02B0;
49
struct {
50
    u8 voiceprompt;
51
    u8 voicelanguage;
52
    u8 scan;
53
    u8 vox;
54
    u8 voxlevel;
55
    u8 voxinhibitonrx;
56
    u8 lowvolinhibittx;
57
    u8 highvolinhibittx;
58
    u8 alarm;
59
    u8 fmradio;
60
} settings;
61
#seekto 0x03C0;
62
struct {
63
    u8 unused:6,
64
       batterysaver:1,
65
       beep:1;
66
    u8 squelchlevel;
67
    u8 sidekeyfunction;
68
    u8 timeouttimer;
69
    u8 unused2[3];
70
    u8 unused3:7,
71
       scanmode:1;
72
} settings2;
73
"""
74

    
75
CMD_ACK = "\x06"
76
BLOCK_SIZE = 0x08
77
UPLOAD_BLOCKS = [range(0x0000, 0x0110, 8),
78
                 range(0x02b0, 0x02c0, 8),
79
                 range(0x0380, 0x03e0, 8)]
80

    
81
# TODO: Is it 1 watt?
82
H777_POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=1.00),
83
                     chirp_common.PowerLevel("High", watts=5.00)]
84
VOICE_LIST = ["English", "Chinese"]
85
TIMEOUTTIMER_LIST = ["Off", "30 seconds", "60 seconds", "90 seconds",
86
                     "120 seconds", "150 seconds", "180 seconds",
87
                     "210 seconds", "240 seconds", "270 seconds",
88
                     "300 seconds"]
89
SCANMODE_LIST = ["Carrier", "Time"]
90

    
91
SETTING_LISTS = {
92
    "voice": VOICE_LIST,
93
}
94

    
95

    
96
def _h777_enter_programming_mode(radio):
97
    serial = radio.pipe
98

    
99
    try:
100
        serial.write("\x02")
101
        time.sleep(0.1)
102
        serial.write("PROGRAM")
103
        ack = serial.read(1)
104
    except:
105
        raise errors.RadioError("Error communicating with radio")
106

    
107
    if not ack:
108
        raise errors.RadioError("No response from radio")
109
    elif ack != CMD_ACK:
110
        raise errors.RadioError("Radio refused to enter programming mode")
111

    
112
    try:
113
        serial.write("\x02")
114
        ident = serial.read(8)
115
    except:
116
        raise errors.RadioError("Error communicating with radio")
117

    
118
    if not ident.startswith("P3107"):
119
        LOG.debug(util.hexprint(ident))
120
        raise errors.RadioError("Radio returned unknown identification string")
121

    
122
    try:
123
        serial.write(CMD_ACK)
124
        ack = serial.read(1)
125
    except:
126
        raise errors.RadioError("Error communicating with radio")
127

    
128
    if ack != CMD_ACK:
129
        raise errors.RadioError("Radio refused to enter programming mode")
130

    
131

    
132
def _h777_exit_programming_mode(radio):
133
    serial = radio.pipe
134
    try:
135
        serial.write("E")
136
    except:
137
        raise errors.RadioError("Radio refused to exit programming mode")
138

    
139

    
140
def _h777_read_block(radio, block_addr, block_size):
141
    serial = radio.pipe
142

    
143
    cmd = struct.pack(">cHb", 'R', block_addr, BLOCK_SIZE)
144
    expectedresponse = "W" + cmd[1:]
145
    LOG.debug("Reading block %04x..." % (block_addr))
146

    
147
    try:
148
        serial.write(cmd)
149
        response = serial.read(4 + BLOCK_SIZE)
150
        if response[:4] != expectedresponse:
151
            raise Exception("Error reading block %04x." % (block_addr))
152

    
153
        block_data = response[4:]
154

    
155
        serial.write(CMD_ACK)
156
        ack = serial.read(1)
157
    except:
158
        raise errors.RadioError("Failed to read block at %04x" % block_addr)
159

    
160
    if ack != CMD_ACK:
161
        raise Exception("No ACK reading block %04x." % (block_addr))
162

    
163
    return block_data
164

    
165

    
166
def _h777_write_block(radio, block_addr, block_size):
167
    serial = radio.pipe
168

    
169
    if 0x02B0 <= block_addr <= 0x02C0:
170
        cmd = struct.pack(">cHb", 'Y', block_addr, BLOCK_SIZE)
171
    else:
172
        cmd = struct.pack(">cHb", 'W', block_addr, BLOCK_SIZE)
173
    data = radio.get_mmap()[block_addr:block_addr + 8]
174

    
175
    LOG.debug("Writing Data:")
176
    LOG.debug(util.hexprint(cmd + data))
177

    
178
    try:
179
        serial.write(cmd + data)
180
        if serial.read(1) != CMD_ACK:
181
            raise Exception("No ACK")
182
    except:
183
        raise errors.RadioError("Failed to send block "
184
                                "to radio at %04x" % block_addr)
185

    
186

    
187
def do_download(radio):
188
    LOG.debug("download")
189
    _h777_enter_programming_mode(radio)
190

    
191
    data = ""
192

    
193
    status = chirp_common.Status()
194
    status.msg = "Cloning from radio"
195

    
196
    status.cur = 0
197
    status.max = radio._memsize
198

    
199
    for addr in range(0, radio._memsize, BLOCK_SIZE):
200
        status.cur = addr + BLOCK_SIZE
201
        radio.status_fn(status)
202

    
203
        block = _h777_read_block(radio, addr, BLOCK_SIZE)
204
        data += block
205

    
206
        LOG.debug("Address: %04x" % addr)
207
        LOG.debug(util.hexprint(block))
208

    
209
    _h777_exit_programming_mode(radio)
210

    
211
    return memmap.MemoryMap(data)
212

    
213

    
214
def do_upload(radio):
215
    status = chirp_common.Status()
216
    status.msg = "Uploading to radio"
217

    
218
    _h777_enter_programming_mode(radio)
219

    
220
    status.cur = 0
221
    status.max = radio._memsize
222

    
223
    for start_addr, end_addr in radio._ranges:
224
        for addr in range(start_addr, end_addr, BLOCK_SIZE):
225
            status.cur = addr + BLOCK_SIZE
226
            radio.status_fn(status)
227
            _h777_write_block(radio, addr, BLOCK_SIZE)
228

    
229
    _h777_exit_programming_mode(radio)
230

    
231

    
232
class ArcshellAR5(chirp_common.Alias):
233
    VENDOR = 'Arcshell'
234
    MODEL = 'AR-5'
235

    
236

    
237
class ArcshellAR6(chirp_common.Alias):
238
    VENDOR = 'Arcshell'
239
    MODEL = 'AR-6'
240

    
241

    
242
class GV8SAlias(chirp_common.Alias):
243
    VENDOR = 'Greaval'
244
    MODEL = 'GV-8S'
245

    
246

    
247
class GV9SAlias(chirp_common.Alias):
248
    VENDOR = 'Greaval'
249
    MODEL = 'GV-9S'
250

    
251

    
252
class A8SAlias(chirp_common.Alias):
253
    VENDOR = 'Ansoko'
254
    MODEL = 'A-8S'
255

    
256

    
257
class TenwayTW325Alias(chirp_common.Alias):
258
    VENDOR = 'Tenway'
259
    MODEL = 'TW-325'
260

    
261

    
262
@directory.register
263
class H777Radio(chirp_common.CloneModeRadio):
264
    """HST H-777"""
265
    # VENDOR = "Heng Shun Tong (恒顺通)"
266
    # MODEL = "H-777"
267
    VENDOR = "Baofeng"
268
    MODEL = "BF-888"
269
    BAUD_RATE = 9600
270

    
271
    ALIASES = [ArcshellAR5, ArcshellAR6, GV8SAlias, GV9SAlias, A8SAlias,
272
               TenwayTW325Alias]
273
    SIDEKEYFUNCTION_LIST = ["Off", "Monitor", "Transmit Power", "Alarm"]
274

    
275
    # This code currently requires that ranges start at 0x0000
276
    # and are continious. In the original program 0x0388 and 0x03C8
277
    # are only written (all bytes 0xFF), not read.
278
    # _ranges = [
279
    #       (0x0000, 0x0110),
280
    #       (0x02B0, 0x02C0),
281
    #       (0x0380, 0x03E0)
282
    #       ]
283
    # Memory starts looping at 0x1000... But not every 0x1000.
284

    
285
    _ranges = [
286
        (0x0000, 0x0110),
287
        (0x0380, 0x03E0),
288
        (0x02B0, 0x02C0),
289
    ]
290
    _memsize = 0x03E0
291
    _has_fm = True
292
    _has_sidekey = True
293

    
294
    def get_features(self):
295
        rf = chirp_common.RadioFeatures()
296
        rf.has_settings = True
297
        rf.valid_modes = ["NFM", "FM"]  # 12.5 KHz, 25 kHz.
298
        rf.valid_skips = ["", "S"]
299
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
300
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
301
        rf.can_odd_split = True
302
        rf.has_rx_dtcs = True
303
        rf.has_ctone = True
304
        rf.has_cross = True
305
        rf.valid_cross_modes = [
306
            "Tone->Tone",
307
            "DTCS->",
308
            "->DTCS",
309
            "Tone->DTCS",
310
            "DTCS->Tone",
311
            "->Tone",
312
            "DTCS->DTCS"]
313
        rf.has_tuning_step = False
314
        rf.has_bank = False
315
        rf.has_name = False
316
        rf.memory_bounds = (1, 16)
317
        rf.valid_bands = [(400000000, 470000000)]
318
        rf.valid_power_levels = H777_POWER_LEVELS
319
        rf.valid_tuning_steps = [2.5, 5.0, 6.25, 10.0, 12.5, 15.0, 20.0, 25.0,
320
                                 50.0, 100.0]
321

    
322
        return rf
323

    
324
    def process_mmap(self):
325
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
326

    
327
    def sync_in(self):
328
        self._mmap = do_download(self)
329
        self.process_mmap()
330

    
331
    def sync_out(self):
332
        do_upload(self)
333

    
334
    def get_raw_memory(self, number):
335
        return repr(self._memobj.memory[number - 1])
336

    
337
    def _decode_tone(self, val):
338
        val = int(val)
339
        if val == 16665:
340
            return '', None, None
341
        elif val >= 12000:
342
            return 'DTCS', val - 12000, 'R'
343
        elif val >= 8000:
344
            return 'DTCS', val - 8000, 'N'
345
        else:
346
            return 'Tone', val / 10.0, None
347

    
348
    def _encode_tone(self, memval, mode, value, pol):
349
        if mode == '':
350
            memval[0].set_raw(0xFF)
351
            memval[1].set_raw(0xFF)
352
        elif mode == 'Tone':
353
            memval.set_value(int(value * 10))
354
        elif mode == 'DTCS':
355
            flag = 0x80 if pol == 'N' else 0xC0
356
            memval.set_value(value)
357
            memval[1].set_bits(flag)
358
        else:
359
            raise Exception("Internal error: invalid mode `%s'" % mode)
360

    
361
    def get_memory(self, number):
362
        _mem = self._memobj.memory[number - 1]
363

    
364
        mem = chirp_common.Memory()
365

    
366
        mem.number = number
367
        mem.freq = int(_mem.rxfreq) * 10
368

    
369
        # We'll consider any blank (i.e. 0MHz frequency) to be empty
370
        if mem.freq == 0:
371
            mem.empty = True
372
            return mem
373

    
374
        if _mem.rxfreq.get_raw() == "\xFF\xFF\xFF\xFF":
375
            mem.freq = 0
376
            mem.empty = True
377
            return mem
378

    
379
        if _mem.txfreq.get_raw() == "\xFF\xFF\xFF\xFF":
380
            mem.duplex = "off"
381
            mem.offset = 0
382
        elif int(_mem.rxfreq) == int(_mem.txfreq):
383
            mem.duplex = ""
384
            mem.offset = 0
385
        else:
386
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
387
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
388

    
389
        mem.mode = not _mem.narrow and "FM" or "NFM"
390
        mem.power = H777_POWER_LEVELS[_mem.highpower]
391

    
392
        mem.skip = _mem.skip and "S" or ""
393

    
394
        txtone = self._decode_tone(_mem.txtone)
395
        rxtone = self._decode_tone(_mem.rxtone)
396
        chirp_common.split_tone_decode(mem, txtone, rxtone)
397

    
398
        mem.extra = RadioSettingGroup("Extra", "extra")
399
        rs = RadioSetting("bcl", "Busy Channel Lockout",
400
                          RadioSettingValueBoolean(not _mem.bcl))
401
        mem.extra.append(rs)
402
        rs = RadioSetting("beatshift", "Beat Shift(scramble)",
403
                          RadioSettingValueBoolean(not _mem.beatshift))
404
        mem.extra.append(rs)
405

    
406
        return mem
407

    
408
    def set_memory(self, mem):
409
        # Get a low-level memory object mapped to the image
410
        _mem = self._memobj.memory[mem.number - 1]
411

    
412
        if mem.empty:
413
            _mem.set_raw("\xFF" * (_mem.size() / 8))
414
            return
415

    
416
        _mem.rxfreq = mem.freq / 10
417

    
418
        if mem.duplex == "off":
419
            for i in range(0, 4):
420
                _mem.txfreq[i].set_raw("\xFF")
421
        elif mem.duplex == "split":
422
            _mem.txfreq = mem.offset / 10
423
        elif mem.duplex == "+":
424
            _mem.txfreq = (mem.freq + mem.offset) / 10
425
        elif mem.duplex == "-":
426
            _mem.txfreq = (mem.freq - mem.offset) / 10
427
        else:
428
            _mem.txfreq = mem.freq / 10
429

    
430
        txtone, rxtone = chirp_common.split_tone_encode(mem)
431
        self._encode_tone(_mem.txtone, *txtone)
432
        self._encode_tone(_mem.rxtone, *rxtone)
433

    
434
        _mem.narrow = 'N' in mem.mode
435
        _mem.highpower = mem.power == H777_POWER_LEVELS[1]
436
        _mem.skip = mem.skip == "S"
437

    
438
        for setting in mem.extra:
439
            # NOTE: Only two settings right now, both are inverted
440
            setattr(_mem, setting.get_name(), not int(setting.value))
441

    
442
        # When set to one, official programming software (BF-480) shows always
443
        # "WFM", even if we choose "NFM". Therefore, for compatibility
444
        # purposes, we will set these to zero.
445
        _mem.unknown1 = 0
446
        _mem.unknown2 = 0
447
        _mem.unknown3 = 0
448

    
449
    def get_settings(self):
450
        _settings = self._memobj.settings
451
        basic = RadioSettingGroup("basic", "Basic Settings")
452
        top = RadioSettings(basic)
453

    
454
        # TODO: Check that all these settings actually do what they
455
        # say they do.
456

    
457
        rs = RadioSetting("voiceprompt", "Voice prompt",
458
                          RadioSettingValueBoolean(_settings.voiceprompt))
459
        basic.append(rs)
460

    
461
        rs = RadioSetting("voicelanguage", "Voice language",
462
                          RadioSettingValueList(
463
                              VOICE_LIST,
464
                              VOICE_LIST[_settings.voicelanguage]))
465
        basic.append(rs)
466

    
467
        rs = RadioSetting("scan", "Scan",
468
                          RadioSettingValueBoolean(_settings.scan))
469
        basic.append(rs)
470

    
471
        rs = RadioSetting("settings2.scanmode", "Scan mode",
472
                          RadioSettingValueList(
473
                              SCANMODE_LIST,
474
                              SCANMODE_LIST[self._memobj.settings2.scanmode]))
475
        basic.append(rs)
476

    
477
        rs = RadioSetting("vox", "VOX",
478
                          RadioSettingValueBoolean(_settings.vox))
479
        basic.append(rs)
480

    
481
        rs = RadioSetting("voxlevel", "VOX level",
482
                          RadioSettingValueInteger(
483
                              1, 5, _settings.voxlevel + 1))
484
        basic.append(rs)
485

    
486
        rs = RadioSetting("voxinhibitonrx", "Inhibit VOX on receive",
487
                          RadioSettingValueBoolean(_settings.voxinhibitonrx))
488
        basic.append(rs)
489

    
490
        rs = RadioSetting("lowvolinhibittx", "Low voltage inhibit transmit",
491
                          RadioSettingValueBoolean(_settings.lowvolinhibittx))
492
        basic.append(rs)
493

    
494
        rs = RadioSetting("highvolinhibittx", "High voltage inhibit transmit",
495
                          RadioSettingValueBoolean(_settings.highvolinhibittx))
496
        basic.append(rs)
497

    
498
        rs = RadioSetting("alarm", "Alarm",
499
                          RadioSettingValueBoolean(_settings.alarm))
500
        basic.append(rs)
501

    
502
        # TODO: This should probably be called “FM Broadcast Band Radio”
503
        # or something. I'm not sure if the model actually has one though.
504
        if self._has_fm:
505
            rs = RadioSetting("fmradio", "FM function",
506
                              RadioSettingValueBoolean(_settings.fmradio))
507
            basic.append(rs)
508

    
509
        rs = RadioSetting("settings2.beep", "Beep",
510
                          RadioSettingValueBoolean(
511
                              self._memobj.settings2.beep))
512
        basic.append(rs)
513

    
514
        rs = RadioSetting("settings2.batterysaver", "Battery saver",
515
                          RadioSettingValueBoolean(
516
                              self._memobj.settings2.batterysaver))
517
        basic.append(rs)
518

    
519
        rs = RadioSetting("settings2.squelchlevel", "Squelch level",
520
                          RadioSettingValueInteger(
521
                              0, 9, self._memobj.settings2.squelchlevel))
522
        basic.append(rs)
523

    
524
        if self._has_sidekey:
525
            rs = RadioSetting("settings2.sidekeyfunction", "Side key function",
526
                              RadioSettingValueList(
527
                                  self.SIDEKEYFUNCTION_LIST,
528
                                  self.SIDEKEYFUNCTION_LIST[
529
                                      self._memobj.settings2.sidekeyfunction]))
530
            basic.append(rs)
531

    
532
        rs = RadioSetting("settings2.timeouttimer", "Timeout timer",
533
                          RadioSettingValueList(
534
                              TIMEOUTTIMER_LIST,
535
                              TIMEOUTTIMER_LIST[
536
                                  self._memobj.settings2.timeouttimer]))
537
        basic.append(rs)
538

    
539
        return top
540

    
541
    def set_settings(self, settings):
542
        for element in settings:
543
            if not isinstance(element, RadioSetting):
544
                self.set_settings(element)
545
                continue
546
            else:
547
                try:
548
                    if "." in element.get_name():
549
                        bits = element.get_name().split(".")
550
                        obj = self._memobj
551
                        for bit in bits[:-1]:
552
                            obj = getattr(obj, bit)
553
                        setting = bits[-1]
554
                    else:
555
                        obj = self._memobj.settings
556
                        setting = element.get_name()
557

    
558
                    if element.has_apply_callback():
559
                        LOG.debug("Using apply callback")
560
                        element.run_apply_callback()
561
                    elif setting == "voxlevel":
562
                        setattr(obj, setting, int(element.value) - 1)
563
                    else:
564
                        LOG.debug("Setting %s = %s" % (setting, element.value))
565
                        setattr(obj, setting, element.value)
566
                except Exception, e:
567
                    LOG.debug(element.get_name())
568
                    raise
569

    
570

    
571
class H777TestCase(unittest.TestCase):
572

    
573
    def setUp(self):
574
        self.driver = H777Radio(None)
575
        self.testdata = bitwise.parse("lbcd foo[2];",
576
                                      memmap.MemoryMap("\x00\x00"))
577

    
578
    def test_decode_tone_dtcs_normal(self):
579
        mode, value, pol = self.driver._decode_tone(8023)
580
        self.assertEqual('DTCS', mode)
581
        self.assertEqual(23, value)
582
        self.assertEqual('N', pol)
583

    
584
    def test_decode_tone_dtcs_rev(self):
585
        mode, value, pol = self.driver._decode_tone(12023)
586
        self.assertEqual('DTCS', mode)
587
        self.assertEqual(23, value)
588
        self.assertEqual('R', pol)
589

    
590
    def test_decode_tone_tone(self):
591
        mode, value, pol = self.driver._decode_tone(885)
592
        self.assertEqual('Tone', mode)
593
        self.assertEqual(88.5, value)
594
        self.assertEqual(None, pol)
595

    
596
    def test_decode_tone_none(self):
597
        mode, value, pol = self.driver._decode_tone(16665)
598
        self.assertEqual('', mode)
599
        self.assertEqual(None, value)
600
        self.assertEqual(None, pol)
601

    
602
    def test_encode_tone_dtcs_normal(self):
603
        self.driver._encode_tone(self.testdata.foo, 'DTCS', 23, 'N')
604
        self.assertEqual(8023, int(self.testdata.foo))
605

    
606
    def test_encode_tone_dtcs_rev(self):
607
        self.driver._encode_tone(self.testdata.foo, 'DTCS', 23, 'R')
608
        self.assertEqual(12023, int(self.testdata.foo))
609

    
610
    def test_encode_tone(self):
611
        self.driver._encode_tone(self.testdata.foo, 'Tone', 88.5, 'N')
612
        self.assertEqual(885, int(self.testdata.foo))
613

    
614
    def test_encode_tone_none(self):
615
        self.driver._encode_tone(self.testdata.foo, '', 67.0, 'N')
616
        self.assertEqual(16665, int(self.testdata.foo))
617

    
618

    
619
@directory.register
620
class ROGA2SRadio(H777Radio):
621
    VENDOR = "Radioddity"
622
    MODEL = "GA-2S"
623
    _has_fm = False
624
    SIDEKEYFUNCTION_LIST = ["Off", "Monitor", "Unused", "Alarm"]
625

    
626
    @classmethod
627
    def match_model(cls, filedata, filename):
628
        # This model is only ever matched via metadata
629
        return False
    (1-1/1)