1

I'm new to Python. I've a threaded callback code working fine on my raspi.

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
import time
from daemon import runner

GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)   # float switch goes down (closed to open) => low water level
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)     # float switch goes up (opened to close)  => high water level

def callback_lowlevel(channel):
    if GPIO.input(channel):
        print "Low water level in the sump detected"
    else:
        print "Water level in the sump returned to normal"

def callback_highlevel(channel):
    if GPIO.input(channel):
        print "High water level in the sump detected"
    else:
        print "Water level in the sump returned to normal"

GPIO.add_event_detect(23, GPIO.BOTH, callback=callback_lowlevel, bouncetime=1000)
GPIO.add_event_detect(24, GPIO.BOTH, callback=callback_highlevel, bouncetime=1000)

If I start an infinite loop like this:

try:
    print "Waiting for events"
    while True:
        time.sleep(1)

except KeyboardInterrupt:
    GPIO.cleanup()       # clean up GPIO on CTRL+C exit
GPIO.cleanup()           # clean up GPIO on normal exit

It works.

But if I "daemonize" it with the daemon library, my threaded callbacks are just not working anymore.

class App():                           # Daemon content, not doing much, sleeping mostly, to lower CPU footprint
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/stdout'
        self.stderr_path = '/dev/stdout'
        self.pidfile_path =  '/var/run/aquamonitor.pid'
        self.pidfile_timeout = 5
    def run(self):
        Logger("Starting monitoring")
        while True:
            time.sleep(1)                           # Sleep most of time to be not too CPU intensive
app = App()                                         # Init the App
daemon_runner = runner.DaemonRunner(app)            # Run as a daemon
daemon_runner.do_action()                           # Just do it

What am I doing wrong? Does the fact that it's a daemon changes the way I'm supposed to write my threaded callbacks?

kameo
  • 11
  • 1

1 Answers1

1

I had the same issue and I figured I was registering the callback to the wrong thread. So, long story short, be sure that GPIO.add_event_detect is called from within the run method of your App class, just before the loop.