-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb.py
More file actions
204 lines (175 loc) · 6.93 KB
/
web.py
File metadata and controls
204 lines (175 loc) · 6.93 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
from flask import Flask, session, redirect, url_for, render_template, request, jsonify
import random
import time
import json
from threading import Thread, Lock
import os
from multiprocessing import Queue
q = Queue()
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
count = 0
class Channel: #analog channel objects
def __init__(self, name, color, address, rawLow=0.0, rawHigh=10.0, scaledLow=0.0, scaledHigh=10.0):
self.name = name
self.color = color
self.address = address
self.rawLow = rawLow
self.rawHigh = rawHigh
self.scaledLow = scaledLow
self.scaledHigh = scaledHigh
def serialize(self):
return {
'name':self.name,
'color':self.color,
'address':self.address,
'rawLow':self.rawLow,
'rawHigh':self.rawHigh,
'scaledLow':self.scaledLow,
'scaledHigh':self.scaledHigh
}
class Instruction: #instruction object
def __init__(self, header, body=''):
self.header = header
self.body = body
def serialize(self):
return {
'header': self.header,
'body': json.dumps(self.body)
}
def scaleValue(rawValue, channel):
m = (channel.scaledHigh - channel.scaledLow) / (channel.rawHigh - channel.rawLow)
b = channel.scaledLow - m * channel.rawLow
return m * rawValue + b
channels = [Channel('Inner temperature','#ff0000',1234),Channel('Outer temperature','#00ff00',1235)] #staring list of channels
latestValues = [] #list of the most recent values from the input cards
lock = Lock()
path = '/vagrant/www/data'
filename = '' #current filename
for ch in channels: #initialize the latestValues list
latestValues.append(0.0)
@app.route("/")
def index():
global count
count = count +1
if 'welcome' in session:
return render_template('index.html')
return redirect(url_for('splashScreen'))
@app.route('/settings')
def settings():
return render_template('settings.html')
@app.route("/splashScreen")
def splashScreen():
global count
count = count +1
session['welcome'] = 'true'
return render_template('spinningLogo.html')
#return "Welcome<br><a href='/'>Home</a>"
@app.route("/action/<action>", methods = ['GET','POST'])
def action(action):
global channels, latestValues, q, filename
if(action == 'getLatest'):
return jsonify(error=False, values=latestValues, filename = filename)
elif(action == 'getChannels'):
return jsonify(channels = [ch.serialize() for ch in channels])
elif(action == 'updateInputChannel'):
index = int(request.form['index'])
channels[index].name = request.form['name']
channels[index].address = request.form['address']
channels[index].color = request.form['color']
channels[index].rawLow = float(request.form['rawLow'])
channels[index].scaledLow = float(request.form['scaledLow'])
channels[index].rawHigh = float(request.form['rawHigh'])
channels[index].scaledHigh = float(request.form['scaledHigh'])
return jsonify(error=False,channel=channels[index].serialize())
elif(action == 'addInputChannel'):
channel = Channel(request.form['name'],request.form['color'],request.form['address'],float(request.form['rawLow']),float(request.form['rawHigh']),float(request.form['scaledLow']),float(request.form['scaledHigh']))
with lock:
channels.append(channel)
latestValues.append(0.0)
return jsonify(error=False,channel=channel.serialize())
elif(action == 'deleteChannel'):
index = int(request.form['index'])
with lock:
del channels[index]
del latestValues[index]
return jsonify(error=False)
elif(action == 'getFileList'):
return jsonify(files=os.listdir(path))
elif(action == 'startLogging'): #TODO - check to see if the file already exists
filename = request.form['filename'] + '.csv'
print "should start logging with filename: "+filename
existingFiles = os.listdir(path)
if filename in existingFiles:
return jsonify(error=True, message="File already exists. Choose another filename.")
q.put(Instruction('openFile',filename))
return jsonify(error=False)
elif(action == 'stopLogging'):
print "should close file"
q.put(Instruction('closeFile'))
return jsonify(error=False)
else:
return jsonify(error=True,message="Action "+action+" not recognized")
@app.route("/logging")
def logging():
return render_template('logging.html')
def io(): #thread reading from the hardware inputs and outputs... Simulated values at this point...
global channels, latestValues, q
while True:
x = 0
with lock:
try:
for ch in channels:
latestValues[x] = scaleValue(random.randint(0,10),ch)
x += 1
#print json.dumps(latestValues)
q.put(Instruction('writeData',latestValues))
except:
print("Error writing to latestValues")
time.sleep(0.5)
t = Thread(target=io)
t.start()
def fileModule(): #TODO - add time column (elapsed time in seconds?)
global q, channels, path, filename
f = None #file reference
startTime = None #time file was created
firstDataWrite = True #want to set start time with first data write
while True:
i = q.get()
if(i.header == 'writeData'):
if f is not None:
print "The file appears to be open so we'll try to write to it, "+json.dumps(i.body)
if firstDataWrite:
firstDataWrite = False
contents = '0,'
startTime = time.time()
else:
contents = "{:0.2f}".format(time.time() - startTime)+','
for value in i.body:
contents += str(value) + ','
contents += '\n'
print "contents: "+contents
f.write(contents)
elif (i.header == 'openFile'): #TODO - add column headers when opening a new file
filePath = path+'/'+i.body
print "Will open filename: "+filePath
filename = i.body
f = open(filePath,"w+")
header = 'Time(s),'
for ch in channels:
header += ch.name + ','
header += '\n'
f.write(header)
firstDataWrite = True #reset firstDataWrite
elif (i.header == 'closeFile'):
print "Will close file"
f.close()
f = None
filename = ''
else:
print "fileModule: unrecognized header..."+json.dumps(i.serialize())
fileThread = Thread(target=fileModule)
fileThread.start()
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=5000)