forked from kaveri-nadhamuni/Beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver-side.py
278 lines (241 loc) · 8.63 KB
/
server-side.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
import datetime
import sqlite3
import requests
#import matplotlib.pyplot as plt
import numpy as np
from bokeh.plotting import figure, output_file, show
from bokeh.embed import components
from bokeh.models import Title
heartRate_db = "__HOME__/heartRate.db"
def request_handler(request):
if (request["method"] == 'POST'):
return do_POST(request)
elif (request["method"] == 'GET'):
if ('type' not in request["args"]):
return "Error please enter the type of graph"
else:
#data from SQL
data = get_data()
#type of graph from input
graph = request['values']['type']
if graph == "ekg":
index = 0
t = ("Graph for the EKG")
elif graph == "steps":
index = 1
t = ("Graph for the Steps")
else:
return "error please enter either ekg or steps"
#time axis
xaxis = []
for i in range(len(data[index])+1):
xaxis.append(i*5)
#bokeh stuff
p = figure(title = t, plot_width=400, plot_height=400)
p.line(xaxis, data[index], line_width=2)
#titles
p.add_layout(Title(text="Time (s)", align="center"), "below")
if index == 0:
p.add_layout(Title(text="Heart Rate (BPM)", align="left"), "left")
else:
p.add_layout(Title(text="Steps (steps per second)", align="left"), "left")
p.title.text_font_size = "20px"
p.toolbar.logo = None
script, div = components(p)
output = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bokeh Scatter Plots</title>
<link rel="stylesheet" href="http://cdn.pydata.org/bokeh/release/bokeh-0.12.13.min.css" type="text/css" />
<script type="text/javascript" src="http://cdn.pydata.org/bokeh/release/bokeh-0.12.13.min.js"></script>
{}
</head>
<body>
{}
</body>
</html>""".format(script,div)
return output
def do_POST(request):
kerb = str(request['form']["kerb"])
heartRate = request['form']["heartRate"]
steps = request['form']["steps"]
#SQL stuff
conn = sqlite3.connect(heartRate_db) # connect to that database (will create if it doesn't already exist)
c = conn.cursor() # make cursor into database (allows us to execute commands)
outs = ""
try:
c.execute('''CREATE TABLE dated_table (ID, time, kerb, rate, steps);''') # run a CREATE TABLE command
outs = "database constructed"
except:
things = c.execute('''SELECT * FROM dated_table ORDER BY ID DESC;''').fetchone()
if things == None:
things=[0]
dataID = things[0] + 1
c.execute('''INSERT into dated_table VALUES (?,?,?,?,?);''', (dataID,datetime.datetime.now(),kerb,heartRate,steps))
things = c.execute('''SELECT * FROM dated_table ORDER BY ID DESC;''').fetchall()
outs = things
conn.commit() # commit commands
conn.close() # close connection to database
return outs
def get_data():
#SQL stuff
conn = sqlite3.connect(heartRate_db) # connect to that database (will create if it doesn't already exist)
c = conn.cursor() # make cursor into database (allows us to execute commands)
outs = ""
things = c.execute('''SELECT * FROM dated_table ORDER BY ID DESC;''').fetchone()
result = []
result.append(parse(tokenize(things[3])))
result.append(parse(tokenize(things[4])))
conn.commit() # commit commands
conn.close() # close connection to database
return result
def tokenize(equation):
"""helper function: splits up function with no spaces"""
token = []
#keeps track of current "word"
val = ""
for i in equation:
#if there is a paren
if i == ",":
pass
elif i == "[":
if val != "":
token.append(val)
val = ""
token.append(i)
elif i == "]":
if val != "":
token.append(val)
val = ""
val += i
#keeps track of op and numbers
elif i != " ":
val += i
elif i == " ":
token.append(val)
val = ""
if val != "":
token.append(val)
return token
def parse(tokens):
"""
Parses a list of tokens, constructing a representation where:
* symbols are represented as Python strings
* numbers are represented as Python ints or floats
* S-expressions are represented as Python lists
Arguments:
tokens (list): a list of strings representing tokens
"""
# (define circle-area (lambda (r) (* 3.14 (* r r))))
# ['define', 'circle-area', ['lambda', ['r'], ['*', 3.14, ['*', 'r', 'r']]]]
def check_valid_paren(s):
"""return True if each left parenthesis is closed by exactly one
right parenthesis later in the string and each right parenthesis
closes exactly one left parenthesis earlier in the string."""
par = 0
end_par = False
for i in s:
if i == "[":
par += 1
end_par = True
elif i == "]":
par -= 1
end_par = False
if par<0:
return False
#checks if it ends with an open paren or if the number of open doesn't equal close paren
if end_par or par != 0:
return False
return True
def typeChange(x):
"""helper function: to change type into a int float or stay as a string"""
try:
#if float or int
a = float(x)
try:
b = int(x)
if a == b:
return b
except:
return a
except:
#else it's a str
return x
#if str, float, or int
if tokens[0] != "[":
if len(tokens) == 1:
return typeChange(tokens[0])
raise SyntaxError
#if s-expression
if not check_valid_paren(tokens):
raise SyntaxError
#parses s expressions
def parseExpressions(tokens, index = 1):
"""helper function: recursive function that parses s - expressions"""
# (define circle-area (lambda (r) (* 3.14 (* r r))))
parsed = []
while index<len(tokens):
item = tokens[index]
# if its an ( then there needs to be a new list so it recursively calls itself
if item == "[":
inner_list, index = parseExpressions(tokens, index+1)
parsed.append(inner_list)
elif item == "]":
return parsed, index + 1
else:
parsed.append(typeChange(item))
index += 1
return parsed, index
parsed, index = parseExpressions(tokens)
return parsed
##def ekgPlot(data):
## plt.xlabel('time/ s')
## plt.ylabel('Heart rate/ bpm')
## plt.title('EKG graph')
##
## #since we take a heartrate reading once every 0.5 seconds
## xaxis = list(np.arange(0, len(data)//2, 0.5))
##
## plt.plot(xaxis,data,'o')
## plt.plot(xaxis,data)
## plt.axis([0,-(-len(data)//2),0,max(data)+-(-max(data)//10)])
## plt.show()
##def ekgPlot2(data):
## p = figure(plot_width=400, plot_height=400)
## xaxis = []
## for i in range(len(data)+1):
## xaxis.append(i*5)
## p.line(xaxis, data, line_width=2)
## p.toolbar.logo = None
## script, div = components(p)
## output = r"""<!DOCTYPE html>
##<html lang="en">
## <head>
## <meta charset="utf-8">
## <title>Bokeh Scatter Plots</title>
##
## <link rel="stylesheet" href="http://cdn.pydata.org/bokeh/release/bokeh-0.12.13.min.css" type="text/css" />
## <script type="text/javascript" src="http://cdn.pydata.org/bokeh/release/bokeh-0.12.13.min.js"></script>
## {}
##
## </head>
## <body>
## {}
## </body>
##</html>""".format(script,div)
## return output
##def stepPlot(data):
## plt.xlabel('time/ s')
## plt.ylabel('Steps/ steps per min')
## plt.title('Steps graph')
##
## #since we take a steps reading once every 5 seconds
## xaxis = list(np.arange(0, len(data)*5, 5))
##
## plt.plot(xaxis,data,'o')
## plt.plot(xaxis,data)
## plt.axis([0,-(-len(data)*5),0,max(data)+-(-max(data)//10)])
## plt.show()
##stepPlot(random.sample(range(160, 170), 8))
##ekgPlot(random.sample(range(120, 145), 8))