twisted python通过GPIO发送消息,直到按下enter键才会接收到该消息

2024-06-25 06:29:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于twisted python的问题无法解决。在

GPIO.add_event_detect(24, GPIO.RISING, callback=pDetected, bouncetime=1000)

def pDetected(channel):
    communicator.sendNotifications(factory)

class notification(Protocol):
    def connectionMade(self):
        print "connection made but not added"

    def connectionLost(self, reason):
        self.factory.clients.remove(self)

    def dataReceived(self, data):
        lineMessage = data.split('|')
        theCommand = lineMessage[0]
        theContent = lineMessage[1]

        if theCommand == "welcome":
            self.name = theContent
            self.factory.clients.append(self)
            print self.name + " has joined"

        elif theCommand == "msg":
            for c in self.factory.clients:
                c.message(msg)

        elif theCommand == "stopreactor":
            reactor.stop()

    def message(self, msgToSend):
        msgToSend += " \r\n"
        self.transport.write(msgToSend)

    def sendNotifications(self, theFactory):
        for c in theFactory.clients:
            c.message("notify " + c.name)

factory = Factory()
factory.protocol = notification
factory.clients = []
communicator = notification()

reactor.listenTCP(myPort, factory)
reactor.run()

notification类中的所有功能都正常—客户端可以连接,并且可以使用telnet毫无问题地发送/接收消息。在

当事件pDetected被触发时,对pDetected的回调起作用。它发送消息(notify);但是,telnet会话在我按下enter键之前不会接收消息。。。每一次。在按下enter键之前,其他客户机都不会看到该消息。我在端口上运行了一个分析器,数据不在缓冲区中。在

有人能指出我做错了什么吗?我希望触发GPIO事件并向每个连接到服务器的客户机发送消息。在

感谢任何帮助。。。谢谢。在


Tags: nameself消息messagegpiofactorydefnotification
1条回答
网友
1楼 · 发布于 2024-06-25 06:29:44

根据this documentation,传递给GPIO.add_event_detect的回调是一个“线程回调”——意思是,它在一个新线程上运行。在

从非主线程调用随机扭曲API是未定义的-您将得到随机行为。到目前为止,您看到的是需要向它发送一个新消息来取消主循环,但是其他事情也可能发生,包括挂起和崩溃。在

解决此问题的方法是使用^{},如下所示:

def pDetected(channel):
    reactor.callFromThread(communicator.sendNotifications, factory)

GPIO.add_event_detect(24, GPIO.RISING, callback=pDetected, bouncetime=1000)

相关问题 更多 >