forked from imoyer/gestalt
-
Notifications
You must be signed in to change notification settings - Fork 10
/
utilities.py
242 lines (197 loc) · 7.01 KB
/
utilities.py
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import math
import ast
import datetime
def notice(source = None, message = ""):
''' Sends a notice to the user.
For now, this just prints to the screen. But eventually, could re-route via a web interface.'''
#check for name attribute
if hasattr(source, 'name'):
name = getattr(source, 'name')
if name:
print name + ": " + str(message)
elif hasattr(source, 'owner'):
owner = getattr(source, 'owner')
if owner:
notice(source.owner, message)
else:
print str(source) + ": " + str(message)
else:
print str(source) + ": " + str(message)
else:
if hasattr(source, 'owner'):
owner = getattr(source, 'owner')
if owner:
notice(source.owner, message)
else:
print str(source) + ": " + str(message)
else:
print str(source) + ": " + str(message)
class persistenceManager(object):
'''Handles interacting with persistence files.'''
def __init__(self, filename = None, namespace = None):
self.filename = filename
self.namespace = namespace
def __call__(self):
if self.filename: return self
else: return False
def get(self, name):
persistenceDict = self.readPersistenceDictionary()
lookup = self.namespace + '.' + name
if lookup in persistenceDict:
return persistenceDict[self.namespace + '.' + name]
else:
return None
def set(self, name, value):
persistenceDict = self.readPersistenceDictionary()
persistenceDict.update({self.namespace + '.' + name: value})
self.writePersistenceDictionary(persistenceDict)
def readPersistenceDictionary(self):
try:
fileObject = open(self.filename, 'rU')
persistenceDict = ast.literal_eval(fileObject.read())
fileObject.close()
return persistenceDict
except IOError:
return {}
def writePersistenceDictionary(self, persistenceDict):
fileObject = open(self.filename, 'w')
fileObject.write("# This Gestalt persistence file was auto-generated @ " + str(datetime.datetime.now()) + "\n")
fileObject.write("{\n")
for key in persistenceDict:
fileObject.write("'" + key + "'" + ":" + str(persistenceDict[key]) + ",\n")
fileObject.write("}")
fileObject.close()
def intToBytes(integer, numbytes):
bytes = range(numbytes)
for i in bytes:
bytes[i] = integer%256
integer -= integer%256
integer = integer//256
if integer>0: print "ERROR in PACKET COMPOSER: BYTE OVERFLOW"
return bytes
def bytesToInt(bytes):
integer = 0
order = 0
for i in bytes:
integer += i*(256**order)
order += 1
return integer
def listToString(numList):
strList = [chr(x) for x in numList]
return ''.join(strList)
def vectorAbs(vector):
output = range(len(vector))
for i in output:
output[i] = abs(vector[i])
return output
def vectorInt(vector):
output = range(len(vector))
for i in output:
output[i] = int(vector[i])
return output
def vectorMultiply(vector1, vector2):
if len(vector1) != len(vector2):
print "ERROR in vectorMultiply: vectors have dissimilar lengths"
output = range(len(vector1))
for i in output:
output[i] = vector1[i]*vector2[i]
return output
def vectorDivide(vector1, vector2):
if len(vector1) != len(vector2):
print "ERROR in vectorDivide: vectors have dissimilar lengths"
output = range(len(vector1))
for i in output:
output[i] = vector1[i]/float(vector2[i])
return output
def vectorSign(vector):
output = range(len(vector))
for i in output:
if vector[i] > 0: output[i] = 1
if vector[i] < 0: output[i] = -1
if vector[i] == 0: output[i] = 0
return output
def vectorMCUSign(vector):
output = range(len(vector))
for i in output:
if vector[i] > 0: output[i] = 1
if vector[i] <= 0: output[i] = 0
return output
def vectorLength(vector):
sum = 0.0
for i in vector:
sum += i**2 #squares power
return math.sqrt(sum)
def vectorMax(vector):
vMax = 0.0
for i in vector:
if i > vMax: vMax = i
return vMax
class intelHexParser(object):
'''Parses Intel Hex Files for Bootloading and Memory Programming.'''
def __init__(self):
self.filename = None
self.hexFile = None
self.resetParser()
def openHexFile(self, filename = None):
if filename != None:
self.hexFile = open(filename, 'r')
return self.hexFile
else:
print "intelHexParser: please provide a filename!"
return False
def resetParser(self):
self.baseByteLocation = 0 #always initialize at location 0, this can be changed by the hex file during reading
self.parsedFile = []
self.codeStart = 0
self.terminated = False #gets set when end of file record is reached
def loadHexFile(self):
parseVectors = {0:self.processDataRecord, 1: self.processEndOfFileRecord, 2: self.processExtendedSegmentAddressRecord,
3:self.processStartSegmentAddressRecord, 4: self.processExtendedLinearAddressRecord, 5: self.processStartLinearAddressRecord}
for index, record in enumerate(self.hexFile): #enumerate over lines in hex file
integerRecord = self.integerRecord(self.recordParser(record))
parseVectors[integerRecord['RECTYP']](integerRecord)
# print self.parsedFile
self.checkAddressContinuity()
def returnPages(self, pageSize):
numPages = int(math.ceil(len(self.parsedFile)/float(pageSize))) #number of pages
pages = [self.parsedFile[i*pageSize:(i+1)*pageSize] for i in range(numPages)] #slice parsed data into pages of size pageSize
#fill in last page
lastPage = pages[-1]
delta = pageSize - len(lastPage)
lastAddress = lastPage[-1][0] #address of last entry in last page
makeUp = [[lastAddress+i+1, 0] for i in range(delta)]
pages[-1] += makeUp #fill last page
return pages
def recordParser(self, record):
record = record.rstrip()
length = len(record)
return {'RECLEN':record[1:3], 'OFFSET':record[3:7], 'RECTYP':record[7:9], 'DATA':record[9:length-2], 'CHECKSUM':record[length-2: length]}
def integerRecord(self, record):
return {'RECLEN':int(record['RECLEN'],16), 'OFFSET':int(record['OFFSET'], 16), 'RECTYP':int(record['RECTYP'],16),
'CHECKSUM': int(record['CHECKSUM'], 16), 'DATA': self.dataList(record['DATA'])}
def dataList(self, data):
return [int(data[i:i+2], 16) for i in range(0, len(data), 2)]
def processDataRecord(self, record):
codeLocation = record['OFFSET'] + self.baseByteLocation
for index, byte in enumerate(record['DATA']):
self.parsedFile +=[[codeLocation + index, byte]]
def processEndOfFileRecord(self, record):
self.terminated = True
def processExtendedSegmentAddressRecord(self, record):
self.baseByteLocation = (record['DATA'][0]*256 + record['DATA'][1])*16 #value is shifted by four bits
def processStartSegmentAddressRecord(self, record):
print "Start Segment Address Record Encountered and Ignored"
def processExtendedLinearAddressRecord(self, record):
print "Extended Linear Address Record Encountered and Ignored"
def processStartLinearAddressRecord(self, record):
print "Start Linear Address Record Encountered and Ignored"
def checkAddressContinuity(self):
baseAddress = self.parsedFile[0][0] #inital address entry
for byte in self.parsedFile[1::]:
if byte[0] == baseAddress + 1:
baseAddress += 1
continue
else:
print "CONTINUITY CHECK FAILED"
return False
print "CONTINUITY CHECK PASSED"