在python中使用TCP / IP协议创建与其他软件的Webots接口

问题描述

Webots 允许我通过 TCP/IP 协议将我的机器人与其他软件连接。它已经带有一个已实现的示例,但所有代码都在 C 中,我想使用 socket 进行 python 实现。

控制器需要检查客户端是否发送了任何命令,为此我在主循环中放了一个msg = con.recv (1024),但问题是在循环的每次交互中它都停止等待接收一个消息。如何让套接字不锁定循环但仍然能够捕获任何传入消息?

这是 C 服务器实现的链接Link

这是我的问题实现:

import socket
from controller import Robot

robot = Robot()

# get the time step of the current world
timestep = 250
max_speed = 6.28
                
# Enable motors    
left_motor = robot.getMotor('left wheel motor')
right_motor = robot.getMotor('right wheel motor')
            
left_motor.setPosition(float('inf'))
left_motor.setVeLocity(0.0)
            
right_motor.setPosition(float('inf'))
right_motor.setVeLocity(0.0)

right_speed = 0.0
left_speed = 0.0

HOST = '10.0.0.6'             
PORT = 10020           
tcp = socket.socket(socket.AF_INET,socket.soCK_STREAM)
orig = (HOST,PORT)
tcp.bind(orig)
tcp.listen(1)

con,cliente = tcp.accept()
print ('Connected by ',cliente)

# Main loop:
# - perform simulation steps until Webots is stopping the controller
while robot.step(timestep) != -1:
    msg = con.recv(1024)
    txt = msg.decode('UTF-8')

    if txt[0] == "D":      
    
        if float(txt[2]) < max_speed:
            right_motor.setVeLocity(max_speed)
        else:
            print("Very high speed")        
    
        if float(txt[4]) < max_speed:
            left_motor.setVeLocity(max_speed)
        else:
            print("Very high speed ")
            
        
print ('Ending client connection ',cliente)
con.close()

解决方法

您可以设置超时:

tcp.settimeout(0.1)

然后,在while循环中:

try:
  msg = s.recv(1024)
except socket.timeout,e:
  continue

(而不是 msg = con.recv(1024)

使用给定的实现,您的控制器将等待 0.1 秒的数据。如果在 0.1 秒内没有接收到数据,它将简单地跳过并执行一个模拟步骤。