在ros里面,是有专门的工具帮忙做这一步的,但是ros2里面还没有,不过我看论坛上大家更加推荐使用代码的形式做数据传输。
我使用的是python的paho这个包,首先需要安装
pip install paho
我这里贴两个代码,分别是publisher和subscriber,也就是发布者和订阅者。
1. publisher
import time
import paho.mqtt.client as mqtt
class Publisher:
def __init__(self, host="127.0.0.1", port=1883, topic="test_channel"):
self.host = host
self.port = port
self.topic = topic
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.on_publish = self.on_publish
def on_connect(self, client, userdata, flags, rc):
print("Connected with result code "+str(rc))
def on_publish(self, client, userdata, mid):
print("Message Published ...")
def start(self, msg="Hello MQTT", times=10, delay=1):
self.client.connect(self.host, self.port, 60)
self.client.loop_start()
for i in range(times):
time.sleep(delay)
self.client.publish(self.topic, f"{msg} {i}")
if __name__ == "__main__":
publisher = Publisher()
publisher.start()
2. subscriber
import paho.mqtt.client as mqtt
class Subscriber:
def __init__(self, host="127.0.0.1", port=1883, topic="test_channel"):
self.host = host
self.port = port
self.topic = topic
self.msg_count = 0
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
def on_connect(self, client, userdata, flags, rc):
print("Connected with result code "+str(rc))
self.client.subscribe(self.topic)
def on_message(self, client, userdata, msg):
self.msg_count += 1
print(f"Message {self.msg_count}: {msg.topic} {str(msg.payload)}")
def start(self):
self.client.connect(self.host, self.port, 60)
self.client.loop_forever()
if __name__ == "__main__":
subscriber = Subscriber()
subscriber.start()
可以在跟mosquitto所在的同一台机器上运行上面两个脚本,否则就要修改代码中的host为mosquitto实际的IP地址,还要确保网络没有限制。
测试的时候,要先运行subscriber,然后再运行publisher,否则subscriber很可能接受不到数据。
全部0条评论
快来发表一下你的评论吧 !