Project

General

Profile

Bug #1441 » h777.py

Daniel Hjort, 02/14/2014 07:22 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

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

    
28
DEBUG = os.getenv("CHIRP_DEBUG") and True or False
29

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

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

    
80
# TODO: Is it 1 watt?
81
H777_POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=1.00),
82
                     chirp_common.PowerLevel("High", watts=5.00)]
83
VOICE_LIST = ["English", "Chinese"]
84
SIDEKEYFUNCTION_LIST = ["Off", "Monitor", "Transmit Power", "Alarm"]
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
def _h777_enter_programming_mode(radio):
96
    serial = radio.pipe
97

    
98
    print "ack:"
99
    print CMD_ACK
100

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

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

    
115
    print "ack:"
116
    print ack
117

    
118
    try:
119
        serial.write("\x02")
120
        ident = serial.read(8)
121
    except:
122
        raise errors.RadioError("Error communicating with radio")
123

    
124
    print "ident:"
125
    print ident
126

    
127
    if not ident.startswith("P3107"):
128
        print util.hexprint(ident)
129
        raise errors.RadioError("Radio returned unknown identification string")
130

    
131
    try:
132
        serial.write(CMD_ACK)
133
        ack = serial.read(1)
134
    except:
135
        raise errors.RadioError("Error communicating with radio")
136

    
137
    if ack != CMD_ACK:
138
        raise errors.RadioError("Radio refused to enter programming mode")
139

    
140
def _h777_exit_programming_mode(radio):
141
    serial = radio.pipe
142
    try:
143
        serial.write("E")
144
    except:
145
        raise errors.RadioError("Radio refused to exit programming mode")
146

    
147
def _h777_read_block(radio, block_addr, block_size):
148
    serial = radio.pipe
149

    
150
    cmd = struct.pack(">cHb", 'R', block_addr, BLOCK_SIZE)
151
    expectedresponse = "W" + cmd[1:]
152
    if DEBUG:
153
        print("Reading block %04x..." % (block_addr))
154

    
155
    try:
156
        serial.write(cmd)
157
        response = serial.read(4 + BLOCK_SIZE)
158
        if response[:4] != expectedresponse:
159
            raise Exception("Error reading block %04x." % (block_addr))
160

    
161
        block_data = response[4:]
162

    
163
        serial.write(CMD_ACK)
164
        ack = serial.read(1)
165
    except:
166
        raise errors.RadioError("Failed to read block at %04x" % block_addr)
167

    
168
    if ack != CMD_ACK:
169
        raise Exception("No ACK reading block %04x." % (block_addr))
170

    
171
    return block_data
172

    
173
def _h777_write_block(radio, block_addr, block_size):
174
    serial = radio.pipe
175

    
176
    cmd = struct.pack(">cHb", 'W', block_addr, BLOCK_SIZE)
177
    data = radio.get_mmap()[block_addr:block_addr + 8]
178

    
179
    if DEBUG:
180
        print("Writing Data:")
181
        print util.hexprint(cmd + data)
182

    
183
    try:
184
        serial.write(cmd + data)
185
        if serial.read(1) != CMD_ACK:
186
            raise Exception("No ACK")
187
    except:
188
        raise errors.RadioError("Failed to send block "
189
                                "to radio at %04x" % block_addr)
190

    
191
def do_download(radio):
192
    print "download"
193
    _h777_enter_programming_mode(radio)
194

    
195
    data = ""
196

    
197
    status = chirp_common.Status()
198
    status.msg = "Cloning from radio"
199

    
200
    status.cur = 0
201
    status.max = radio._memsize
202

    
203
    for addr in range(0, radio._memsize, BLOCK_SIZE):
204
        status.cur = addr + BLOCK_SIZE
205
        radio.status_fn(status)
206

    
207
        block = _h777_read_block(radio, addr, BLOCK_SIZE)
208
        data += block
209

    
210
        if DEBUG:
211
            print "Address: %04x" % addr
212
            print util.hexprint(block)
213

    
214
    _h777_exit_programming_mode(radio)
215

    
216
    return memmap.MemoryMap(data)
217

    
218
def do_upload(radio):
219
    status = chirp_common.Status()
220
    status.msg = "Uploading to radio"
221

    
222
    _h777_enter_programming_mode(radio)
223

    
224
    status.cur = 0
225
    status.max = radio._memsize
226

    
227
    for start_addr, end_addr in radio._ranges:
228
        for addr in range(start_addr, end_addr, BLOCK_SIZE):
229
            status.cur = addr + BLOCK_SIZE
230
            radio.status_fn(status)
231
            _h777_write_block(radio, addr, BLOCK_SIZE)
232

    
233
    _h777_exit_programming_mode(radio)
234

    
235
@directory.register
236
class H777Radio(chirp_common.CloneModeRadio):
237
    """HST H-777"""
238
    # VENDOR = "Heng Shun Tong (恒顺通)"
239
    # MODEL = "H-777"
240
    VENDOR = "Baofeng"
241
    MODEL = "BF-888"
242
    BAUD_RATE = 9600
243

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

    
254
    _ranges = [
255
        (0x0000, 0x0110),
256
        (0x02B0, 0x02C0),
257
        (0x0380, 0x03E0),
258
        ]
259
    _memsize = 0x03E0
260

    
261
    def get_features(self):
262
        rf = chirp_common.RadioFeatures()
263
        rf.has_settings = True
264
        rf.valid_modes = ["NFM", "FM"]  # 12.5 KHz, 25 kHz.
265
        rf.valid_skips = ["", "S"]
266
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
267
        rf.has_rx_dtcs = True
268
        rf.has_ctone = True
269
        rf.has_cross = True
270
        rf.has_tuning_step = False
271
        rf.has_bank = False
272
        rf.has_name = False
273
        rf.memory_bounds = (1, 16)
274
        rf.valid_bands = [(400000000, 470000000)]
275
        rf.valid_power_levels = H777_POWER_LEVELS
276

    
277
        return rf
278

    
279
    def process_mmap(self):
280
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
281

    
282
    def sync_in(self):
283
        self._mmap = do_download(self)
284
        self.process_mmap()
285

    
286
    def sync_out(self):
287
        do_upload(self)
288

    
289
    def get_raw_memory(self, number):
290
        return repr(self._memobj.memory[number - 1])
291

    
292
    def _decode_tone(self, val):
293
        val = int(val)
294
        if val == 16665:
295
            return '', None, None
296
        elif val >= 12000:
297
            return 'DTCS', val - 12000, 'R'
298
        elif val >= 8000:
299
            return 'DTCS', val - 8000, 'N'
300
        else:
301
            return 'Tone', val / 10.0, None
302

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

    
316
    def get_memory(self, number):
317
        _mem = self._memobj.memory[number - 1]
318

    
319
        mem = chirp_common.Memory()
320

    
321
        mem.number = number
322
        mem.freq = int(_mem.rxfreq) * 10
323

    
324
        # We'll consider any blank (i.e. 0MHz frequency) to be empty
325
        if mem.freq == 0:
326
            mem.empty = True
327
            return mem
328

    
329
        if _mem.rxfreq.get_raw() == "\xFF\xFF\xFF\xFF":
330
            mem.freq = 0
331
            mem.empty = True
332
            return mem
333

    
334
        if int(_mem.rxfreq) == int(_mem.txfreq):
335
            mem.duplex = ""
336
            mem.offset = 0
337
        else:
338
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
339
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
340

    
341
        mem.mode = not _mem.narrow and "FM" or "NFM"
342
        mem.power = H777_POWER_LEVELS[_mem.highpower]
343

    
344
        mem.skip = _mem.skip and "S" or ""
345

    
346
        txtone = self._decode_tone(_mem.txtone)
347
        rxtone = self._decode_tone(_mem.rxtone)
348
        chirp_common.split_tone_decode(mem, txtone, rxtone)
349

    
350
        mem.extra = RadioSettingGroup("Extra", "extra")
351
        rs = RadioSetting("bcl", "Busy Channel Lockout",
352
                          RadioSettingValueBoolean(not _mem.bcl))
353
        mem.extra.append(rs)
354
        rs = RadioSetting("beatshift", "Beat Shift(scramble)",
355
                          RadioSettingValueBoolean(not _mem.beatshift))
356
        mem.extra.append(rs)
357

    
358
        return mem
359

    
360
    def set_memory(self, mem):
361
        # Get a low-level memory object mapped to the image
362
        _mem = self._memobj.memory[mem.number - 1]
363

    
364
        if mem.empty:
365
            _mem.set_raw("\xFF" * (_mem.size() / 8))
366
            return
367

    
368
        _mem.rxfreq = mem.freq / 10
369

    
370
        if mem.duplex == "off":
371
            for i in range(0, 4):
372
                _mem.txfreq[i].set_raw("\xFF")
373
        elif mem.duplex == "split":
374
            _mem.txfreq = mem.offset / 10
375
        elif mem.duplex == "+":
376
            _mem.txfreq = (mem.freq + mem.offset) / 10
377
        elif mem.duplex == "-":
378
            _mem.txfreq = (mem.freq - mem.offset) / 10
379
        else:
380
            _mem.txfreq = mem.freq / 10
381

    
382
        txtone, rxtone = chirp_common.split_tone_encode(mem)
383
        self._encode_tone(_mem.txtone, *txtone)
384
        self._encode_tone(_mem.rxtone, *rxtone)
385

    
386
        _mem.narrow = 'N' in mem.mode
387
        _mem.highpower = mem.power == H777_POWER_LEVELS[1]
388
        _mem.skip = mem.skip == "S"
389

    
390
        for setting in mem.extra:
391
            # NOTE: Only two settings right now, both are inverted
392
            setattr(_mem, setting.get_name(), not setting.value)
393

    
394
    def get_settings(self):
395
        _settings = self._memobj.settings
396
        basic = RadioSettingGroup("basic", "Basic Settings")
397

    
398
        # TODO: Check that all these settings actually do what they
399
        # say they do.
400

    
401
        rs = RadioSetting("voiceprompt", "Voice prompt",
402
                          RadioSettingValueBoolean(_settings.voiceprompt))
403
        basic.append(rs)
404

    
405
        rs = RadioSetting("voicelanguage", "Voice language",
406
                          RadioSettingValueList(VOICE_LIST,
407
                              VOICE_LIST[_settings.voicelanguage]))
408
        basic.append(rs)
409

    
410
        rs = RadioSetting("scan", "Scan",
411
                          RadioSettingValueBoolean(_settings.scan))
412
        basic.append(rs)
413

    
414
        rs = RadioSetting("settings2.scanmode", "Scan mode",
415
                          RadioSettingValueList(SCANMODE_LIST,
416
                          SCANMODE_LIST[self._memobj.settings2.scanmode]))
417
        basic.append(rs)
418

    
419
        rs = RadioSetting("vox", "VOX",
420
                          RadioSettingValueBoolean(_settings.vox))
421
        basic.append(rs)
422

    
423
        rs = RadioSetting("voxlevel", "VOX level",
424
                          RadioSettingValueInteger(
425
                              1, 5, _settings.voxlevel + 1))
426
        basic.append(rs)
427

    
428
        rs = RadioSetting("voxinhibitonrx", "Inhibit VOX on receive",
429
                          RadioSettingValueBoolean(_settings.voxinhibitonrx))
430
        basic.append(rs)
431

    
432
        rs = RadioSetting("lowvolinhibittx", "Low voltage inhibit transmit",
433
                          RadioSettingValueBoolean(_settings.lowvolinhibittx))
434
        basic.append(rs)
435

    
436
        rs = RadioSetting("highvolinhibittx", "High voltage inhibit transmit",
437
                          RadioSettingValueBoolean(_settings.highvolinhibittx))
438
        basic.append(rs)
439

    
440
        rs = RadioSetting("alarm", "Alarm",
441
                          RadioSettingValueBoolean(_settings.alarm))
442
        basic.append(rs)
443

    
444
        # TODO: This should probably be called “FM Broadcast Band Radio”
445
        # or something. I'm not sure if the model actually has one though.
446
        rs = RadioSetting("fmradio", "FM function",
447
                          RadioSettingValueBoolean(_settings.fmradio))
448
        basic.append(rs)
449

    
450
        rs = RadioSetting("settings2.beep", "Beep",
451
                          RadioSettingValueBoolean(
452
                              self._memobj.settings2.beep))
453
        basic.append(rs)
454

    
455
        rs = RadioSetting("settings2.batterysaver", "Battery saver",
456
                          RadioSettingValueBoolean(
457
                              self._memobj.settings2.batterysaver))
458
        basic.append(rs)
459

    
460
        rs = RadioSetting("settings2.squelchlevel", "Squelch level",
461
                          RadioSettingValueInteger(0, 9,
462
                              self._memobj.settings2.squelchlevel))
463
        basic.append(rs)
464

    
465
        rs = RadioSetting("settings2.sidekeyfunction", "Side key function",
466
                          RadioSettingValueList(SIDEKEYFUNCTION_LIST,
467
                          SIDEKEYFUNCTION_LIST[
468
                              self._memobj.settings2.sidekeyfunction]))
469
        basic.append(rs)
470

    
471
        rs = RadioSetting("settings2.timeouttimer", "Timeout timer",
472
                          RadioSettingValueList(TIMEOUTTIMER_LIST,
473
                          TIMEOUTTIMER_LIST[
474
                              self._memobj.settings2.timeouttimer]))
475
        basic.append(rs)
476

    
477
        return basic
478

    
479
    def set_settings(self, settings):
480
        for element in settings:
481
            if not isinstance(element, RadioSetting):
482
                self.set_settings(element)
483
                continue
484
            else:
485
                try:
486
                    if "." in element.get_name():
487
                        bits = element.get_name().split(".")
488
                        obj = self._memobj
489
                        for bit in bits[:-1]:
490
                            obj = getattr(obj, bit)
491
                        setting = bits[-1]
492
                    else:
493
                        obj = self._memobj.settings
494
                        setting = element.get_name()
495

    
496
                    if element.has_apply_callback():
497
                        print "Using apply callback"
498
                        element.run_apply_callback()
499
                    elif setting == "voxlevel":
500
                        setattr(obj, setting, int(element.value) - 1)
501
                    else:
502
                        print "Setting %s = %s" % (setting, element.value)
503
                        setattr(obj, setting, element.value)
504
                except Exception, e:
505
                    print element.get_name()
506
                    raise
507

    
508
class H777TestCase(unittest.TestCase):
509
    def setUp(self):
510
        self.driver = H777Radio(None)
511
        self.testdata = bitwise.parse("lbcd foo[2];",
512
                                      memmap.MemoryMap("\x00\x00"))
513

    
514
    def test_decode_tone_dtcs_normal(self):
515
        mode, value, pol = self.driver._decode_tone(8023)
516
        self.assertEqual('DTCS', mode)
517
        self.assertEqual(23, value)
518
        self.assertEqual('N', pol)
519

    
520
    def test_decode_tone_dtcs_rev(self):
521
        mode, value, pol = self.driver._decode_tone(12023)
522
        self.assertEqual('DTCS', mode)
523
        self.assertEqual(23, value)
524
        self.assertEqual('R', pol)
525

    
526
    def test_decode_tone_tone(self):
527
        mode, value, pol = self.driver._decode_tone(885)
528
        self.assertEqual('Tone', mode)
529
        self.assertEqual(88.5, value)
530
        self.assertEqual(None, pol)
531

    
532
    def test_decode_tone_none(self):
533
        mode, value, pol = self.driver._decode_tone(16665)
534
        self.assertEqual('', mode)
535
        self.assertEqual(None, value)
536
        self.assertEqual(None, pol)
537

    
538
    def test_encode_tone_dtcs_normal(self):
539
        self.driver._encode_tone(self.testdata.foo, 'DTCS', 23, 'N')
540
        self.assertEqual(8023, int(self.testdata.foo))
541

    
542
    def test_encode_tone_dtcs_rev(self):
543
        self.driver._encode_tone(self.testdata.foo, 'DTCS', 23, 'R')
544
        self.assertEqual(12023, int(self.testdata.foo))
545

    
546
    def test_encode_tone(self):
547
        self.driver._encode_tone(self.testdata.foo, 'Tone', 88.5, 'N')
548
        self.assertEqual(885, int(self.testdata.foo))
549

    
550
    def test_encode_tone_none(self):
551
        self.driver._encode_tone(self.testdata.foo, '', 67.0, 'N')
552
        self.assertEqual(16665, int(self.testdata.foo))
(1-1/2)