Cant get Flask app and another function to run together using Flask Script

340 views Asked by At

I've got a raspberry pi and I've managed to get to separate elements working independently. On to sense motion and take a picture, another to stream the cameras feed over my local network using Flask.

However i want these to run simultaneously, I've been looking at the Flask Script module and the Manger functionality. I believe i have it setup correctly. However when I run the 'runserver' command nothing actually happens.

Is what I want to do even possible with Flask Script? If it is is my approach correct, or what would be a better solution.

Thanks

Here's is my python script so far:

from importlib import import_module
import os
from flask_script import Server, Manager
from flask import Flask, render_template, Response
from camera import Camera
from gpiozero import MotionSensor
import time

# Code to take a snapshot when motion is detected
def senseMotion():
    pir = MotionSensor(4)

    while True:
        if pir.motion_detected:
            print('Motion detected')
            Camera.snapshot()
            time.sleep(60)

app = Flask(__name__)
manager = Manager(app)


# Flask app to view video stream in browser
@app.route('/')
def index():
    """Video streaming home page."""
    return render_template('index.html')


def gen(camera):
    """Video streaming generator function."""
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
           b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')


@app.route('/video_feed')
def video_feed():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen(Camera()),
                mimetype='multipart/x-mixed-replace; boundary=frame')

@manager.command
def runserver():
    senseMotion()
    app.run(host='0.0.0.0', threaded=True)


if __name__ == "__main__":
    manager.run()

#if __name__ == '__main__':
    #app.run(host='0.0.0.0', threaded=True)
1

There are 1 answers

0
Koxo On

gpiozero.MotionSensor has event when_motion which runs code in different thread.

so use pir = MotionSensor(4)

and

pir.when_motion = MakeSnapshot

Of course you need to define function MakeSnapshot()

Read more about this class: https://gpiozero.readthedocs.io/en/stable/api_input.html#motion-sensor-d-sun-pir