summaryrefslogtreecommitdiffstats
path: root/libtoprammer/bitfile.py
blob: 6f795029cc990222bb33a8f4a6dabc31848a1c81 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""
#    *.BIT file parser
#
#    Copyright (c) 2009-2011 Michael Buesch <m@bues.ch>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""

import sys
try:
	import pkg_resources
except ImportError:
	print "Failed to import the 'pkg_resources' Python module."
	print "'pkg_resources' is part of the Python 'setuptools' package."
	print "On Debian Linux run:  apt-get install python-pkg-resources"
	sys.exit(1)

from util import *


class BitfileException(Exception): pass

class Bitfile:
	# Magic header
	MAGIC		= "\x00\x09\x0f\xf0\x0f\xf0\x0f\xf0\x0f\xf0\x00\x00\x01"
	# Field IDs
	FIELD_SRCFILE	= 0x61
	FIELD_FPGA	= 0x62
	FIELD_DATE	= 0x63
	FIELD_TIME	= 0x64
	FIELD_PAYLOAD	= 0x65

	def __init__(self):
		self.filename = ""
		self.srcfile = ""
		self.fpga = ""
		self.date = ""
		self.time = ""
		self.payload = ""

	def getFilename(self):
		return self.filename

	def getSrcFile(self):
		return self.srcfile

	def getFPGA(self):
		return self.fpga

	def getDate(self):
		return self.date

	def getTime(self):
		return self.time

	def getPayload(self):
		return self.payload

	def parseFile(self, filename):
		try:
			fd = open(filename, "rb")
			data = fd.read()
			fd.close()
		except (IOError), e:
			raise BitfileException("Failed to read \"" + filename + "\": " + e.strerror)
		self.filename = filename
		self.__parse(data)

	def __parse(self, data):
		try:
			magic = data[0:len(self.MAGIC)]
			if magic != self.MAGIC:
				raise BitfileException("Invalid magic header")
			i = len(self.MAGIC)
			while i < len(data):
				i += self.__parseNextField(data, i)
		except (IndexError), e:
			raise BitfileException("Failed to parse BIT file")
		if not self.fpga:
			raise BitfileException("No FPGA ID string found")
		if not self.payload:
			raise BitfileException("No payload found")

	def __parseNextField(self, data, i):
		fieldId = byte2int(data[i + 0])
		if (fieldId == self.FIELD_SRCFILE):
			data = self.__parse16bitField(data, i + 1)
			self.srcfile = data.decode("ASCII").strip().strip("\x00")
			return len(data) + 3
		if (fieldId == self.FIELD_FPGA):
			data = self.__parse16bitField(data, i + 1)
			self.fpga = data.decode("ASCII").strip().strip("\x00")
			return len(data) + 3
		if (fieldId == self.FIELD_DATE):
			data = self.__parse16bitField(data, i + 1)
			self.date = data.decode("ASCII").strip().strip("\x00")
			return len(data) + 3
		if (fieldId == self.FIELD_TIME):
			data = self.__parse16bitField(data, i + 1)
			self.time = data.decode("ASCII").strip().strip("\x00")
			return len(data) + 3
		if (fieldId == self.FIELD_PAYLOAD):
			self.payload = self.__parse32bitField(data, i + 1)
			return len(self.payload) + 5
		raise BitfileException("Found unknown data field 0x%02X" % fieldId)

	def __parse16bitField(self, data, i):
		fieldLen = (byte2int(data[i + 0]) << 8) | byte2int(data[i + 1])
		return data[i + 2 : i + 2 + fieldLen]

	def __parse32bitField(self, data, i):
		fieldLen = (byte2int(data[i + 0]) << 24) | (byte2int(data[i + 1]) << 16) |\
			   (byte2int(data[i + 2]) << 8) | byte2int(data[i + 3])
		return data[i + 4 : i + 4 + fieldLen]

def __probeFile(fullpath):
	try:
		open(fullpath, "rb").close()
	except (IOError), e:
		return False
	return True

def bitfileFind(filename):
	"Search some standard paths for a bitfile"
	if not filename.endswith(".bit"):
		filename += ".bit"
	if filename.startswith("/"):
		if __probeFile(filename):
			return filename
	paths = ( ".", "./libtoprammer/fpga/bin", )
	for path in paths:
		fullpath = path + "/" + filename
		if __probeFile(fullpath):
			return fullpath
	fullpath = pkg_resources.resource_filename("libtoprammer",
						   "fpga/bin/" + filename)
	if __probeFile(fullpath):
		return fullpath
	return None

if __name__ == "__main__":
	if len(sys.argv) != 3:
		print "Usage: %s file.bit ACTION"
		print ""
		print "Actions:"
		print " GETSRC       - print the src-file field to stdout"
		print " GETFPGA      - print the fpga-type field to stdout"
		print " GETDATE      - print the date field to stdout"
		print " GETTIME      - print the time field to stdout"
		print " GETPAYLOAD   - print the payload field to stdout"
		sys.exit(1)
	filename = sys.argv[1]
	action = sys.argv[2].upper()

	b = Bitfile()
	b.parseFile(filename)
	if action == "GETSRC":
		sys.stdout.write(b.getSrcFile())
	if action == "GETFPGA":
		sys.stdout.write(b.getFPGA())
	if action == "GETDATE":
		sys.stdout.write(b.getDate())
	if action == "GETTIME":
		sys.stdout.write(b.getTime())
	if action == "GETPAYLOAD":
		sys.stdout.write(b.getPayload())
bues.ch cgit interface