Project

General

Profile

New Model #4933 » bf-t1 (hwh).py

Hank's modified version of Pavel's driver. - Harold Hankins, 12/11/2017 03:54 PM

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

    
16
import time
17
import struct
18
import logging
19

    
20
LOG = logging.getLogger(__name__)
21

    
22
from time import sleep
23
from chirp import chirp_common, directory, memmap
24
from chirp import bitwise, errors, util
25
from textwrap import dedent
26

    
27
# A note about the memmory in these radios
28
# mainly speculation until proven otherwise:
29
#
30
# The '9100' OEM software only manipulates the lower 0x180 bytes on read/write
31
# operations as we know, the file generated by the OEM software IN NOT an exact
32
# eeprom image, it's a crude text file with a pseudo csv format
33

    
34
MEM_SIZE = 0x180 # 384 bytes
35
BLOCK_SIZE = 0x10
36
ACK_CMD = "\x06"
37
MODES = ["FM", "NFM"]
38
SKIP_VALUES = ["S", ""]
39

    
40
# This is a general serial timeout for all serial read functions.
41
# Practice has show that about 0.7 sec will be enough to cover all radios.
42
STIMEOUT = 1
43

    
44
# this var controls the verbosity in the debug and by default it's low (False)
45
# make it True and you will to get a very verbose debug.log
46
debug = True
47

    
48
##### ID strings #####################################################
49

    
50
# BF-T1 handheld
51
BFT1_magic = "\x05PROGRAM"
52
BFT1_ident = "\x20\x42\x46\x39\x31\x30\x30\x53" # " BF9100S"
53

    
54

    
55
def _clean_buffer(radio):
56
    """Cleaning the read serial buffer, hard timeout to survive an infinite
57
    data stream"""
58

    
59
    # touching the serial timeout to optimize the flushing
60
    # restored at the end to the default value
61
    radio.pipe.timeout = 0.1
62
    dump = "1"
63
    datacount = 0
64

    
65
    try:
66
        while len(dump) > 0:
67
            dump = radio.pipe.read(100)
68
            datacount += len(dump)
69
            # hard limit to survive a infinite serial data stream
70
            # 5 times bigger than a normal rx block (20 bytes)
71
            if datacount > 101:
72
                seriale = "Please check your serial port selection."
73
                raise errors.RadioError(seriale)
74

    
75
        # restore the default serial timeout
76
        radio.pipe.timeout = STIMEOUT
77

    
78
    except Exception:
79
        raise errors.RadioError("Unknown error cleaning the serial buffer")
80

    
81

    
82
def _rawrecv(radio, amount = 0):
83
    """Raw read from the radio device"""
84

    
85
    # var to hold the data to return
86
    data = ""
87

    
88
    try:
89
        if amount == 0:
90
            data = radio.pipe.read()
91
        else:
92
            data = radio.pipe.read(amount)
93

    
94
        # DEBUG
95
        if debug is True:
96
            LOG.debug("<== (%d) bytes:\n\n%s" %
97
                      (len(data), util.hexprint(data)))
98

    
99
        # fail if no data is received
100
        if len(data) == 0:
101
            raise errors.RadioError("No data received from radio")
102

    
103
    except:
104
        raise errors.RadioError("Error reading data from radio")
105

    
106
    return data
107

    
108

    
109
def _send(radio, data):
110
    """Send data to the radio device"""
111

    
112
    try:
113
        radio.pipe.write(data)
114

    
115
        # DEBUG
116
        if debug is True:
117
            LOG.debug("==> (%d) bytes:\n\n%s" %
118
                      (len(data), util.hexprint(data)))
119
    except:
120
        raise errors.RadioError("Error sending data to radio")
121

    
122

    
123
def _make_frame(cmd, addr, data=""):
124
    """Pack the info in the header format"""
125
    frame = struct.pack(">BHB", ord(cmd), addr, BLOCK_SIZE)
126

    
127
    # add the data if set
128
    if len(data) != 0:
129
        frame += data
130

    
131
    return frame
132

    
133

    
134
def _recv(radio, addr):
135
    """Get data from the radio"""
136

    
137
    # Get the full 20 bytes at a time
138
    # 4 bytes header + 16 bytes of data (BLOCK_SIZE)
139

    
140
    # get the whole block
141
    block = _rawrecv(radio, BLOCK_SIZE + 4)
142

    
143
    # short answer
144
    if len(block) < (BLOCK_SIZE + 4):
145
        raise errors.RadioError("Wrong block length (short) at 0x%04x" % addr)
146

    
147
    # long answer
148
    if len(block) > (BLOCK_SIZE + 4):
149
        raise errors.RadioError("Wrong block length (long) at 0x%04x" % addr)
150

    
151

    
152
    # header validation
153
    c, a, l = struct.unpack(">cHB", block[0:4])
154
    if c != "W" or a != addr or l != BLOCK_SIZE:
155
        LOG.debug("Invalid header for block 0x%04x:" % addr)
156
        LOG.debug("CMD: %s  ADDR: %04x  SIZE: %02x" % (c, a, l))
157
        raise errors.RadioError("Invalid header for block 0x%04x:" % addr)
158

    
159
    # return the data, 16 bytes of payload
160
    return block[4:]
161

    
162

    
163
def _start_clone_mode(radio, status):
164
    """Put the radio in clone mode, 3 tries"""
165

    
166
    # cleaning the serial buffer
167
    _clean_buffer(radio)
168

    
169
    # prep the data to show in the UI
170
    status.cur = 0
171
    status.msg = "Identifying the radio..."
172
    status.max = 3
173
    radio.status_fn(status)
174

    
175
    try:
176
        for a in range(0, status.max):
177
            # Update the UI
178
            status.cur = a + 1
179
            radio.status_fn(status)
180

    
181
            # send the magic word
182
            _send(radio, radio._magic)
183

    
184
            # Now you get a x06 of ACK if all goes well
185
            ack = _rawrecv(radio, 1)
186

    
187
            if ack == ACK_CMD:
188
                # DEBUG
189
                LOG.info("Magic ACK received")
190
                status.cur = status.max
191
                radio.status_fn(status)
192

    
193
                return True
194

    
195
        return False
196

    
197
    except errors.RadioError:
198
        raise
199
    except Exception, e:
200
        raise errors.RadioError("Error sending Magic to radio:\n%s" % e)
201

    
202

    
203
def _do_ident(radio, status):
204
    """Put the radio in PROGRAM mode & identify it"""
205
    #  set the serial discipline (default)
206
    radio.pipe.baudrate = 9600
207
    radio.pipe.parity = "N"
208
    radio.pipe.bytesize = 8
209
    radio.pipe.stopbits = 1
210
    radio.pipe.timeout = STIMEOUT
211
    radio.pipe.flush()
212

    
213
    # open the radio into program mode
214
    if _start_clone_mode(radio, status) is False:
215
        raise errors.RadioError("Radio did not enter clone mode, wrong model?")
216

    
217
    # Ok, poke it to get the ident string
218
    _send(radio, "\x02")
219
    ident = _rawrecv(radio, len(radio._id))
220

    
221
    # basic check for the ident
222
    if len(ident) != len(radio._id):
223
        raise errors.RadioError("Radio send a odd identification block.")
224

    
225
    # check if ident is OK
226
    if ident != radio._id:
227
        LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
228
        raise errors.RadioError("Radio identification failed.")
229

    
230
    # handshake
231
    _send(radio, ACK_CMD)
232
    ack = _rawrecv(radio, 1)
233

    
234
    #checking handshake
235
    if len(ack) == 1 and ack == ACK_CMD:
236
        # DEBUG
237
        LOG.info("ID ACK received")
238
    else:
239
        LOG.debug("Radio handshake failed.")
240
        raise errors.RadioError("Radio handshake failed.")
241

    
242
    # DEBUG
243
    LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL))
244

    
245
    return True
246

    
247

    
248
def _download(radio):
249
    """Get the memory map"""
250

    
251
    # UI progress
252
    status = chirp_common.Status()
253

    
254
    # put radio in program mode and identify it
255
    _do_ident(radio, status)
256

    
257
    # reset the progress bar in the UI
258
    status.max = MEM_SIZE / BLOCK_SIZE
259
    status.msg = "Cloning from radio..."
260
    status.cur = 0
261
    radio.status_fn(status)
262

    
263
    # cleaning the serial buffer
264
    _clean_buffer(radio)
265

    
266
    # increasing the timeout in the "discovery" process.
267
    radio.pipe.timeout = 3   # 3 seconds.
268

    
269
    data = ""
270
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
271
        # sending the read request
272
        _send(radio, _make_frame("R", addr))
273

    
274
        # read
275
        d = _recv(radio, addr)
276

    
277
        # aggregate the data
278
        data += d
279

    
280
        # UI Update
281
        status.cur = addr / BLOCK_SIZE
282
        status.msg = "Cloning from radio..."
283
        radio.status_fn(status)
284

    
285
    return data
286

    
287

    
288
def _upload(radio):
289
    """Upload procedure"""
290

    
291
    # UI progress
292
    status = chirp_common.Status()
293

    
294
    # put radio in program mode and identify it
295
    _do_ident(radio, status, True)
296

    
297
    # get the data to upload to radio
298
    data = radio.get_mmap()
299

    
300
    # Reset the UI progress
301
    status.max = MEM_SIZE / BLOCK_SIZE
302
    status.cur = 0
303
    status.msg = "Cloning to radio..."
304
    radio.status_fn(status)
305

    
306
    # cleaning the serial buffer
307
    _clean_buffer(radio)
308

    
309
    # the fun start here
310
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
311
        # getting the block of data to send
312
        d = data[addr:addr + BLOCK_SIZE]
313

    
314
        # build the frame to send
315
        frame = _make_frame("W", addr, BLOCK_SIZE, d)
316

    
317
        # send the frame
318
        _send(radio, frame)
319

    
320
        # receiving the response
321
        ack = _rawrecv(radio, 1)
322

    
323
        # basic check
324
        if len(ack) != 1:
325
            raise errors.RadioError("No ACK when writing block 0x%04x" % addr)
326

    
327
        if ack != ACK_CMD:
328
            raise errors.RadioError("Bad ACK writing block 0x%04x:" % addr)
329

    
330
         # UI Update
331
        status.cur = addr / TX_BLOCK_SIZE
332
        status.msg = "Cloning to radio..."
333
        radio.status_fn(status)
334

    
335

    
336
def _split(rf, f1, f2):
337
    """Returns False if the two freqs are in the same band (no split)
338
    or True otherwise"""
339

    
340
    # determine if the two freqs are in the same band
341
    for low, high in rf.valid_bands:
342
        if f1 >= low and f1 <= high and f2 >= low and f2 <= high:
343
            # if the two freqs are on the same Band this is not a split
344
            return False
345

    
346
    # if you get here is because the freq pairs are split
347
    return True
348

    
349

    
350
#~ def model_match(cls, data):
351
    #~ """Match the opened/downloaded image to the correct version"""
352
    #~ # by now just size match
353

    
354
    #~ return False
355

    
356

    
357
MEM_FORMAT = """
358
#seekto 0x0000;
359
struct {
360
  u8 unknown0;
361
  lbcd rxfreq[3];
362
  u8 unknown1[4];
363
  lbcd txfreq[3];
364
  u8 unknown2[5];
365
} memory[20];
366
"""
367

    
368

    
369
@directory.register
370
class BFT1(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio):
371
    """Baofeng BT-F1 radio & possibly alike radios"""
372
    VENDOR = "Baofeng"
373
    MODEL = "BF-T1"
374
    _power_levels = [chirp_common.PowerLevel("High", watts=5),
375
                     chirp_common.PowerLevel("Low", watts=1)]
376
    _vhf_range = (136000000, 174000000)
377
    _uhf_range = (400000000, 470000000)
378
    _upper = 19
379
    _magic = BFT1_magic
380
    _id = BFT1_ident
381

    
382
    @classmethod
383
    def get_prompts(cls):
384
        rp = chirp_common.RadioPrompts()
385
        rp.experimental = \
386
            ('This driver is experimental.\n'
387
             '\n'
388
             'Please keep a copy of your memories with the original software '
389
             'if you treasure them, this driver is new and may contain'
390
             ' bugs.\n'
391
             '\n'
392
             )
393
        rp.pre_download = _(dedent("""\
394
            Follow these instructions to download your info:
395

    
396
            1 - Turn off your radio
397
            2 - Connect your interface cable
398
            3 - Turn on your radio
399
            4 - Do the download of your radio data
400

    
401
            """))
402
        rp.pre_upload = _(dedent("""\
403
            Follow these instructions to upload your info:
404

    
405
            1 - Turn off your radio
406
            2 - Connect your interface cable
407
            3 - Turn on your radio
408
            4 - Do the upload of your radio data
409

    
410
            """))
411
        return rp
412

    
413
    def get_features(self):
414
        """Get the radio's features"""
415

    
416
        # we will use the following var as global
417
        global POWER_LEVELS
418

    
419
        rf = chirp_common.RadioFeatures()
420
        #~ rf.has_settings = True
421
        #~ rf.has_bank = False
422
        #~ rf.has_tuning_step = False
423
        #~ rf.can_odd_split = True
424
        #~ rf.has_name = True
425
        rf.has_offset = True
426
        rf.has_mode = True
427
        rf.valid_modes = MODES
428
        #~ rf.has_dtcs = True
429
        #~ rf.has_rx_dtcs = True
430
        #~ rf.has_dtcs_polarity = True
431
        #~ rf.has_ctone = True
432
        #~ rf.has_cross = True
433
        #~ rf.valid_characters = VALID_CHARS
434
        #~ rf.valid_name_length = self.NAME_LENGTH
435
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
436
        #~ rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
437
        #~ rf.valid_cross_modes = [
438
            #~ "Tone->Tone",
439
            #~ "DTCS->",
440
            #~ "->DTCS",
441
            #~ "Tone->DTCS",
442
            #~ "DTCS->Tone",
443
            #~ "->Tone",
444
            #~ "DTCS->DTCS"]
445
        rf.valid_skips = SKIP_VALUES
446
        #~ rf.valid_dtcs_codes = DTCS
447
        rf.memory_bounds = (0, self._upper)
448

    
449
        # power levels
450
        POWER_LEVELS = self._power_levels
451
        rf.valid_power_levels = POWER_LEVELS
452

    
453
        # normal dual bands
454
        rf.valid_bands = [self._vhf_range, self._uhf_range]
455

    
456
        return rf
457

    
458
    def process_mmap(self):
459
        """Process the mem map into the mem object"""
460

    
461
        # Get it
462
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
463

    
464
    def sync_in(self):
465
        """Download from radio"""
466
        data = _download(self)
467
        self._mmap = memmap.MemoryMap(data)
468
        self.process_mmap()
469

    
470
    def sync_out(self):
471
        """Upload to radio"""
472

    
473
        #~ try:
474
            #~ _upload(self)
475
        #~ except errors.RadioError:
476
            #~ raise
477
        #~ except Exception, e:
478
            #~ raise errors.RadioError("Error: %s" % e)
479

    
480
        # upload disabled by now
481
        raise errors.RadioError("Error: This is a dev driver, no upload yet.")
482

    
483
    def get_raw_memory(self, number):
484
        return repr(self._memobj.memory[number])
485

    
486
    def get_memory(self, number):
487
        """Get the mem representation from the radio image"""
488
        _mem = self._memobj.memory[number]
489

    
490
        # Create a high-level memory object to return to the UI
491
        mem = chirp_common.Memory()
492

    
493
        # Memory number
494
        mem.number = number
495

    
496
        if _mem.get_raw()[0] == "\xFF":
497
            mem.empty = True
498
            return mem
499

    
500
        # Freq and offset
501
        mem.freq = int(_mem.rxfreq) * 1000
502
        # tx freq can be blank
503
        if _mem.get_raw()[8] == "\xFF":
504
            # TX freq not set
505
            mem.offset = 0
506
            mem.duplex = "off"
507
        else:
508
            # TX freq set
509
            txfreq = int(_mem.txfreq) * 1000
510
            offset = txfreq - mem.freq
511
            if offset != 0:
512
                if _split(self.get_features(), mem.freq, txfreq):
513
                    mem.duplex = "split"
514
                    mem.offset = txfreq
515
                elif offset < 0:
516
                    mem.offset = abs(offset)
517
                    mem.duplex = "-"
518
                elif offset > 0:
519
                    mem.offset = offset
520
                    mem.duplex = "+"
521
            else:
522
                mem.offset = 0
523

    
524
        #~ # power
525
        #~ mem.power = POWER_LEVELS[int(_mem.power)]
526

    
527
        #~ # wide/narrow
528
        #~ mem.mode = MODES[int(_mem.wide)]
529

    
530
        #~ # skip
531
        #~ mem.skip = SKIP_VALUES[_mem.add]
532

    
533
        #~ # tone data
534
        #~ rxtone = txtone = None
535
        #~ txtone = self._decode_tone(_mem.txtone)
536
        #~ rxtone = self._decode_tone(_mem.rxtone)
537
        #~ chirp_common.split_tone_decode(mem, txtone, rxtone)
538

    
539

    
540
        return mem
541

    
542
    def set_memory(self, mem):
543
        """Set the memory data in the eeprom img from the UI"""
544
        # get the eprom representation of this channel
545
        _mem = self._memobj.memory[mem.number]
546
        _names = self._memobj.names[mem.number]
547

    
548
        # if empty memmory
549
        if mem.empty:
550
            # the channel itself
551
            _mem.set_raw("\xFF" * 16)
552

    
553
        # frequency
554
        _mem.rxfreq = mem.freq / 1000
555

    
556
        # duplex
557
        if mem.duplex == "+":
558
            _mem.txfreq = (mem.freq + mem.offset) / 1000
559
        elif mem.duplex == "-":
560
            _mem.txfreq = (mem.freq - mem.offset) / 1000
561
        elif mem.duplex == "off":
562
            for i in _mem.txfreq:
563
                i.set_raw("\xFF")
564
        elif mem.duplex == "split":
565
            _mem.txfreq = mem.offset / 1000
566
        else:
567
            _mem.txfreq = mem.freq / 1000
568

    
569
        #~ # tone data
570
        #~ ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
571
            #~ chirp_common.split_tone_encode(mem)
572
        #~ self._encode_tone(_mem.txtone, txmode, txtone, txpol)
573
        #~ self._encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)
574

    
575
        return mem
576

    
577
    @classmethod
578
    def match_model(cls, filedata, filename):
579
        match_size = False
580
        #~ match_model = False
581

    
582
        LOG.debug("len file/mem %i/%i" % (len(filedata), MEM_SIZE))
583

    
584
        # testing the file data size
585
        if len(filedata) == MEM_SIZE:
586
            match_size = True
587

    
588
            # DEBUG
589
            if debug is True:
590
                LOG.debug("BF-T1 matched!")
591

    
592

    
593
        # testing the firmware model fingerprint
594
        #~ match_model = model_match(cls, filedata)
595

    
596
        if match_size: # and match_model:
597
            return True
598
        else:
599
            return False
(22-22/77)