-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNESTInstrumentationApp_server.py
More file actions
305 lines (252 loc) · 8.96 KB
/
NESTInstrumentationApp_server.py
File metadata and controls
305 lines (252 loc) · 8.96 KB
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
# -*- coding: utf-8 -*-
from __future__ import print_function
import subprocess as sp
import gevent
import gevent.wsgi
import gevent.queue
import flask
import flask_socketio
import json
import nest_utils as nu
VERSION = sp.check_output(["git", "describe", "--tags", "--dirty"]).strip()
app = flask.Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # Turns off caching
socketio = flask_socketio.SocketIO(app, async_mode='gevent')
interface = {}
busy = []
BUSY_ERRORCODE = 418
subscriptions = {}
abort_sub = {}
def emit_exception(exception, user_id):
print('An exception was raised:', exception)
socketio.emit('message',
{'message': "{}: {}".format(type(exception).__name__,
exception.args[0] if exception.args else '')},
namespace='/message/{}'.format(user_id))
@app.route('/')
def redirect():
"""
Redirects the client to the right index URL.
"""
return flask.redirect(flask.url_for('index'))
@app.route('/NESTInstrumentationApp')
def index():
"""
Renders the index page template and sends it to the client.
"""
return flask.render_template('NESTInstrumentationApp.html',
version=VERSION)
@app.route('/makeNetwork', methods=['POST'])
def make_network():
"""
Receives the network and construct the interface.
"""
data = flask.request.json
user_id = int(data['userID'])
print('User ID: {}'.format(user_id))
global interface
try:
if user_id in interface:
interface[user_id].cease_threads()
interface[user_id].terminate_nest_client()
interface[user_id] = nu.NESTInterface(json.dumps(data['network']),
user_id,
socketio=socketio)
except Exception as exception:
emit_exception(exception, user_id)
print(interface)
return flask.Response(status=204)
@app.route('/selector', methods=['POST', 'GET'])
def print_GIDs():
"""
Receives the network and selected areas, and prints the GIDs in the
selected areas to the terminal.
"""
if flask.request.method == 'POST':
data = flask.request.json
user_id = int(data['userID'])
global busy
try:
if user_id in busy:
print("Cannot select, NEST is busy!")
return flask.Response(status=BUSY_ERRORCODE)
busy.append(user_id)
print('Trying to print gids..')
interface[user_id].printGIDs(json.dumps(data['info']))
busy.remove(user_id)
except Exception as exception:
emit_exception(exception, user_id)
return flask.Response(status=204)
@app.route('/connect', methods=['POST'])
def connect_ajax():
"""
Receives the network and projections, and connects them.
"""
print("Connect called")
if flask.request.method == 'POST':
global interface
data = flask.request.json
projections = json.dumps(data['projections'])
user_id = int(data['userID'])
try:
if user_id in busy:
print("Cannot connect, NEST is busy!")
return flask.Response(status=BUSY_ERRORCODE)
print('Projections:')
print(projections)
interface[user_id].device_projections = projections
interface[user_id].send_device_projections()
interface[user_id].connect_all()
except Exception as exception:
emit_exception(exception, user_id)
return flask.Response(status=204)
@app.route('/connections', methods=['GET'])
def get_connections_ajax():
"""
Sends the number of current connections to the client.
"""
global interface
print("Received ", flask.request.args.get('input'))
user_id = flask.request.args.get('userID')
n_connections = 0
try:
n_connections = interface[int(user_id)].get_num_connections()
except Exception as exception:
emit_exception(exception, user_id)
return flask.jsonify(connections=n_connections)
@app.route('/simulate', methods=['POST'])
def simulate_ajax():
"""
Receives the network and projections, connects them and simulates.
"""
global interface
global busy
data = flask.request.json
projections = json.dumps(data['projections'])
user_id = int(data['userID'])
try:
if user_id in busy:
print("Cannot simulate, NEST is busy!")
return flask.Response(status=BUSY_ERRORCODE)
t = float(data['time'])
busy.append(user_id)
interface[user_id].device_projections = projections
interface[user_id].send_device_projections()
interface[user_id].connect_all()
print("Simulating for ", t, "ms ...")
interface[user_id].simulate(t)
interface[user_id].simulate(-1)
busy.remove(user_id)
except Exception as exception:
emit_exception(exception, user_id)
return flask.Response(status=204)
def g_simulate(network, projections, t, user_id):
"""
Runs a simulation in steps. This way the client can be updated on the
status of the simulation.
:param network: network specifications
:param projections: projections between layers and devices
:param t: time to simulate
"""
global interface
global busy
global subscriptions
try:
busy.append(user_id)
interface[user_id].device_projections = projections
interface[user_id].send_device_projections()
interface[user_id].connect_all()
interface[user_id].device_results = '{}'
q = gevent.queue.Queue()
abort_sub[user_id] = q
steps = 1000
sleep_t = 0.1 # sleep time
dt = float(t) / steps
for i in range(steps):
print(i)
if not q.empty():
abort = q.get()
if abort:
print("Simulation aborted")
break
interface[user_id].simulate(dt)
device_results = None
while device_results is None:
device_results = interface[user_id].get_device_results()
if device_results is None:
# Waiting for results
gevent.sleep(sleep_t)
results = json.loads(device_results)
if results:
jsonResult = flask.json.dumps(results)
if user_id in subscriptions:
subscriptions[user_id].put(jsonResult)
interface[user_id].device_results = '{}'
# Yield this context to check abort and send data
gevent.sleep(sleep_t)
interface[user_id].simulate(-1)
busy.remove(user_id)
if user_id in subscriptions:
subscriptions[user_id].put(
flask.json.dumps({"simulation_end": True}))
except Exception as exception:
emit_exception(exception, user_id)
@app.route('/streamSimulate', methods=['POST'])
def streamSimulate():
"""
Receive data from the client and run a simulation in steps.
"""
data = flask.request.json
network = json.dumps(data['network'])
projections = json.dumps(data['projections'])
user_id = int(data['userID'])
try:
if user_id in busy:
print("Cannot simulate, NEST is busy!")
return flask.Response(status=BUSY_ERRORCODE)
t = data['time']
print("Simulating for ", t, "ms")
gevent.spawn(g_simulate, network, projections, t, user_id)
except Exception as exception:
emit_exception(exception, user_id)
return flask.Response(status=204)
@app.route('/abortSimulation', methods=['POST'])
def abortSimulation():
"""
Abort the currently running simulation.
"""
global abort_sub
user_id = int(flask.request.json['userID'])
try:
if user_id in abort_sub:
abort_sub[user_id].put(True)
except Exception as exception:
emit_exception(exception, user_id)
return flask.Response(status=204)
@app.route('/simulationData/<int:user_id>')
def simulationData(user_id):
"""
Lets the client listen to this URL to get updates on the simulation status.
"""
global subscriptions
def gen():
try:
q = gevent.queue.Queue()
subscriptions[user_id] = q
try:
while True:
result = q.get()
ev = "data: " + result + "\n\n"
yield ev
except GeneratorExit:
del subscriptions[user_id]
except Exception as exception:
emit_exception(exception, user_id)
return flask.Response(gen(), mimetype="text/event-stream")
if __name__ == '__main__':
socketio.run(app,
host="",
port=7000,
log_output=True,
keyfile='../certs/fsd-cloud42_zam_kfa-juelich_de.key',
certfile='../certs/fsd-cloud42_zam_kfa-juelich_de.pem')