Search code examples
pythonflaskraspberry-piwebservercron

Light a LED with a Raspberry Pi when a call is made to a web service (Flask, python)


Each time a call is made on a web service on our backend, I want to blink a LED.

It's working, but only for few hours, after that, it just stops working.

Each time we post on this URL (http://IP_ADRESS:PORT/scan), our LED is blinking.

I'm wondering why, after a certain amount of time it stops working..

Here is the code called when a POST is done:

@app.route('/scan', methods = ['POST'])
def scan():
    time.sleep(0.5)
    try:
            LED.rainbow()        
    finally:
           print("Scanned")
    return 'Scanned!!!'

The LED.rainbow() code can be found here. The code of the whole project can be found here.

When it stops working, I connect via ssh on the raspberry Pi and I do:

python
>>> import app
>>> app.scan()

And this make the LED blinking!! I don't understand why it's working with ssh and not via the http POST.

At the beginning, I thought the Flask server was crashed, but when I try to call it via CURL, everything is fine:

$ http -f POST http://IP_ADDRESS:PORT/scan
HTTP/1.0 200 OK
Content-Length: 13
Content-Type: text/html; charset=utf-8
Date: Thu, 02 Jun 2016 20:11:02 GMT
Server: Werkzeug/0.11.9 Python/2.7.9

Scanned!!!

Here is how I launch my Flask server on the raspberry Pi:

$ sudo crontab -e
# Add this line at the end of the file
@reboot python /home/pi/Desktop/Claudie/app.py &

What am I missing?

Any help is appreciate!

Thanks!


Solution

  • Found the bug!

    The problem is in the rainbow() function.

    This function is called severals time, and at a certain time, it stops working.

    Here is what the function do:

    def rainbow():
        RED, GREEN, BLUE = initializeGPIO() # setup the GPIO, outputs, and PWM
    
        # Light the LED
    
        GPIO.cleanup()
    

    I noticed that calling this function in a loop (without the web server) stops working.

    So I removed the cleanup() and initializeGPIO(), and now everything is working perfectly :) I don't really know why initializing the GPIO (or cleanup) makes the LED stop working, if someone knows, I'll be happy to read it!