]> sigrok.org Git - sigrok-util.git/blob - firmware/hantek-dso-extract.py
hantek-dso-extract: use 2xxx or 5xxx for firmware blobs
[sigrok-util.git] / firmware / hantek-dso-extract.py
1 #!/usr/bin/python3
2 ##
3 ## This file is part of the sigrok project.
4 ##
5 ## Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
6 ##
7 ## This program is free software; you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation; either version 3 of the License, or
10 ## (at your option) any later version.
11 ##
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 ## GNU General Public License for more details.
16 ##
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program; if not, see <http://www.gnu.org/licenses/>.
19 ##
20
21 import sys
22 import os
23 import re
24 import struct
25 from array import array
26
27 import parsepe
28
29
30 def find_model(filename):
31         filename = os.path.split(filename)[-1]
32         m = re.search('^dso([25])[a-z0-9]+1.sys$', filename, re.I)
33         if m:
34                 model = m.group(1) + 'xxx'
35         else:
36                 model = 'unknown'
37
38         return model
39
40
41 def unsparse(data):
42         p = 0
43         maxaddr = 0
44         blob = array('B', [0] * 0x4000)
45         while p <= len(data) and data[p+4] == 0:
46                 num_bytes = struct.unpack("<H", data[p:p+2])[0]
47                 address = struct.unpack("<H", data[p+2:p+4])[0]
48                 chunk = array('B')
49                 chunk.frombytes(data[p+5:p+5+num_bytes])
50                 p += 22
51
52                 if address > 0x4000:
53                         # the FX2 only has 16K RAM. other writes are to registers
54                         # in the 0xe000 region, skip those
55                         continue
56
57                 blob[address:address+num_bytes] = chunk
58
59                 if address + num_bytes > maxaddr:
60                         maxaddr = address + num_bytes
61
62         return blob[:maxaddr].tostring()
63
64
65 def usage():
66         print("hantek-dso-extract.py <driverfile>")
67         sys.exit()
68
69
70 #
71 # main
72 #
73
74 if len(sys.argv) != 2:
75         usage()
76
77 try:
78         filename = sys.argv[1]
79         binihx = parsepe.extract_symbol(filename, '_firmware')
80         if binihx is None:
81                 raise Exception("no firmware found")
82         blob = unsparse(binihx)
83         outfile = 'hantek-dso-' + find_model(filename) + '.fw'
84         open(outfile, 'wb').write(blob)
85         print("saved %d bytes to %s" % (len(blob), outfile))
86 except Exception as e:
87         print("Error: %s" % str(e))
88
89
90