Flask Server with GPIOs

Let’s say that you have a running Flask server and you want your user to control the state (on/off) of an LED via the GPIO. The following technique shows how to connect Flask server with a separate GPIO script using PID.

Download the whole project

Run the following two scripts at the same time using the terminal:

from flask import *
import os
import signal

app = Flask(__name__)

#create a route path for index page
@app.route("/")
def index():
    return render_template("index.html")

#create a route path for about page
@app.route("/about")
def about():

    if 'name' in session: #if session 'name' exists
        print(session['name']) #print what's inside session[name]

        session.pop('name',None) #after printing, delete session name

    return render_template("aboutus.html") #render the html template aboutus

#/students accepts a get and post requests
@app.route("/student",methods=['GET','POST'])
def student():
    if(request.method == 'POST'): #if user fills a form
        studentName = request.form['studentname']
        if(studentName == "jimmy"):
            session["name"] = studentName #create session, name it 'name' and fill with studentName
            return redirect(url_for("about")) #redirect to about page
        else:
            return render_template("student.html") #render student template

    else:
        return render_template("student.html")#render student template

#routes with paramaters
@app.route("/led")
@app.route("/led/<param>")
def led(param=None):
    if(param == "on"): #if paramater is /led/on
        #read process id from text file generated by ledscript.py
        fh=open("processid.txt","r")
        processId = int(fh.read()) #load the process id
        fh.close()

        fh=open("led.txt","w")
        fh.write("1") #save 1 in text file. 1 means LED ON. 0 means LED Off
        fh.close()

        #send signal to process id
        os.kill(processId, signal.SIGUSR1)
        return "LED ON"
    elif(param =="off"): # if paramater is /led/off
        #read process id from text file
        fh=open("processid.txt","r")
        processId = int(fh.read())
        fh.close()

        fh=open("led.txt","w")
        fh.write("0")
        fh.close()

        #send signal to process id (ledscript)
        os.kill(processId, signal.SIGUSR1)
        return "LED OFF"
    else:
        return "LED MAIN PAGE"

if __name__ == "__main__":
    app.secret_key = 'asdfd!45sdf' #create secret key to secure sessions
    app.run(debug=True, host = "0.0.0.0")

import RPi.GPIO as GPIO
import time
import traceback
import os
import signal

def Main():
    try:
        #when scripts runs create processid.txt
        fh=open("processid.txt","w")
        fh.write(str(os.getpid())) #get current process id and store in file
        fh.close()

        GPIO.setmode(GPIO.BCM)

        GPIO.setwarnings(False)

        GPIO.setup(4, GPIO.OUT, initial = GPIO.LOW) #setup GPIO4 to low

        def handUSR1(signum,frame): #this function is automatically triggered from flask
            fh=open("led.txt","r")
            led = int(fh.read())
            fh.close()

            if(led == 0): #if 0 is found in text file
                print("LED OFF") #turn off led
                GPIO.output(4,GPIO.LOW)
            else:
                print("LED ON") #if not 0 (1) is found in text file
                GPIO.output(4,GPIO.HIGH) #turn on led

        signal.signal(signal.SIGUSR1,handUSR1) #callback function for SIGUSR1 signal (from flask when kill command is given)

        while(True):
            time.sleep(1)

    except Exception as ex:
        traceback.print_exc()
    finally:
        GPIO.cleanup() #this ensures a clean exit

Main()

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s