-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathegdsimulator_http.py
324 lines (263 loc) · 9.86 KB
/
egdsimulator_http.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import cgi
import sys
import getopt
try:
from BaseHTTPServer import BaseHTTPRequestHandler
import SocketServer
except:
from http.server import BaseHTTPRequestHandler
import socketserver as SocketServer
import egdmodel
import MKVIe
import Custom
import egdsimulator
class MyHandler(BaseHTTPRequestHandler):
def buildTag(self, tag):
return """<tr class="tag"><td>{}</td><td>{}</td><td>{}</td></tr>""".format(
tag.offsetbyte+"."+tag.offsetbit,
tag.type,
tag.lastvalue if tag.lastvalue != None else "")
def buildExchange(self, exchange):
print(exchange.dump())
return """
<tr class="exchange">
<td>Exchange {}</td>
<td>Period {} (ms)</td>
<td>Msg {}</td>
<td>{} tags</td>
<td class="toggle"><label></label></td>
</tr>
{}
""".format(
exchange.exchangenumber, exchange.period,
exchange.lasttimestamp if exchange.lasttimestamp != None else "",
len(exchange.tags),
"".join(list(map(lambda t: self.buildTag(t), exchange.sortedTags()))))
def buildProducer(self, producer):
return """
<tr class="producer"><td>Producer {}</td></tr>
{}
""".format(
producer.producerid,
"".join(map(lambda e: self.buildExchange(producer.exchanges[e]), producer.exchanges.keys())))
def buildTable(self, configuration):
return """
<table><tbody>{}</tbody></table>
""".format(
"".join(list(
map(lambda p: self.buildProducer(configuration.producers[p]), configuration.producers.keys()))
)
)
def buildPage(self, simulator, state):
page = (open("resources/index.html")).read()
patches = {
"error": state["error"],
"errorvisible": "" if state["error"] != None else "invisible",
"delimiter": state["delimiter"],
"skiplines": state["skiplines"],
"address": simulator.address,
"fixed": "checked" if simulator.fixed else "",
"displaystart": "inactive" if simulator.isRunning() else "active",
"displaystop": "active" if simulator.isRunning() else "inactive",
"egd": self.buildTable(simulator.egd) if simulator.egd != None else ""
}
page = page.format(**patches)
state["error"] = None
return page
def buildDocumentationPage(self):
page = (open("resources/documentation.html")).read()
patches = {
"license": open("LICENSE").read().replace("\n", "<br/>"),
"authors": open("AUTHORS").read().replace("\n", "<br/>"),
"manual": open("README.md").read().replace("\n", "<br/>")
}
page = page.format(**patches)
return page
def returnPage(self, page):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
if sys.version_info < (3,):
self.wfile.write(page)
else:
self.wfile.write(bytes(page, "UTF-8"))
def returnResource(self, resource, mediatype):
self.send_response(200)
self.send_header(
'Content-type', (mediatype if mediatype != None else ""))
self.end_headers()
self.wfile.write(open(resource, "rb").read())
def redirect(self, location):
self.send_response(301)
self.send_header('Location', location)
self.end_headers()
def do_GET(self):
global simulator
global state
if self.path == "/":
self.returnPage(self.buildPage(simulator, state))
return
if self.path == "/logo":
self.returnResource("resources/logonubisware.png", "image/png")
return
if self.path == "/favicon.ico":
self.returnResource("resources/favicon.ico", "image/ico")
return
if self.path == "/documentation":
self.returnPage(self.buildDocumentationPage())
return
else:
self.redirect("/")
return
def parseMultipartPy2(self):
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
if not ctype == "multipart/form-data":
self.redirect("/")
return
query = cgi.parse_multipart(self.rfile, pdict)
mkvie = query.get("mkvie")[0] if query.get("mkvie")[
0].decode("utf-8-sig") != "" else None
custom = query.get("custom")[0] if query.get("custom")[
0].decode("utf-8-sig") != "" else None
state["delimiter"] = query.get("delimiter")[0]
state["skiplines"] = int(query.get("skiplines")[0])
return (mkvie, custom)
def parseMultipartPy3(self):
global state
ctype, pdict = cgi.parse_header(self.headers.get('content-type'))
if not ctype == "multipart/form-data":
self.redirect("/")
return
pdict["boundary"] = bytes(pdict["boundary"], "utf-8")
query = cgi.parse_multipart(self.rfile, pdict)
mkvie = query.get("mkvie")[0] if query.get("mkvie")[
0].decode("utf-8-sig") != "" else None
custom = query.get("custom")[0] if query.get("custom")[
0].decode("utf-8-sig") != "" else None
state["delimiter"] = (query.get("delimiter")[0]).decode("utf-8")
state["skiplines"] = int(query.get("skiplines")[0])
return (mkvie, custom)
def do_POST(self):
global simulator
global state
if self.path == "/start":
ctype, pdict = cgi.parse_header(self.headers.get('content-type'))
try:
pdict["boundary"] = bytes(
pdict["boundary"], "utf-8") # fix 2 to 3 bug
except:
pdict["boundary"] = bytes(pdict["boundary"])
if not ctype == "multipart/form-data":
self.returnPage(self.buildPage())
return
query = cgi.parse_multipart(self.rfile, pdict)
simulator.fixed = query.get(
"fixed") != None and query.get("fixed")[0] != ""
if query.get("address")[0] != None and query.get("address")[0] != "":
simulator.address = (query.get("address")[0]).decode("utf-8")
if not simulator.isRunning():
simulator.start()
self.redirect("/")
if self.path == "/stop":
if simulator.isRunning():
simulator.stop()
self.redirect("/")
if self.path == "/configure":
mkvie = None
custom = None
if sys.version_info < (3,):
mkvie, custom = self.parseMultipartPy2()
else:
mkvie, custom = self.parseMultipartPy3()
wasrunning = simulator.isRunning()
if wasrunning:
simulator.stop()
if mkvie != None and mkvie != "" and mkvie != b"":
print("Parsing MKVIE")
newegd = egdmodel.EGDConfiguration()
try:
MKVIe.Parser(newegd).parse(
mkvie, state["delimiter"], state["skiplines"])
except Exception as e:
state["error"] = "Unable to parse MKVIe CSV: " + \
str(e) + str(sys.exc_info()[2].tb_lineno)
self.redirect("/")
simulator.egd = newegd
print(simulator.egd.dump())
elif custom != None and custom != "" and custom != b"":
print("Parsing Custom")
newegd = egdmodel.EGDConfiguration()
try:
Custom.Parser(newegd).parse(
custom, state["delimiter"], state["skiplines"])
except Exception as e:
state["error"] = "Unable to parse Custom CSV: " + \
str(e) + str(sys.exc_info()[2].tb_lineno)
self.redirect("/")
simulator.egd = newegd
print(simulator.egd.dump())
if wasrunning:
simulator.start()
self.redirect("/")
return
else:
self.redirect("/")
return
simulator = None
state = {
"skiplines": 2,
"delimiter": ",",
"error": None
}
def dumpUsage():
print("python " + sys.argv[0] + ' [-p <port>] [-a <initial send address>]')
def boot(argv):
global simulator
global state
HTTP_PORT = 8000
INIT_ADDRESS = "127.0.0.255"
# INIT_CSV = None
try:
opts, args = getopt.getopt(argv[1:], "hp:a:")
for opt, arg in opts:
if opt == "-h":
dumpUsage()
sys.exit(0)
elif opt == "-p":
HTTP_PORT = int(arg)
elif opt == "-a":
INIT_ADDRESS = int(arg)
except getopt.GetoptError:
dumpUsage()
sys.exit(2)
# Initialize with empty configuration and default values for fixed and address
simulator = egdsimulator.EGDSimulator(
egdmodel.EGDConfiguration(), INIT_ADDRESS, False)
httpd = SocketServer.TCPServer(
("", HTTP_PORT), MyHandler, bind_and_activate=False)
httpd.allow_reuse_address = True
httpd.daemon_threads = True
try:
print("\nCreating HTTP server...")
httpd.server_bind()
httpd.server_activate()
print(sys.argv[0] + " HTTP server is listening on port " +
str(HTTP_PORT) + "...")
httpd.serve_forever()
except KeyboardInterrupt as e:
print("Interrupted by user...")
except Exception as e:
print(e)
print(traceback.format_exc())
try:
print("Stopping simulator...")
simulator.stop()
print("Stopping HTTP server...")
httpd.shutdown()
httpd.server_close()
except Exception as e:
print(e)
print(traceback.format_exc())
sys.exit(1)
if __name__ == "__main__":
boot(sys.argv)