mqtt和ros1之间的快速转换
笔者使用的是自定义的机器人分布式开发框架,要对及ROS ,所以用到了 mqtt 转ROS 。
安装包
安装paho-mqtt
pip install paho-mqtt
安装ROS1 Python库
sudo apt-get install python-rospy
编写python程序监听 mqtt的消息 ,并转换成 ROS的消息格式发布出去。
mqtt_cmdvel.py
#!/usr/bin/env python
import paho.mqtt.client as mqtt
import rospy
import json
from geometry_msgs.msg import Twist
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
def on_message(client, userdata, msg):
# 将mqtt格式转换为ROS1格式
if (msg.topic == "/cms/vel"):
data = json.loads(msg.payload.decode("utf-8"))
linear = data['vel']
angular = data['ang']
twist = Twist()
twist.linear.x = float(linear)
twist.angular.z = float(angular)
# 发布到ROS1主题
pub.publish(twist)
if __name__ == '__main__':
# 初始化ROS1节点
rospy.init_node('mqtt_twist')
# 创建ROS1发布者
pub = rospy.Publisher('turtle1/cmd_vel', Twist, queue_size=10)
# 创建mqtt客户端
client = mqtt.Client()
# 设置回调函数
client.on_connect = on_connect
client.on_message = on_message
# 连接mqtt代理
client.connect("127.0.0.1", port=1883)
# 订阅mqtt主题 来自客户端 网页 第三方
client.subscribe("/cmd/vel")
# 循环等待mqtt消息
client.loop_forever()
接着执行指令
cd catkin_ws/src
catkin_create_pkg mqtt_cmddev rospy std_msgs geometry_msgs
将上述mqtt_cmdvel.py 放到创建的scripts 文件夹下
lid@lid-VirtualBox:~/catkin_ws/src$ tree -L 3
.
├── CMakeLists.txt -> /opt/ros/melodic/share/catkin/cmake/toplevel.cmake
└── mqtt_cmddev
├── CMakeLists.txt
├── package.xml
├── scripts
│ └── mqtt_cmdvel.py
└── src
修改CMakeLists.txt
## in contrast to setup.py, you can choose the destination
catkin_install_python(PROGRAMS
scripts/mqtt_cmdvel.py
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
返回到 catkin_ws 下 执行指令
catkin_make -DPYTHON_EXECUTABLE=/usr/bin/python3
成功编译后,source ~/catkin_ws/devel/setup.bash