Home > front end >  IoT Python application architecture with Flask on Raspberry Pi
IoT Python application architecture with Flask on Raspberry Pi

Time:12-01

I've started working with Raspberry Pi and I've faced with architecture problem. I want to make python app which blink the LED using GPIO and have Web interface to start and stop blinking. In the Web there are a lot of examples of how to use Flask to make one action (e.g. enable LED, disable LED etc.) but I haven't found example how to run Flask web server and also run parallel "job" to blink LED or in general to run action by timer.

One solution is to have different applications for that 2 purposes. One for blinking. And one for Flask server. But this approach requires a database to share data between applications, I wouldn't like to do it in IoT device (Raspberry Pi). So I'd prefer single monolitic app.

Could anyone help me with idea how to run action by timer within Flask application? Here is pseudocode to show what I expect.

# main.py

import time
import Flask
import RPi.GPIO as GPIO 

GPIO.setmode(GPIO.BOARD)
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW)

app = Flask()

def blinking():
    while True: # Run forever
        GPIO.output(8, GPIO.HIGH) # Turn on
        time.sleep(1)             # Sleep for 1 second
        GPIO.output(8, GPIO.LOW)  # Turn off
        time.sleep(1)


if __name__ == 'main':
    app.run_in_background()
    blinking()

Thanks for any ideas!

CodePudding user response:

If I understand it right, you are looking for something running in the background;

The main idea behind this would be creating a thread or a task that runs in the background that checks a flag to either go into blinking mode or turn it off. Basically the flask endpoint would just set that flag and your background task would check it and act accordingly.

Another option would be Flask schedulers that way you can schedule how and when to run those tasks.

How can I add a background thread to flask?

Also threadpool executors

flask application with background threads

  • Related