我正在创建一个机器人,它将由通过TCP连接接收的命令驱动。因此,我将有一个robot类,其中包含方法(例如sense()、drive()…)和用于TCP连接的类。在
为了建立TCP连接,我查看了twisted中的示例。在客户端,我写了一个客户端.py连接处理脚本:from twisted.internet import reactor, protocol
import random
from eventhook import EventHook
import common
#from Common.socketdataobjects import response
# a client protocol
class EchoClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.transport.write("hello, world!")
#the server should be notified that the connection to the robot has been established
#along with robot state (position)
#eventConnectionEstablishedHook.fire()
def dataReceived(self, data):
print "Server said:", data
self.transport.write("Hello %s" % str(random.randint(1,10)))
'''
serverMessage = common.deserializeJson(data)
command = serverMessage.command
arguments = serverMessage.arguments
#here we get for example command = "DRIVE"
#arguments = {motor1Speed: 50, motor2Speed: 40}
instead of above response, used for testing purposes,
the commands should be extracted from the data and according to the command,
the method in Robot instance should be called.
When the command execution finishes, the self.transport.write() method should be called
to notify the server that the command execution finished
'''
def connectionLost(self, reason):
print "connection lost"
class EchoFactory(protocol.ClientFactory):
protocol = EchoClient
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def initializeEventHandlers(connectionEstablishedHook):
global connection
connection.established = 0
global eventConnectionEstablishedHook
eventConnectionEstablishedHook = connectionEstablishedHook
def main():
f = EchoFactory()
reactor.connectTCP("localhost", 8000, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
除了这个脚本,我还有一个机器人类:
^{pr2}$
我想做的是从TCP连接接收数据(命令),然后在Robot实例中调用相应的方法。有些过程可能需要更长的时间(例如驾驶),因此我尝试使用事件,但还没有找到TCP客户端和robot之间使用事件进行通信的适当方式:if __name__ == '__main__':
robotController = Robot()
eventController = Controller()
connectionEstablishedHook = EventHook()
client.initializeEventHandlers(connectionEstablishedHook)
eventController.connection = connectionEstablishedHook
client.main()
我试图创建clientmain程序脚本,在这里我想创建一个robot实例,一个TCP客户机实例,并使用事件实现它们之间的通信。在
以前,我在一个简单的例子中使用Michael Foord's events pattern实现了事件处理。如果有人能提供这个问题的解决方案或任何类似的例子来帮助解决这个问题,我将非常感谢。在