我已經用Python做了一個家庭安全程序,它使用Raspberry Pi的GPIO來感應移動並啓動警笛。用戶使用NFC標籤激活/停用系統,也可以連接到樹莓派。從另一個線程調用一個扭曲的協議方法
爲此,我需要不間斷地檢查nfc標籤,同時不斷檢查傳感器的運動是否阻塞。我需要更多並行的東西來做,但我認爲這兩點足以說明我的觀點。
現在我使用的線程,我開始/停止像這樣 - Stopping a thread after a certain amount of time - 我不知道這是否是最佳的方式,但到目前爲止系統工作正常。
現在我想擴展它的功能來通過websockets提供通知。我發現,這可以用雙絞線來實現,但我很困惑..
下面是我如何試圖做到這一點的例子代碼:
from twisted.internet import reactor
from autobahn.websocket import WebSocketServerFactory, \
WebSocketServerProtocol, \
listenWS
def thread1(stop_event):
while(not stop_event.is_set()):
stop_event.wait(4)
print "checking sensor"
# sensor_state = GPIO.input(11)
if sensor_state == 1:
# how can I call send_m("sensor detected movement") #<---
t1_stop_event.set()
t1_stop_event = Event()
t1 = Thread(target=thread1, args=(t1_stop_event,))
class EchoServerProtocol(WebSocketServerProtocol):
def onMessage(self, msg, binary):
print "received: "+msg
print "stopping thread1"
t1_stop_event.set()
def send_m(self, msg):
self.sendMessage(msg)
if __name__ == '__main__':
t1.start()
factory = WebSocketServerFactory("ws://localhost:9000")
factory.protocol = EchoServerProtocol
listenWS(factory)
reactor.run()
所以,我怎麼能叫的發送方法服務器協議從一個線程像thread1?
這是一個非常明確的答案非常感謝你!我想這可能會回答我的問題,我會在幾天內檢查它,當我回到這個項目。我希望這不是一個問題,如果我推遲了幾天*答覆*按鈕.. – kapcom01