Project

General

Profile

Bug #4249 » h777.py

no pause between "\x02" and "PROGRAM" - Jim Unroe, 11/24/2016 08:39 AM

 
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
SIDEKEYFUNCTION_LIST = ["Off", "Monitor", "Transmit Power", "Alarm"]
86
TIMEOUTTIMER_LIST = ["Off", "30 seconds", "60 seconds", "90 seconds",
87
                     "120 seconds", "150 seconds", "180 seconds",
88
                     "210 seconds", "240 seconds", "270 seconds",
89
                     "300 seconds"]
90
SCANMODE_LIST = ["Carrier", "Time"]
91

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

    
96

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

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

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

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

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

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

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

    
132

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

    
140

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

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

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

    
154
        block_data = response[4:]
155

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

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

    
164
    return block_data
165

    
166

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

    
170
    cmd = struct.pack(">cHb", 'W', block_addr, BLOCK_SIZE)
171
    data = radio.get_mmap()[block_addr:block_addr + 8]
172

    
173
    LOG.debug("Writing Data:")
174
    LOG.debug(util.hexprint(cmd + data))
175

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

    
184

    
185
def do_download(radio):
186
    LOG.debug("download")
187
    _h777_enter_programming_mode(radio)
188

    
189
    data = ""
190

    
191
    status = chirp_common.Status()
192
    status.msg = "Cloning from radio"
193

    
194
    status.cur = 0
195
    status.max = radio._memsize
196

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

    
201
        block = _h777_read_block(radio, addr, BLOCK_SIZE)
202
        data += block
203

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

    
207
    _h777_exit_programming_mode(radio)
208

    
209
    return memmap.MemoryMap(data)
210

    
211

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

    
216
    _h777_enter_programming_mode(radio)
217

    
218
    status.cur = 0
219
    status.max = radio._memsize
220

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

    
227
    _h777_exit_programming_mode(radio)
228

    
229

    
230
@directory.register
231
class H777Radio(chirp_common.CloneModeRadio):
232
    """HST H-777"""
233
    # VENDOR = "Heng Shun Tong (恒顺通)"
234
    # MODEL = "H-777"
235
    VENDOR = "Baofeng"
236
    MODEL = "BF-888"
237
    BAUD_RATE = 9600
238

    
239
    # This code currently requires that ranges start at 0x0000
240
    # and are continious. In the original program 0x0388 and 0x03C8
241
    # are only written (all bytes 0xFF), not read.
242
    # _ranges = [
243
    #       (0x0000, 0x0110),
244
    #       (0x02B0, 0x02C0),
245
    #       (0x0380, 0x03E0)
246
    #       ]
247
    # Memory starts looping at 0x1000... But not every 0x1000.
248

    
249
    _ranges = [
250
        (0x0000, 0x0110),
251
        (0x02B0, 0x02C0),
252
        (0x0380, 0x03E0),
253
    ]
254
    _memsize = 0x03E0
255

    
256
    def get_features(self):
257
        rf = chirp_common.RadioFeatures()
258
        rf.has_settings = True
259
        rf.valid_modes = ["NFM", "FM"]  # 12.5 KHz, 25 kHz.
260
        rf.valid_skips = ["", "S"]
261
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
262
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
263
        rf.can_odd_split = True
264
        rf.has_rx_dtcs = True
265
        rf.has_ctone = True
266
        rf.has_cross = True
267
        rf.valid_cross_modes = [
268
            "Tone->Tone",
269
            "DTCS->",
270
            "->DTCS",
271
            "Tone->DTCS",
272
            "DTCS->Tone",
273
            "->Tone",
274
            "DTCS->DTCS"]
275
        rf.has_tuning_step = False
276
        rf.has_bank = False
277
        rf.has_name = False
278
        rf.memory_bounds = (1, 16)
279
        rf.valid_bands = [(400000000, 470000000)]
280
        rf.valid_power_levels = H777_POWER_LEVELS
281

    
282
        return rf
283

    
284
    def process_mmap(self):
285
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
286

    
287
    def sync_in(self):
288
        self._mmap = do_download(self)
289
        self.process_mmap()
290

    
291
    def sync_out(self):
292
        do_upload(self)
293

    
294
    def get_raw_memory(self, number):
295
        return repr(self._memobj.memory[number - 1])
296

    
297
    def _decode_tone(self, val):
298
        val = int(val)
299
        if val == 16665:
300
            return '', None, None
301
        elif val >= 12000:
302
            return 'DTCS', val - 12000, 'R'
303
        elif val >= 8000:
304
            return 'DTCS', val - 8000, 'N'
305
        else:
306
            return 'Tone', val / 10.0, None
307

    
308
    def _encode_tone(self, memval, mode, value, pol):
309
        if mode == '':
310
            memval[0].set_raw(0xFF)
311
            memval[1].set_raw(0xFF)
312
        elif mode == 'Tone':
313
            memval.set_value(int(value * 10))
314
        elif mode == 'DTCS':
315
            flag = 0x80 if pol == 'N' else 0xC0
316
            memval.set_value(value)
317
            memval[1].set_bits(flag)
318
        else:
319
            raise Exception("Internal error: invalid mode `%s'" % mode)
320

    
321
    def get_memory(self, number):
322
        _mem = self._memobj.memory[number - 1]
323

    
324
        mem = chirp_common.Memory()
325

    
326
        mem.number = number
327
        mem.freq = int(_mem.rxfreq) * 10
328

    
329
        # We'll consider any blank (i.e. 0MHz frequency) to be empty
330
        if mem.freq == 0:
331
            mem.empty = True
332
            return mem
333

    
334
        if _mem.rxfreq.get_raw() == "\xFF\xFF\xFF\xFF":
335
            mem.freq = 0
336
            mem.empty = True
337
            return mem
338

    
339
        if _mem.txfreq.get_raw() == "\xFF\xFF\xFF\xFF":
340
            mem.duplex = "off"
341
            mem.offset = 0
342
        elif int(_mem.rxfreq) == int(_mem.txfreq):
343
            mem.duplex = ""
344
            mem.offset = 0
345
        else:
346
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
347
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
348

    
349
        mem.mode = not _mem.narrow and "FM" or "NFM"
350
        mem.power = H777_POWER_LEVELS[_mem.highpower]
351

    
352
        mem.skip = _mem.skip and "S" or ""
353

    
354
        txtone = self._decode_tone(_mem.txtone)
355
        rxtone = self._decode_tone(_mem.rxtone)
356
        chirp_common.split_tone_decode(mem, txtone, rxtone)
357

    
358
        mem.extra = RadioSettingGroup("Extra", "extra")
359
        rs = RadioSetting("bcl", "Busy Channel Lockout",
360
                          RadioSettingValueBoolean(not _mem.bcl))
361
        mem.extra.append(rs)
362
        rs = RadioSetting("beatshift", "Beat Shift(scramble)",
363
                          RadioSettingValueBoolean(not _mem.beatshift))
364
        mem.extra.append(rs)
365

    
366
        return mem
367

    
368
    def set_memory(self, mem):
369
        # Get a low-level memory object mapped to the image
370
        _mem = self._memobj.memory[mem.number - 1]
371

    
372
        if mem.empty:
373
            _mem.set_raw("\xFF" * (_mem.size() / 8))
374
            return
375

    
376
        _mem.rxfreq = mem.freq / 10
377

    
378
        if mem.duplex == "off":
379
            for i in range(0, 4):
380
                _mem.txfreq[i].set_raw("\xFF")
381
        elif mem.duplex == "split":
382
            _mem.txfreq = mem.offset / 10
383
        elif mem.duplex == "+":
384
            _mem.txfreq = (mem.freq + mem.offset) / 10
385
        elif mem.duplex == "-":
386
            _mem.txfreq = (mem.freq - mem.offset) / 10
387
        else:
388
            _mem.txfreq = mem.freq / 10
389

    
390
        txtone, rxtone = chirp_common.split_tone_encode(mem)
391
        self._encode_tone(_mem.txtone, *txtone)
392
        self._encode_tone(_mem.rxtone, *rxtone)
393

    
394
        _mem.narrow = 'N' in mem.mode
395
        _mem.highpower = mem.power == H777_POWER_LEVELS[1]
396
        _mem.skip = mem.skip == "S"
397

    
398
        for setting in mem.extra:
399
            # NOTE: Only two settings right now, both are inverted
400
            setattr(_mem, setting.get_name(), not int(setting.value))
401

    
402
        # When set to one, official programming software (BF-480) shows always
403
        # "WFM", even if we choose "NFM". Therefore, for compatibility
404
        # purposes, we will set these to zero.
405
        _mem.unknown1 = 0
406
        _mem.unknown2 = 0
407
        _mem.unknown3 = 0
408

    
409
    def get_settings(self):
410
        _settings = self._memobj.settings
411
        basic = RadioSettingGroup("basic", "Basic Settings")
412
        top = RadioSettings(basic)
413

    
414
        # TODO: Check that all these settings actually do what they
415
        # say they do.
416

    
417
        rs = RadioSetting("voiceprompt", "Voice prompt",
418
                          RadioSettingValueBoolean(_settings.voiceprompt))
419
        basic.append(rs)
420

    
421
        rs = RadioSetting("voicelanguage", "Voice language",
422
                          RadioSettingValueList(
423
                              VOICE_LIST,
424
                              VOICE_LIST[_settings.voicelanguage]))
425
        basic.append(rs)
426

    
427
        rs = RadioSetting("scan", "Scan",
428
                          RadioSettingValueBoolean(_settings.scan))
429
        basic.append(rs)
430

    
431
        rs = RadioSetting("settings2.scanmode", "Scan mode",
432
                          RadioSettingValueList(
433
                              SCANMODE_LIST,
434
                              SCANMODE_LIST[self._memobj.settings2.scanmode]))
435
        basic.append(rs)
436

    
437
        rs = RadioSetting("vox", "VOX",
438
                          RadioSettingValueBoolean(_settings.vox))
439
        basic.append(rs)
440

    
441
        rs = RadioSetting("voxlevel", "VOX level",
442
                          RadioSettingValueInteger(
443
                              1, 5, _settings.voxlevel + 1))
444
        basic.append(rs)
445

    
446
        rs = RadioSetting("voxinhibitonrx", "Inhibit VOX on receive",
447
                          RadioSettingValueBoolean(_settings.voxinhibitonrx))
448
        basic.append(rs)
449

    
450
        rs = RadioSetting("lowvolinhibittx", "Low voltage inhibit transmit",
451
                          RadioSettingValueBoolean(_settings.lowvolinhibittx))
452
        basic.append(rs)
453

    
454
        rs = RadioSetting("highvolinhibittx", "High voltage inhibit transmit",
455
                          RadioSettingValueBoolean(_settings.highvolinhibittx))
456
        basic.append(rs)
457

    
458
        rs = RadioSetting("alarm", "Alarm",
459
                          RadioSettingValueBoolean(_settings.alarm))
460
        basic.append(rs)
461

    
462
        # TODO: This should probably be called “FM Broadcast Band Radio”
463
        # or something. I'm not sure if the model actually has one though.
464
        rs = RadioSetting("fmradio", "FM function",
465
                          RadioSettingValueBoolean(_settings.fmradio))
466
        basic.append(rs)
467

    
468
        rs = RadioSetting("settings2.beep", "Beep",
469
                          RadioSettingValueBoolean(
470
                              self._memobj.settings2.beep))
471
        basic.append(rs)
472

    
473
        rs = RadioSetting("settings2.batterysaver", "Battery saver",
474
                          RadioSettingValueBoolean(
475
                              self._memobj.settings2.batterysaver))
476
        basic.append(rs)
477

    
478
        rs = RadioSetting("settings2.squelchlevel", "Squelch level",
479
                          RadioSettingValueInteger(
480
                              0, 9, self._memobj.settings2.squelchlevel))
481
        basic.append(rs)
482

    
483
        rs = RadioSetting("settings2.sidekeyfunction", "Side key function",
484
                          RadioSettingValueList(
485
                              SIDEKEYFUNCTION_LIST,
486
                              SIDEKEYFUNCTION_LIST[
487
                                  self._memobj.settings2.sidekeyfunction]))
488
        basic.append(rs)
489

    
490
        rs = RadioSetting("settings2.timeouttimer", "Timeout timer",
491
                          RadioSettingValueList(
492
                              TIMEOUTTIMER_LIST,
493
                              TIMEOUTTIMER_LIST[
494
                                  self._memobj.settings2.timeouttimer]))
495
        basic.append(rs)
496

    
497
        return top
498

    
499
    def set_settings(self, settings):
500
        for element in settings:
501
            if not isinstance(element, RadioSetting):
502
                self.set_settings(element)
503
                continue
504
            else:
505
                try:
506
                    if "." in element.get_name():
507
                        bits = element.get_name().split(".")
508
                        obj = self._memobj
509
                        for bit in bits[:-1]:
510
                            obj = getattr(obj, bit)
511
                        setting = bits[-1]
512
                    else:
513
                        obj = self._memobj.settings
514
                        setting = element.get_name()
515

    
516
                    if element.has_apply_callback():
517
                        LOG.debug("Using apply callback")
518
                        element.run_apply_callback()
519
                    elif setting == "voxlevel":
520
                        setattr(obj, setting, int(element.value) - 1)
521
                    else:
522
                        LOG.debug("Setting %s = %s" % (setting, element.value))
523
                        setattr(obj, setting, element.value)
524
                except Exception, e:
525
                    LOG.debug(element.get_name())
526
                    raise
527

    
528

    
529
class H777TestCase(unittest.TestCase):
530

    
531
    def setUp(self):
532
        self.driver = H777Radio(None)
533
        self.testdata = bitwise.parse("lbcd foo[2];",
534
                                      memmap.MemoryMap("\x00\x00"))
535

    
536
    def test_decode_tone_dtcs_normal(self):
537
        mode, value, pol = self.driver._decode_tone(8023)
538
        self.assertEqual('DTCS', mode)
539
        self.assertEqual(23, value)
540
        self.assertEqual('N', pol)
541

    
542
    def test_decode_tone_dtcs_rev(self):
543
        mode, value, pol = self.driver._decode_tone(12023)
544
        self.assertEqual('DTCS', mode)
545
        self.assertEqual(23, value)
546
        self.assertEqual('R', pol)
547

    
548
    def test_decode_tone_tone(self):
549
        mode, value, pol = self.driver._decode_tone(885)
550
        self.assertEqual('Tone', mode)
551
        self.assertEqual(88.5, value)
552
        self.assertEqual(None, pol)
553

    
554
    def test_decode_tone_none(self):
555
        mode, value, pol = self.driver._decode_tone(16665)
556
        self.assertEqual('', mode)
557
        self.assertEqual(None, value)
558
        self.assertEqual(None, pol)
559

    
560
    def test_encode_tone_dtcs_normal(self):
561
        self.driver._encode_tone(self.testdata.foo, 'DTCS', 23, 'N')
562
        self.assertEqual(8023, int(self.testdata.foo))
563

    
564
    def test_encode_tone_dtcs_rev(self):
565
        self.driver._encode_tone(self.testdata.foo, 'DTCS', 23, 'R')
566
        self.assertEqual(12023, int(self.testdata.foo))
567

    
568
    def test_encode_tone(self):
569
        self.driver._encode_tone(self.testdata.foo, 'Tone', 88.5, 'N')
570
        self.assertEqual(885, int(self.testdata.foo))
571

    
572
    def test_encode_tone_none(self):
573
        self.driver._encode_tone(self.testdata.foo, '', 67.0, 'N')
574
        self.assertEqual(16665, int(self.testdata.foo))
(4-4/9)