我已经用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