Project

General

Profile

New Model #4933 » bf-t1.py

Latest version, Channels freq + offset + wide + upload. - Pavel Milanes, 12/12/2017 01:29 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
    # 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
    data = ""
267
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
268
        # sending the read request
269
        _send(radio, _make_frame("R", addr))
270

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

    
274
        # aggregate the data
275
        data += d
276

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

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

    
287
    return data
288

    
289

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
342

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

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

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

    
356

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

    
361
    #~ return False
362

    
363
# memory[0] is Emergency Channel
364

    
365

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

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

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

    
398

    
399
"""
400

    
401

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

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

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

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

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

    
443
            """))
444
        return rp
445

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

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

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

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

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

    
489
        return rf
490

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

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

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

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

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

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

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

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

    
523
        # Memory number
524
        mem.number = number
525

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

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

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

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

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

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

    
555

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

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

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

    
568

    
569
        return mem
570

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

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

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

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

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

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

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

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

    
613
        return mem
614

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

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

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

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

    
630

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

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