import RPi.GPIO as GPIO from flask import Flask, render_template, request from src.pins import pins_out, pins_in, pins_pwm, freq kamera_server = Flask(__name__) GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # Create a dictionary called pins to store the pin number, name, and pin state: pins = { 2 : {'name' : 'GPIO 2', 'state' : GPIO.HIGH}, 3 : {'name' : 'GPIO 3', 'state' : GPIO.HIGH} } # Set each pin as an output and make it low: for pin in pins_out: GPIO.setup(pins_out[pin]['nr'], GPIO.OUT) GPIO.output(pins_out[pin]['nr'], GPIO.HIGH) for pin in pins_in: GPIO.setup(pins_in[pin]['nr'], GPIO.IN) for key, value in pins_pwm.items(): value['pwm'].start(0) value['pwm'].ChangeFrequency(freq) value['pwm'].ChangeDutyCycle(0) @kamera_server.route("/") def main(): # For each pin, read the pin state and store it in the pins dictionary: for pin in pins_out: pins_out[pin]['state'] = GPIO.input(pins_out[pin]['nr']) for pin in pins_in: pins_in[pin]['state'] = GPIO.input(pins_in[pin]['nr']) # Put the pin dictionary into the template data dictionary: templateData = { 'pins' : pins_out, 'pins_in' : pins_in } # Pass the template data into the template main.html and return it to the user return render_template('main.html', **templateData) # The function below is executed when someone requests a URL with the pin number and action in it: @kamera_server.route("//") 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_out: pins_out[pin]['state'] = GPIO.input(pins_out[pin]['nr']) for pin in pins_in: pins_in[pin]['state'] = GPIO.input(pins_in[pin]['nr']) # Along with the pin dictionary, put the message into the template data dictionary: templateData = { 'pins' : pins_out, 'pins_in' : pins_in } return render_template('main.html', **templateData) if __name__ == "__main__": kamera_server.run(host='0.0.0.0')