У меня проблема с получением правильной настройки для извлечения данных из базы данных.
Мне нужно извлечь данные за последние 10 минут и поместить их в диаграмму.У меня есть 2 проблемы с этим, я не могу заставить аргументы работать, чтобы получить определенный период времени (последние 10 минут), но мне удалось просто захватить последние 600 записей.
, что работает, номоя ось X диаграммы неверна, и я не могу найти способ инвертировать данные в таблице после того, как вытащил их из базы данных.(последнее чтение слева, а затем стареет, когда вы идете дальше вправо на графике)
код, который я использую в данный момент, таков (да, он уродлив и заимствован у всех), но я надеюсь, что вы можете посмотреть мимоэто потому, что я впервые пишу что-то подобное.
#!/usr/bin/env python
import sqlite3
import sys
import cgi
import cgitb
import time
global variables
speriod=(15)-1
dbname='/var/www/sensors.db'
def printHTTPheader():
print "Content-type: text/html\n\n"
def printHTMLHead(title, table):
print "<head>"
print " <title>"
print title
print " </title>"
print_graph_script(table)
print "</head>"
#current_time=time.time()
def get_data(interval):
conn=sqlite3.connect(dbname)
curs=conn.cursor()
if interval == None:
curs.execute("SELECT * FROM readings")
else:
# curs.execute("SELECT * FROM readings")
curs.execute("SELECT * FROM readings ORDER BY timestamp DESC LIMIT "+str(600))
# curs.execute("SELECT * FROM readings WHERE time>=datetime('now','%s minutes')" % interval)
rows=curs.fetchall()
conn.close()
return rows
def create_table(rows):
chart_table=""
for row in rows[:-4]:
rowstr="['{0}', {1}],\n".format(str(row[2]),str(row[5]))
chart_table+=rowstr
row=rows[-1]
rowstr="['{0}', {1}]\n".format(str(row[2]),str(row[5]))
chart_table+=rowstr
return chart_table
def print_graph_script(table):
chart_code="""
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['windspeed', 'temperature'],
%s
]);
var options = {
title: 'windspeed'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>"""
print chart_code % (table)
def show_graph():
print "<h2>Windspeed Chart</h2>"
print '<div id="chart_div" style="width: 900px; height: 500px;"></div>'
def show_stats(option):
conn=sqlite3.connect(dbname)
curs=conn.cursor()
if option is None:
option = str(24)
curs.execute("SELECT timestamp,max(windspeed) FROM readings WHERE time>date('now','-%s hour') AND time<=date('now')" % option)
# curs.execute("SELECT timestamp,max(windspeed) FROM readings WHERE timestamp>datetime('2013-09-19 21:30:02','-%s hour') AND timestamp<=datetime('2013-09-19 21:31:02')" % option)
rowmax=curs.fetchone()
rowstrmax="{0}   {1}C".format(str(rowmax[0]),str(rowmax[1]))
curs.execute("SELECT timestamp,min(windspeed) FROM readings WHERE timestamp>time('time','-%s hour') AND timestamp<=time('current_time')" % option)
# curs.execute("SELECT timestamp,min(temp) FROM temps WHERE timestamp>datetime('2013-09-19 21:30:02','-%s hour') AND timestamp<=datetime('2013-09-19 21:31:02')" % option)
rowmin=curs.fetchone()
rowstrmin="{0}   {1}C".format(str(rowmin[0]),str(rowmin[1]))
curs.execute("SELECT avg(windspeed) FROM readings WHERE timestamp>time('now','-%s hour') AND timestamp<=time('current_time')" % option)
# curs.execute("SELECT avg(temp) FROM temps WHERE timestamp>datetime('2013-09-19 21:30:02','-%s hour') AND timestamp<=datetime('2013-09-19 21:31:02')" % option)
rowavg=curs.fetchone()
print "<hr>"
print "<h2>Minumum temperature </h2>"
print rowstrmin
print "<h2>Maximum temperature</h2>"
print rowstrmax
print "<h2>Average temperature</h2>"
print "%.3f" % rowavg+ "C"
print "<hr>"
print "<h2>In the last hour:</h2>"
print "<table>"
print "<tr><td><strong>Date/Time</strong></td><td>
<strong>Temperature</strong></td></tr>"
rows=curs.execute("SELECT * FROM readings WHERE timestamp>datetime('now','-1 hour') AND timestamp<=datetime('now')")
# rows=curs.execute("SELECT * FROM temps WHERE timestamp>datetime('2013-09-19 21:30:02','-1 hour') AND timestamp<=datetime('2013-09-19 21:31:02')")
for row in rows:
rowstr="<tr><td>{0}  </td><td>{1}C</td></tr>".format(str(row[0]),str(row[1]))
print rowstr
print "</table>"
print "<hr>"
conn.close()
def print_time_selector(option):
print """<form action="/cgi-bin/webgui.py" method="POST">
Show the temperature logs for
<select name="timeinterval">"""
if option is not None:
if option == "6":
print "<option value=\"6\" selected=\"selected\">the last 6 hours</option>"
else:
print "<option value=\"6\">the last 6 hours</option>"
if option == "12":
print "<option value=\"12\" selected=\"selected\">the last 12 hours</option>"
else:
print "<option value=\"12\">the last 12 hours</option>"
if option == "24":
print "<option value=\"24\" selected=\"selected\">the last 24 hours</option>"
else:
print "<option value=\"24\">the last 24 hours</option>"
else:
print """<option value="6">the last 6 hours</option>
<option value="12">the last 12 hours</option>
<option value="24" selected="selected">the last 24 hours</option>"""
print """ </select>
<input type="submit" value="Display">
</form>"""
def validate_input(option_str):
if option_str.isalnum():
if int(option_str) > 0 and int(option_str) <= 24:
return option_str
else:
return None
else:
return None
def get_option():
form=cgi.FieldStorage()
if "timeinterval" in form:
option = form["timeinterval"].value
return validate_input (option)
else:
return None
def main():
cgitb.enable()
option=get_option()
if option is None:
option = str(24)
records=get_data(option)
printHTTPheader()
if len(records) != 0:
table=create_table(records)
else:
print "No data found"
return
print "<html>"
printHTMLHead("Raspberry Pi Wind Logger", table)
print "<body>"
print "<h1>Raspberry Pi Wind Logger</h1>"
print "<hr>"
print_time_selector(option)
show_graph()
show_stats(option)
print "</body>"
print "</html>"
sys.stdout.flush()
if __name__=="__main__":
main()
база данных содержит 7 строк (время Unix, дата, время, скорость ветра, направление, температура, контрольная сумма), данные поступают от ультразвукового датчика ветраЯ хотел бы получить "опции" в этой работе, а также максимальную скорость ветра или среднюю скорость ветра, но я думаю, что это должно стать ясным, как только я пойму, как на самом деле отсортировать время.
edit:
вот чтение, извлеченное из базы данных
1540300313.94403|23/10/2018|21:11:53|0.1|273|24.1|5E*4B
и часть кода для хранения данных в базе данных
cursor.execute('''insert into readings values (?, ?, ?, ?, ?, ?, ?)''',
(timestamp, current_date, current_time, windspeed, direction, temperature, checksum));
dbconnect.commit()