forked from amunson27/EyeblinkRig
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheyeblink_app.py
More file actions
328 lines (258 loc) · 9.92 KB
/
eyeblink_app.py
File metadata and controls
328 lines (258 loc) · 9.92 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
'''eyeblink_app.py
Joey Broussard
PNI
20191106
Interfaces the eyeblink class with an HTML/JS based web GUI
(1) need to use eventlet, otherwise .run() defaults to gevent() which is SLOW
(2) monkey_path() wraps some functions to call eventlet equivalents
in particule time.sleep() is redirected to coresponding eventlet() call
'''
from flask import Flask, abort, render_template, send_file, request
from flask_socketio import SocketIO, emit
from flaskext.markdown import Markdown
import os, time
from datetime import datetime
from threading import Thread
import eventlet
import json
import sys
import signal
from eyeblink import eyeblink
from eyeblinkAnalysis import eyeblinkAnalysis
from plotly_plot import myplotlyplot
from settings import APP_ROOT
#see: https://github.com/miguelgrinberg/Flask-SocketIO/issues/192
eventlet.monkey_patch()
#eventlet.debug.hub_prevent_multiple_readers(False)
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.debug = True
app.config['DATA_FOLDER'] = 'data/'
Markdown(app, extensions=['fenced_code'])
#Getting socket for state transfer and declaring namespace
socketio = SocketIO(app, async_mode='eventlet')
namespace = ''
#Initializing objects attributes
thread = None #second thread used by background_thread()
ser = None
myeyeblink = None
myanalysis = None
def background_thread():
"""Example of how to send server generated events to clients."""
#Constantly update the server output stream with current
#object state
while True:
time.sleep(.7)
response = MakeServerResponse()
jsonResponse = json.dumps(response)
socketio.emit('serverUpdate', jsonResponse, namespace=namespace)
def MakeServerResponse():
#Import eyeblink object state to push to server
now = datetime.now()
dateStr = now.strftime("%m/%d/%y")
timeStr = now.strftime("%H:%M:%S.%f")
response = {}
response['currentdate'] = dateStr
response['currenttime'] = timeStr
response['savepath'] = myeyeblink.savepath
response['animalID'] = myeyeblink.animalID
response['filePath'] = myeyeblink.trial['filePath']
response['fileName'] = myeyeblink.trial['fileName']
response['trialRunning'] = myeyeblink.trialRunning
response['sessionNumber'] = myeyeblink.trial['sessionNumber']
response['sessionDur'] = myeyeblink.trial['sessionDur']
response['trialNumber'] = myeyeblink.trial['trialNumber']
response['numTrial'] = myeyeblink.trial['numTrial']
response['useMotor'] = myeyeblink.trial['useMotor']
return response
@app.route('/')
def index():
global thread
if thread is None:
print('starting background thread')
thread = Thread(target=background_thread)
thread.daemon = True; #as a daemon the thread will stop when *this stops
thread.start()
theRet = render_template('indexE.html', eyeblink=myeyeblink)
return theRet
@app.route('/form2')
def form2():
return render_template('form_sandbox.html')
#from: http://stackoverflow.com/questions/23718236/python-flask-browsing-through-directory-with-files
@app.route('/', defaults={'req_path': ''})
@app.route('/<path:req_path>')
def dir_listing(req_path):
print('\n')
print('req_path:', req_path)
# Joining the base and the requested path
abs_path = os.path.join(APP_ROOT, req_path)
print('abs_path:', abs_path)
# Return 404 if path doesn't exist
if not os.path.exists(abs_path):
return abort(404)
# Check if path is a file and serve
if os.path.isfile(abs_path):
return send_file(abs_path)
# Show directory contents
if os.path.isdir(abs_path):
print('IS DIRECTORY:', abs_path)
files = os.listdir(abs_path)
return render_template('files.html', path=req_path.replace('data/','') + '/', files=files)
@app.route('/analysis')
def analysis():
#list = myAnalysis.getlist()
#return render_template('analysis.html', list=list)
myAnalysis.builddb('')
return render_template('analysis2E.html')
@app.route('/help')
def help():
return render_template('help.md')
@app.route('/p5')
def index_highchart():
return render_template('p5.html')
@app.route('/grafica')
def index_grafica():
return render_template('grafica.html')
@socketio.on('connectArduino', namespace=namespace) #
def connectArduino(message):
emit('my response', {'data': message['data']})
print('connectArduino', message['data'])
@socketio.on('startarduinoButtonID', namespace=namespace) #
def startarduinoButton(message):
print('startarduinoButtonID')
myeyeblink.startSession()
@socketio.on('stoparduinoButtonID', namespace=namespace) #
def stoparduinoButtonID(message):
print('stoparduinoButtonID')
myeyeblink.stopSession()
@socketio.on('printArduinoStateID', namespace=namespace) #
def printArduinoStateID(message):
myeyeblink.GetArduinoState()
@socketio.on('emptySerialID', namespace=namespace) #
def printArduinoStateID(message):
myeyeblink.emptySerial()
@socketio.on('checkserialportID', namespace=namespace) #
def checkserialportID(message):
exists, str = myeyeblink.checkserialport()
if exists:
emit('serialdata', {'data': "OK: " + str})
else:
emit('serialdata', {'data': "ERROR: " + str})
@socketio.on('setSerialPortID', namespace=namespace) #
def setSerialPort(message):
portStr = message['data']
ok = myeyeblink.setserialport(portStr)
if ok:
emit('serialdata', {'data': "OK: " + portStr})
else:
emit('serialdata', {'data': "ERROR: " + portStr})
@socketio.on('arduinoVersionID', namespace=namespace) #
def arduinoVersionID(message):
myeyeblink.checkarduinoversion()
@socketio.on('my event', namespace=namespace) #responds to echo
def test_message(message):
emit('my response', {'data': message['data']})
@socketio.on('my broadcast event', namespace=namespace)
def test_message(message):
emit('my response', {'data': message['data']}, broadcast=True)
@socketio.on('connect', namespace=namespace)
def test_connect():
emit('my response', {'data': 'Connected'})
@socketio.on('disconnect', namespace=namespace)
def test_disconnect():
print('*** eyeblink_app -- Client disconnected')
@socketio.on('trialform', namespace=namespace)
def trialform(message):
'''message is trailFormDict from eyeblink object'''
print('\n=== eyeblink_app.trialform:', message)
numTrial = message['numTrial']
trialDur = message['trialDur']
interTrialIntervalLow = message['interTrialIntervalLow']
interTrialIntervalHigh = message['interTrialIntervalHigh']
preCSdur = message['preCSdur']
CSdur = message['CSdur']
USdur = message['USdur']
percentUS = message['percentUS']
percentCS = message['percentCS']
useMotor = message['useMotor'] #{motorOn, motorLocked, motorFree}
motorSpeed = message['motorSpeed']
#
emit('serialdata', {'data': "=== Session Form ==="})
myeyeblink.settrial('numTrial', numTrial)
time.sleep(0.01)
myeyeblink.settrial('trialDur', trialDur)
time.sleep(0.01)
myeyeblink.settrial('interTrialIntervalLow', interTrialIntervalLow)
time.sleep(0.01)
myeyeblink.settrial('interTrialIntervalHigh', interTrialIntervalHigh)
time.sleep(0.01)
myeyeblink.settrial('preCSdur', preCSdur)
time.sleep(0.01)
myeyeblink.settrial('CSdur', CSdur)
time.sleep(0.01)
myeyeblink.settrial('USdur', USdur)
time.sleep(0.01)
myeyeblink.settrial('percentUS', percentUS)
time.sleep(0.01)
myeyeblink.settrial('percentCS', percentCS)
time.sleep(0.01)
myeyeblink.settrial('motorSpeed', motorSpeed)
time.sleep(0.01)
myeyeblink.settrial('useMotor', useMotor)
time.sleep(0.01)
myeyeblink.updatetrial() #update total dur
myeyeblink.emptySerial()
print('trialform() useMotor=', useMotor)
trialDiv = myAnalysis.plottrialparams(myeyeblink.trial)
emit('trialPlotDiv', {'data': trialDiv})
emit('serialdata', {'data': "=== Session Form Done ==="})
@socketio.on('animalform', namespace=namespace)
def animalform(message):
print('animalform:', message)
animalID = message['animalID']
myeyeblink.animalID = animalID
#mytreadmill.settrial('dur', dur)
emit('my response', {'data': "animal id is now '" + animalID + "'"})
@socketio.on('plotSessionButtonID', namespace=namespace)
def plotTrialButton(message):
filePath = message['data']
print('plotSessionButton() filename:' + filePath)
divStr = myplotlyplot(filePath,'div')
emit('lastSessionPlot', {'plotDiv': divStr})
@socketio.on('plotTrialHeaderID', namespace=namespace)
def plotTrialHeader(message):
filename = message['data']
print('plotTrialHeader() filename:' + filename)
headerStr = myAnalysis.loadheader(filename)
emit('headerDiv', {'headerStr': headerStr})
@socketio.on('filterTrial', namespace=namespace)
def filterTrial(message):
filename = myAnalysis.builddb(message['data'])
emit('refreshList', {'data': filename})
def sig_handler(signal,frame):
print('Signal handler called by eyeblink_app.py')
myeyeblink.__del__
print('Process kill applied to eyeblinkCamera subprocess')
os.system("pkill -9 -f eyeblinkCamera.py")
sys.exit(0)
if __name__ == '__main__':
try:
#Make kill method for all processes and threads
signal.signal(signal.SIGINT, sig_handler)
#Starting the camera as a subprocess
os.system("python3 eyeblinkCamera.py &")
#Initializing the eyeblink object
myeyeblink = eyeblink()
dataRoot = os.path.join(APP_ROOT, "data") + '/'
myeyeblink.setsavepath(dataRoot)
myeyeblink.bAttachSocket(socketio)
#Starting the plotly_plots based ananlysis thread
myAnalysis = eyeblinkAnalysis()
myAnalysis.assignfolder(dataRoot)
print('starting server')
#host settings in 'this' namespace location if desired here
socketio.run(app, host='10.9.67.150', port=5010, use_reloader=True)
print('finished')
except:
print('...exiting')
raise