194 lines
5.4 KiB
Python
194 lines
5.4 KiB
Python
from flask import Flask, render_template, make_response, jsonify, request
|
|
import mysql.connector as mariadb
|
|
import datetime
|
|
import time
|
|
import io
|
|
import json
|
|
import pandas as pd
|
|
from collections import OrderedDict
|
|
|
|
DB = ""
|
|
DB_USER = ""
|
|
DB_PASSWORD = ""
|
|
API_SECRET = ""
|
|
|
|
class Source():
|
|
def __init__(self):
|
|
self.status = "unknown"
|
|
self.last_msg = 0.0
|
|
|
|
source = Source()
|
|
app = Flask(__name__)
|
|
|
|
def query_db(sql):
|
|
dbconn = mariadb.connect(user=DB_USER, password=DB_PASSWORD, database=DB)
|
|
cursor = dbconn.cursor()
|
|
|
|
try:
|
|
cursor.execute(sql)
|
|
except mariadb.Error as e:
|
|
print(e)
|
|
|
|
data = cursor.fetchall()
|
|
dbconn.close()
|
|
|
|
return data
|
|
|
|
@app.route('/')
|
|
def index():
|
|
return render_template('index.html')
|
|
|
|
@app.route('/api/getData', methods = ['GET','POST'])
|
|
def process_data():
|
|
if request.method == 'GET':
|
|
if request.args.get('samples') is not None:
|
|
try:
|
|
samples = int(request.args.get('samples'))
|
|
if samples > 10800:
|
|
samples = 120
|
|
except Exception as excp:
|
|
print(excp)
|
|
samples = 120
|
|
else:
|
|
samples = 120
|
|
|
|
elif request.method == 'POST':
|
|
try:
|
|
samples = int(request.form.get('samples'))
|
|
except Exception as excp:
|
|
print(excp)
|
|
samples = 120
|
|
|
|
if samples > 10800:
|
|
samples = 120
|
|
|
|
sql = "SELECT * FROM envdata ORDER BY timestamp DESC LIMIT %s" % samples
|
|
dbdata = query_db(sql)
|
|
|
|
f = '%Y-%m-%d %H:%M:%S'
|
|
|
|
labels = []
|
|
temps = []
|
|
hums = []
|
|
press = []
|
|
concs = []
|
|
|
|
for i in range(len(dbdata)):
|
|
labels.append(dbdata[i][0])
|
|
temps.append(dbdata[i][1])
|
|
hums.append(dbdata[i][2])
|
|
press.append(dbdata[i][3])
|
|
concs.append(dbdata[i][4])
|
|
|
|
df = pd.DataFrame({'dt': labels, 'temp': temps, 'hum': hums, 'pres': press, 'conc': concs})
|
|
r = pd.date_range(start=df['dt'].min(), end=df['dt'].max(), freq='T')
|
|
# df = df.drop_duplicates('dt').set_index('dt').reindex(r, method='pad', tolerance='90s').reset_index()
|
|
df = df.set_index('dt').reindex(r, method='nearest', tolerance='90s').reset_index()
|
|
|
|
darry = df.to_numpy()
|
|
start = len(darry)
|
|
print("darry %s" % str(len(darry)))
|
|
print("samples %s" % str(samples))
|
|
print(start)
|
|
print(start-samples)
|
|
print(samples-start)
|
|
|
|
if len(darry) != samples:
|
|
if samples > len(darry):
|
|
labels=darry[samples-start:start:1,0]
|
|
temps=darry[samples-start:start:1,1]
|
|
hums=darry[samples-start:start:1,2]
|
|
press=darry[samples-start:start:1,3]
|
|
concs=darry[samples-start:start:1,4]
|
|
else:
|
|
labels=darry[start-samples:start:1,0]
|
|
temps=darry[start-samples:start:1,1]
|
|
hums=darry[start-samples:start:1,2]
|
|
press=darry[start-samples:start:1,3]
|
|
concs=darry[start-samples:start:1,4]
|
|
elif len(darry) == 1:
|
|
labels=darry[0,0]
|
|
temps=darry[0,1]
|
|
hums=darry[0,2]
|
|
press=darry[0,3]
|
|
concs=darry[0,4]
|
|
else:
|
|
labels=darry[0:start:1,0]
|
|
temps=darry[0:start:1,1]
|
|
hums=darry[0:start:1,2]
|
|
press=darry[0:start:1,3]
|
|
concs=darry[0:start:1,4]
|
|
|
|
tempdict = OrderedDict()
|
|
humdict = OrderedDict()
|
|
presdict = OrderedDict()
|
|
co2dict = OrderedDict()
|
|
|
|
if len(darry) == 1:
|
|
tempdict[labels.strftime(f)] = str(temps)
|
|
humdict[labels.strftime(f)] = str(hums)
|
|
presdict[labels.strftime(f)] = str(press)
|
|
co2dict[labels.strftime(f)] = str(concs)
|
|
else:
|
|
for i in range(len(labels)):
|
|
tempdict[labels[i].strftime(f)] = str(temps[i])
|
|
humdict[labels[i].strftime(f)] = str(hums[i])
|
|
presdict[labels[i].strftime(f)] = str(press[i])
|
|
co2dict[labels[i].strftime(f)] = str(concs[i])
|
|
|
|
if (time.time() - source.last_msg) > 180:
|
|
status = "dead"
|
|
else:
|
|
status = "alive"
|
|
|
|
respdict = OrderedDict()
|
|
datas = ["status", "temp", "hum", "pres", "co2"]
|
|
dicts = [status, tempdict, humdict, presdict, co2dict]
|
|
|
|
for i in range(len(datas)):
|
|
respdict[datas[i]] = dicts[i]
|
|
|
|
response = app.response_class(
|
|
response=json.dumps(respdict),
|
|
status=200,
|
|
mimetype='application/json'
|
|
)
|
|
return response
|
|
|
|
@app.route('/api/heartbeat', methods = ['GET','POST'])
|
|
def heartbeat():
|
|
global source
|
|
if request.method == 'POST':
|
|
key = request.form.get('key')
|
|
if key == API_SECRET:
|
|
if request.form.get('message') is not None:
|
|
source.last_msg = float(request.form.get('message'))
|
|
else:
|
|
source.last_msg = "nodata"
|
|
source.status = "unknown"
|
|
|
|
post_response = app.response_class(
|
|
status=200)
|
|
return post_response
|
|
else:
|
|
err_response = app.response_class(
|
|
status=401)
|
|
return err_response
|
|
|
|
if request.method == 'GET':
|
|
if (time.time() - source.last_msg) > 180:
|
|
source.status = "dead"
|
|
else:
|
|
source.status = "alive"
|
|
|
|
resp_data = {'status': source.status, 'last_msg': source.last_msg}
|
|
get_response=app.response_class(
|
|
response=json.dumps(resp_data),
|
|
status=200,
|
|
mimetype='application/json'
|
|
)
|
|
return get_response
|
|
|
|
if __name__ == "__main__":
|
|
app.run()
|