2015-12-24 48 views
1

我是Python新手。 我有一個線程回調代碼在我的raspi上正常工作。Python:線程回調不能用守護進程模式?

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) 

如果我開始一個無限循環這樣的:

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 

它的工作原理。

但是,如果我用守護進程「守護進程」它,我的線程回調不再工作。

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 

我在做什麼錯?它是一個守護進程的事實改變了我應該寫我的線程回調的方式嗎?

+0

您是否嘗試其他方法來守護進程?......例如'os.fork' –

+0

是否通過這個'self.pidfile_path ='/ var/run/aquamonitor.pid'來守護進程? –

+0

嗨,對於遲到的回答感到抱歉。不,我只是嘗試守護進程庫。守護進程本身由daemon_runner踢。 – kameo

回答

1

我有同樣的問題,我想我正在註冊回調到錯誤的線程。因此,長話短說,確保GPIO.add_event_detect在應用程序類的run方法內部,就在循環之前調用。