Commit 954ac304 authored by Kristian Tan's avatar Kristian Tan

Allow control over GPIO

parent b9f892fa
from flask import Flask, render_template
import datetime
# import datetime
import RPi.GPIO as GPIO
app = Flask(__name__)
# Create a dictionary called pins to store the pin number, name, and pin state:
pins = {
24: {'name': 'coffee maker', 'state': GPIO.LOW},
25: {'name': 'lamp', 'state': GPIO.LOW}
25: {'name': 'Light', 'state': 'GPIO.LOW'}
}
#
# Set each pin as an output and make it low:
for pin in pins:
GPIO.setup(pin, GPIO.OUT)
......@@ -20,7 +19,7 @@ for pin in pins:
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)
pins[pin]['state'] = 'GPIO.input(pin)'
# Put the pin dictionary into the template data dictionary:
template_data = {
'pins': pins
......@@ -29,6 +28,30 @@ def main():
return render_template('main.html', **template_data)
# The function below is executed when someone requests a URL with the pin number and action in it:
@app.route("/<change_pin>/<action>")
def action(change_pin, action):
change_pin = int(change_pin)
device_name = pins[change_pin]['name']
if action == "on":
GPIO.output(change_pin, GPIO.HIGH)
message = "Turned " + device_name + " on."
if action == "off":
GPIO.output(change_pin, GPIO.LOW)
message = "Turned " + device_name + " off."
if action == "toggle":
GPIO.output(change_pin, not GPIO.input(change_pin))
message = "Toggled " + device_name + "."
template_data = {
'message': message,
'pins': pins
}
return render_template('main.html', **template_data)
@app.route('/button')
def button():
print("Button press")
......
<!DOCTYPE html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>Hello, World!</h1>
<h2>The date and time on the server is: {{ time }}</h2>
<form action="button">
<button type="submit">Press Button!</button>
<form>
</body>
<head>
<title>Current Status</title>
</head>
<body>
<h1>Device Listing and Status</h1>
{% for pin in pins %}
<p>The {{ pins[pin].name }}
{% if pins[pin].state == true %}
is currently on (<a href="/{{pin}}/off">turn off</a>)
{% else %}
is currently off (<a href="/{{pin}}/on">turn on</a>)
{% endif %}
</p>
{% endfor %}
{% if message %}
<h2>{{ message }}</h2>
{% endif %}
</body>
</html>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment