环境:
Win10+python叫它WinPC
虚拟机Ubuntu16.04 + ROS kinetic 叫它RosPC
首先,在RosPC上安装rosbridge suite:
sudo apt-get install -y ros-kinetic-rosbridge-server sudo apt-get install -y ros-kinetic-tf2-web-republisher
在你连接之前,确保服务已经开启:
roslaunch rosbridge_server rosbridge_websocket.launch rosrun tf2_web_republisher tf2_web_republisher
在你的WinPC上安装roslibpy:
pip install roslibpy
简单连接:
我们开始导入roslibpy
如下:
>>> import roslibpy
我们初始化连接(端口默认9090):
>>> ros = roslibpy.Ros(host='localhost', port=9090)
>>> ros.run()
前面的行开始连接但不阻塞,即连接在后台建立,但函数立即将控件返回给程序。
我们来看看状态:
>>> ros.is_connected
True
比较复杂的例子:
建立一个ROS 节点,开始Publish(发送):
import time import roslibpy client = roslibpy.Ros(host='localhost', port=9090) talker = roslibpy.Topic(client, '/chatter', 'std_msgs/String') def start_talking(): while client.is_connected: talker.publish(roslibpy.Message({'data': 'Hello World!'})) print('Sending message...') time.sleep(1) talker.unadvertise() client.on_ready(start_talking) client.run_forever()
如果是接收端:
import roslibpy client = roslibpy.Ros(host='localhost', port=9090) listener = roslibpy.Topic(client, '/chatter', 'std_msgs/String') def start_listening(): listener.subscribe(receive_message) def receive_message(message): print('Heard talking: ' + message['data']) client.on_ready(start_listening) client.run_forever()
做Service的服务器:
import roslibpy client = roslibpy.Ros(host='localhost', port=9090) client.run() client.on_ready(lambda: call_service()) service = roslibpy.Service(client, '/rosout/get_loggers', 'roscpp/GetLoggers') def call_service(): print('Calling service') request = roslibpy.ServiceRequest() service.call(request, success_callback, error_callback) def success_callback(result): print('Service response: ', result['loggers']) def error_callback(result): print('Something went wrong') try: while True: pass except KeyboardInterrupt: pass client.terminate()
但是对于我来说,我在ROS上的代码是C++的,所以我希望在WinPC上用c++来连接ROS。
于是我又用了rosserial_windows.