我有一个运行来处理要显示的数据图表和一些gpio控件的webapp烧瓶。所有的功能,如显示来自sqlite db的数据,以及来自按钮的gpio控件完全工作。
下面的代码是我的webapp烧瓶,其中包含许多app-route。我的主要问题是:
所以在我的观点上,如果我们添加一些代码来调用此路由中的索引路径(“/”),它可能会起作用:@ app.route(“//”)。但不幸的是,我有python和烧瓶的经验,在php webserver上可能会工作,但dunno与这种类型的语言。也许你可以给我一些线索?
我的目标是,该页面将能够处理控制gpio(中继)的动作,以及使用matplotlib显示数据的数据
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import io
import RPi.GPIO as GPIO
#import water
from flask import Flask, render_template, send_file, make_response, request
app = Flask(__name__)
import sqlite3
#GPIO NEEDS############################################################
GPIO.setmode(GPIO.BCM)
# Create a dictionary called pins to store the pin number, name, and pin state:
pins = {
13 : {'name' : 'Waterpump 1', 'state' : GPIO.LOW},
19 : {'name' : 'Growlight 2', 'state' : GPIO.LOW}
}
# Set each pin as an output and make it low:
for pin in pins:
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, GPIO.LOW)
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
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])
return dates, temps, hums
def maxRowsTable():
for row in curs.execute("select COUNT(temp) from DHT_data"):
maxNumberRows=row[0]
return maxNumberRows
#initialize global variables
global numSamples
numSamples = maxRowsTable()
if (numSamples > 101):
numSamples = 100
# main route
@app.route("/")
def index():
time, temp, hum = getLastData()
templateData = {
'time' : time,
'temp' : temp,
'hum' : hum,
'numSamples' : numSamples,
'pins' : pins
# 'text' : text
}
return render_template('index.html', **templateData)
#method for gpio########################################################
def main():
# For each pin, read the pin state and store it in the pins dictionary:
for pin in pins:
pins[pin]['state'] = GPIO.input(pin)
# Put the pin dictionary into the template data dictionary:
templateData = {
'pins' : pins
}
# Pass the template data into the template main.html and return it to the user
return render_template('index.html', **templateData)
@app.route('/', methods=['POST'])
def my_form_post():
global numSamples
numSamples = int (request.form['numSamples'])
numMaxSamples = maxRowsTable()
if (numSamples > numMaxSamples):
numSamples = (numMaxSamples-1)
time, temp, hum = getLastData()
templateData = {
'time' : time,
'temp' : temp,
'hum' : hum,
'numSamples' : numSamples
}
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
###APPROUTEGPIO##########################################################
@app.route("/<changePin>/<action>")
def action(changePin, action):
# Convert the pin from the URL into an integer:
changePin = int(changePin)
# Get the device name for the pin being changed:
deviceName = pins[changePin]['name']
# If the action part of the URL is "on," execute the code indented below:
if action == "on":
# Set the pin high:
GPIO.output(changePin, GPIO.HIGH)
# Save the status message to be passed into the template:
message = "Turned " + deviceName + " on."
if action == "off":
GPIO.output(changePin, GPIO.LOW)
message = "Turned " + deviceName + " off."
# For each pin, read the pin state and store it in the pins dictionary:
for pin in pins:
pins[pin]['state'] = GPIO.input(pin)
# Along with the pin dictionary, put the message into the template data dictionary:
templateData = {
'pins' : pins
}
return render_template('index.html', **templateData)
##approutesoil################################################################
#@app.route("/sensor")
#def action():
# status = water.get_status()
# message = ""
# if (status == 1):
# message = "Water me please!"
# else:
# message = "I'm a happy plant"
#
# templateData = template(text = message)
# return render_template('index.html', **templateData)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=False)