Project

General

Profile

New Model #4933 » bf-t1_hwh3.py

a version of the driver Pavel posted 2 hours ago with hwh changes included - Harold Hankins, 12/12/2017 03:57 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 = ["NFM", "FM"]
38
SKIP_VALUES = ["S", ""]
39

    
40
# This is a general serial timeout for all serial read functions.
41
# Practice has show that about 0.07 sec will be enough to cover all radios.
42
STIMEOUT = 0.07
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

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

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

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

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

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

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

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

    
246
    return True
247

    
248

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

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

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

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

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

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

    
272
        # read
273
        d = _recv(radio, addr)
274

    
275
        # aggregate the data
276
        data += d
277

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

    
283
    # close comms with the radio
284
    _send(radio, "\x62")
285
    # DEBUG
286
    LOG.info("Close comms cmd sent, radio must reboot now.")
287

    
288
    return data
289

    
290

    
291
def _upload(radio):
292
    """Upload procedure"""
293

    
294
    # UI progress
295
    status = chirp_common.Status()
296

    
297
    # put radio in program mode and identify it
298
    _do_ident(radio, status)
299

    
300
    # get the data to upload to radio
301
    data = radio.get_mmap()
302

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

    
309
    # cleaning the serial buffer
310
    _clean_buffer(radio)
311

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

    
317
        # build the frame to send
318
        frame = _make_frame("W", addr, d)
319

    
320
        # send the frame
321
        _send(radio, frame)
322

    
323
        # receiving the response
324
        ack = _rawrecv(radio, 1)
325

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

    
330
        if ack != ACK_CMD:
331
            raise errors.RadioError("Bad ACK writing block 0x%04x:" % addr)
332

    
333
         # UI Update
334
        status.cur = addr / BLOCK_SIZE
335
        status.msg = "Cloning to radio..."
336
        radio.status_fn(status)
337

    
338
    # close comms with the radio
339
    _send(radio, "\x62")
340
    # DEBUG
341
    LOG.info("Close comms cmd sent, radio must reboot now.")
342

    
343

    
344
def _split(rf, f1, f2):
345
    """Returns False if the two freqs are in the same band (no split)
346
    or True otherwise"""
347

    
348
    # determine if the two freqs are in the same band
349
    for low, high in rf.valid_bands:
350
        if f1 >= low and f1 <= high and f2 >= low and f2 <= high:
351
            # if the two freqs are on the same Band this is not a split
352
            return False
353

    
354
    # if you get here is because the freq pairs are split
355
    return True
356

    
357

    
358
#~ def model_match(cls, data):
359
    #~ """Match the opened/downloaded image to the correct version"""
360
    #~ # by now just size match
361

    
362
    #~ return False
363

    
364
# memory[0] is Emergency Channel
365

    
366

    
367
MEM_FORMAT = """
368
#seekto 0x0000;         // normal 1-20 mem channels
369
struct {
370
  lbcd rxfreq[4];       // rx freq.
371
  u8 rxtone;            // x00 = none
372
                        // x01 - x32 = index of the analog tones
373
                        // x33 - x9b = index of Digital tones
374
                        // Digital tone polarity is handled below
375
  lbcd txoffset[4];     // the difference against RX
376
                        // pending to find the offset polarity in settings
377
  u8 txtone;            // Idem to rxtone
378
  u8 unA:1,         //
379
     wide:1,        // 1 = Wide, 0 = narrow
380
     unC:1,         //
381
     unD:1,         //
382
     unE:1,         //
383
     unF:1,         //
384
     offplus:1,     // TX = RX + offset
385
     offminus:1;    // TX = RX - offset
386
  u8 empty[5];
387
} memory[21];
388

    
389
#seekto 0x0150;     // Unknown data... settings?
390
struct {
391
  u8 unknown0[16];  // settings goes HERE....
392
} settings[2];
393

    
394
#seekto 0x0170;     // Relay CH: same structure of memory ?
395
struct {
396
  u8 unknown1[16];
397
} relaych[1];
398

    
399

    
400
"""
401

    
402

    
403
@directory.register
404
class BFT1(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio):
405
    """Baofeng BT-F1 radio & possibly alike radios"""
406
    VENDOR = "Baofeng"
407
    MODEL = "BF-T1"
408
    _power_levels = [chirp_common.PowerLevel("High", watts=5),
409
                     chirp_common.PowerLevel("Low", watts=1)]
410
    _vhf_range = (136000000, 174000000)
411
    _uhf_range = (400000000, 470000000)
412
    _upper = 20
413
    _magic = BFT1_magic
414
    _id = BFT1_ident
415

    
416
    @classmethod
417
    def get_prompts(cls):
418
        rp = chirp_common.RadioPrompts()
419
        rp.experimental = \
420
            ('This driver is experimental.\n'
421
             '\n'
422
             'Please keep a copy of your memories with the original software '
423
             'if you treasure them, this driver is new and may contain'
424
             ' bugs.\n'
425
             '\n'
426
             )
427
        rp.pre_download = _(dedent("""\
428
            Follow these instructions to download your info:
429

    
430
            1 - Turn off your radio
431
            2 - Connect your interface cable
432
            3 - Turn on your radio
433
            4 - Do the download of your radio data
434

    
435
            """))
436
        rp.pre_upload = _(dedent("""\
437
            Follow these instructions to upload your info:
438

    
439
            1 - Turn off your radio
440
            2 - Connect your interface cable
441
            3 - Turn on your radio
442
            4 - Do the upload of your radio data
443

    
444
            """))
445
        return rp
446

    
447
    def get_features(self):
448
        """Get the radio's features"""
449

    
450
        # we will use the following var as global
451
        global POWER_LEVELS
452

    
453
        rf = chirp_common.RadioFeatures()
454
        #~ rf.has_settings = True
455
        #~ rf.has_bank = False
456
        #~ rf.has_tuning_step = False
457
        #~ rf.can_odd_split = True
458
        #~ rf.has_name = True
459
        rf.has_offset = True
460
        rf.has_mode = True
461
        rf.valid_modes = MODES
462
        #~ rf.has_dtcs = True
463
        #~ rf.has_rx_dtcs = True
464
        #~ rf.has_dtcs_polarity = True
465
        #~ rf.has_ctone = True
466
        #~ rf.has_cross = True
467
        #~ rf.valid_characters = VALID_CHARS
468
        #~ rf.valid_name_length = self.NAME_LENGTH
469
        rf.valid_duplexes = ["", "-", "+"] # , "split"]
470
        #~ rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
471
        #~ rf.valid_cross_modes = [
472
            #~ "Tone->Tone",
473
            #~ "DTCS->",
474
            #~ "->DTCS",
475
            #~ "Tone->DTCS",
476
            #~ "DTCS->Tone",
477
            #~ "->Tone",
478
            #~ "DTCS->DTCS"]
479
        rf.valid_skips = SKIP_VALUES
480
        #~ rf.valid_dtcs_codes = DTCS
481
        rf.memory_bounds = (0, self._upper)
482

    
483
        # power levels
484
        POWER_LEVELS = self._power_levels
485
        rf.valid_power_levels = POWER_LEVELS
486

    
487
        # normal dual bands
488
        rf.valid_bands = [self._vhf_range, self._uhf_range]
489

    
490
        return rf
491

    
492
    def process_mmap(self):
493
        """Process the mem map into the mem object"""
494

    
495
        # Get it
496
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
497

    
498
    def sync_in(self):
499
        """Download from radio"""
500
        data = _download(self)
501
        self._mmap = memmap.MemoryMap(data)
502
        self.process_mmap()
503

    
504
    def sync_out(self):
505
        """Upload to radio"""
506

    
507
        try:
508
            _upload(self)
509
        except errors.RadioError:
510
            raise
511
        except Exception, e:
512
            raise errors.RadioError("Error: %s" % e)
513

    
514
    def get_raw_memory(self, number):
515
        return repr(self._memobj.memory[number])
516

    
517
    def get_memory(self, number):
518
        """Get the mem representation from the radio image"""
519
        _mem = self._memobj.memory[number]
520

    
521
        # Create a high-level memory object to return to the UI
522
        mem = chirp_common.Memory()
523

    
524
        # Memory number
525
        mem.number = number
526

    
527
        if _mem.get_raw()[0] == "\xFF":
528
            mem.empty = True
529
            return mem
530

    
531
        # Freq and offset
532
        mem.freq = int(_mem.rxfreq) * 10
533

    
534
        # TX freq (Stored as a difference)
535
        mem.offset = int(_mem.txoffset) * 10
536
        mem.duplex = ""
537

    
538
        # must work out the polarity
539
        if mem.offset != 0:
540
            if _mem.offminus == 1:
541
                mem.duplex = "-"
542
                #  tx below RX
543

    
544
            if _mem.offplus == 1:
545
                #  tx above RX
546
                mem.duplex = "+"
547

    
548
            # I need to work this out with a real split example
549
            ####################################################
550
            #~ # find if there are a split freq (min diff is 400 - 174)
551
            #~ absv = abs(mem.freq - mem.offset)
552
            #~ if absv < 225000000:
553
                #~ mem.duplex = "split"
554
                #~ LOG.info("absolute difference is: %i" % absv)
555

    
556

    
557
        # wide/narrow
558
        mem.mode = MODES[int(_mem.wide)]
559

    
560
        #~ # skip
561
        #~ mem.skip = SKIP_VALUES[_mem.add]
562

    
563
        #~ # tone data
564
        #~ rxtone = txtone = None
565
        #~ txtone = self._decode_tone(_mem.txtone)
566
        #~ rxtone = self._decode_tone(_mem.rxtone)
567
        #~ chirp_common.split_tone_decode(mem, txtone, rxtone)
568

    
569

    
570
        return mem
571

    
572
    def set_memory(self, mem):
573
        """Set the memory data in the eeprom img from the UI"""
574
        # get the eprom representation of this channel
575
        _mem = self._memobj.memory[mem.number]
576

    
577
        # if empty memmory
578
        if mem.empty:
579
            # the channel itself
580
            _mem.set_raw("\xFF" * 16)
581
            # return it
582
            return mem
583

    
584
        # frequency
585
        _mem.rxfreq = mem.freq / 10
586

    
587
        # duplex/ offset Offset is an absolute value
588
        _mem.txoffset = mem.offset / 10
589

    
590
        # must work out the polarity
591
        if mem.duplex == "":
592
            _mem.offplus = 0
593
            _mem.offminus = 0
594
        elif mem.duplex == "+":
595
            _mem.offplus = 1
596
            _mem.offminus = 0
597
        elif mem.duplex == "-":
598
            _mem.offplus = 0
599
            _mem.offminus = 1
600

    
601
        # test this with a real split example.
602
        #~ elif mem.duplex == "split":
603
            #~ _mem.txfreq = mem.offset / 1000
604

    
605
        # wide/narrow
606
        _mem.wide = MODES.index(mem.mode)
607

    
608
        #~ # tone data
609
        #~ ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
610
            #~ chirp_common.split_tone_encode(mem)
611
        #~ self._encode_tone(_mem.txtone, txmode, txtone, txpol)
612
        #~ self._encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)
613

    
614
        return mem
615

    
616
    @classmethod
617
    def match_model(cls, filedata, filename):
618
        match_size = False
619
        #~ match_model = False
620

    
621
        LOG.debug("len file/mem %i/%i" % (len(filedata), MEM_SIZE))
622

    
623
        # testing the file data size
624
        if len(filedata) == MEM_SIZE:
625
            match_size = True
626

    
627
            # DEBUG
628
            if debug is True:
629
                LOG.debug("BF-T1 matched!")
630

    
631

    
632
        # testing the firmware model fingerprint
633
        #~ match_model = model_match(cls, filedata)
634

    
635
        if match_size: # and match_model:
636
            return True
637
        else:
638
            return False
(53-53/77)