mqtt和ros1之间的快速转换2 一包两节点

笔者使用的是自定义的机器人分布式开发框架,要对及ROS ,所以用到了 mqtt 转ROS 。
安装包

安装paho-mqtt
pip install paho-mqtt

安装ROS1 Python库
sudo apt-get install python-rospy

编写python程序监听 mqtt的消息 ,并转换成 ROS的消息格式发布出去。在上一篇文章中提到

mqtt_cmdvel.py 且已经实现。
本篇增加 ,从ros中订阅位姿 并通过MQTT 发送出去
编写 pose_subscibe.py

import paho.mqtt.client as mqtt
import rospy
import json
from geometry_msgs.msg import Twist

#MQTT相关
broker = '127.0.0.1'
#broker = 'www.woyilian.com'
port = 1883
odomxyz_topic = "/odom/xyz" 
raw_odom_topic ="/sensors/odom"
bno_topic = "/sensors/bno085"

client_id = 'python-mqtt-{}'.format(random.randint(0, 1000))
#控制指令topic 
cmd_vel_topic = "/cmd/vel"
#定义mqtt的client
client = mqtt_client.Client(client_id)
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

def mycallback(data):
    # 将ROS1格式转换为mqtt格式
    mqtt_message = "{},{}".format(data.linear.x, data.angular.z)
    # 发布到mqtt主题
    client.publish(topic="/pose/xyz", payload=mqtt_message)

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)
    # 订阅ROS1主题
    sub = rospy.Subscriber("turtle1/cmd_vel", Twist, mycallback)
    # 创建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()
    # 循环等待ROS1消息
    rospy.spin()

目录结构变成这样

修改Cmakelists.txt

返回到,catkin_src 下 catkin_make
source bash 后

微信截图_20230423164833.png

就可以指定节点运行了。
rosrun mqtt_cmddev mqtt_cmdvel.py
rosrun mqtt_cmddev pose_subscribe.py

sitemap