-
Notifications
You must be signed in to change notification settings - Fork 2
/
appDhtWebHistCam.py
188 lines (155 loc) · 4.48 KB
/
appDhtWebHistCam.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# appDhtWebHistCam.py
'''
RPi WEb Server for DHT captured data with Gage and Graph plot and Streeming video
'''
# Raspberry Pi camera module (requires picamera package)
from camera_pi import Camera
from datetime import datetime
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import io
from flask import Flask, render_template, send_file, make_response, request, Response
app = Flask(__name__)
import sqlite3
conn=sqlite3.connect('../sensorsData.db')
curs=conn.cursor()
# Retrieve LAST data from database
def getLastData():
for row in curs.execute("SELECT * FROM DHT_data ORDER BY timestamp DESC LIMIT 1"):
time = str(row[0])
temp = row[1]
hum = row[2]
#conn.close()
return time, temp, hum
# Get 'x' samples of historical data
def getHistData (numSamples):
curs.execute("SELECT * FROM DHT_data ORDER BY timestamp DESC LIMIT "+str(numSamples))
data = curs.fetchall()
dates = []
temps = []
hums = []
for row in reversed(data):
dates.append(row[0])
temps.append(row[1])
hums.append(row[2])
temps, hums = testeData(temps, hums)
return dates, temps, hums
# Test data for cleanning possible "out of range" values
def testeData(temps, hums):
n = len(temps)
for i in range(0, n-1):
if (temps[i] < -10 or temps[i] >50):
temps[i] = temps[i-2]
if (hums[i] < 0 or hums[i] >100):
hums[i] = temps[i-2]
return temps, hums
# Get Max number of rows (table size)
def maxRowsTable():
for row in curs.execute("select COUNT(temp) from DHT_data"):
maxNumberRows=row[0]
return maxNumberRows
# Get sample frequency in minutes
def freqSample():
times, temps, hums = getHistData (2)
fmt = '%Y-%m-%d %H:%M:%S'
tstamp0 = datetime.strptime(times[0], fmt)
tstamp1 = datetime.strptime(times[1], fmt)
freq = tstamp1-tstamp0
freq = int(round(freq.total_seconds()/60))
return (freq)
# Define and Initialize global variables
global numSamples
numSamples = maxRowsTable()
if (numSamples > 101):
numSamples = 100
global freqSamples
freqSamples = freqSample()
global rangeTime
rangeTime = 100
# main route
@app.route("/")
def index():
time, temp, hum = getLastData()
templateData = {
'time' : time,
'temp' : temp,
'hum' : hum,
'freq' : freqSamples,
'rangeTime' : rangeTime
}
return render_template('index.html', **templateData)
@app.route('/', methods=['POST'])
def my_form_post():
global numSamples
global freqSamples
global rangeTime
rangeTime = int (request.form['rangeTime'])
if (rangeTime < freqSamples):
rangeTime = freqSamples + 1
numSamples = rangeTime//freqSamples
numMaxSamples = maxRowsTable()
if (numSamples > numMaxSamples):
numSamples = (numMaxSamples-1)
time, temp, hum = getLastData()
templateData = {
'time' : time,
'temp' : temp,
'hum' : hum,
'freq' : freqSamples,
'rangeTime' : rangeTime
}
return render_template('index.html', **templateData)
@app.route('/plot/temp')
def plot_temp():
times, temps, hums = getHistData(numSamples)
ys = temps
fig = Figure()
axis = fig.add_subplot(1, 1, 1)
axis.set_title("Temperature [°C]")
axis.set_xlabel("Samples")
axis.grid(True)
xs = range(numSamples)
axis.plot(xs, ys)
canvas = FigureCanvas(fig)
output = io.BytesIO()
canvas.print_png(output)
response = make_response(output.getvalue())
response.mimetype = 'image/png'
return response
@app.route('/plot/hum')
def plot_hum():
times, temps, hums = getHistData(numSamples)
ys = hums
fig = Figure()
axis = fig.add_subplot(1, 1, 1)
axis.set_title("Humidity [%]")
axis.set_xlabel("Samples")
axis.grid(True)
xs = range(numSamples)
axis.plot(xs, ys)
canvas = FigureCanvas(fig)
output = io.BytesIO()
canvas.print_png(output)
response = make_response(output.getvalue())
response.mimetype = 'image/png'
return response
@app.route('/camera')
def cam():
"""Video streaming home page."""
return render_template('camera.html')
def gen(camera):
"""Video streaming generator function."""
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
@app.route('/video_feed')
def video_feed():
"""Video streaming route. Put this in the src attribute of an img tag."""
return Response(gen(Camera()),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=False)