在ros里面,是有專(zhuān)門(mén)的工具幫忙做這一步的,但是ros2里面還沒(méi)有,不過(guò)我看論壇上大家更加推薦使用代碼的形式做數(shù)據(jù)傳輸。
我使用的是python的paho這個(gè)包,首先需要安裝
pip install paho
我這里貼兩個(gè)代碼,分別是publisher和subscriber,也就是發(fā)布者和訂閱者。
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所在的同一臺(tái)機(jī)器上運(yùn)行上面兩個(gè)腳本,否則就要修改代碼中的host為mosquitto實(shí)際的IP地址,還要確保網(wǎng)絡(luò)沒(méi)有限制。
測(cè)試的時(shí)候,要先運(yùn)行subscriber,然后再運(yùn)行publisher,否則subscriber很可能接受不到數(shù)據(jù)。
-
數(shù)據(jù)傳輸
+關(guān)注
關(guān)注
9文章
1976瀏覽量
65036 -
python
+關(guān)注
關(guān)注
56文章
4813瀏覽量
85316 -
MQTT
+關(guān)注
關(guān)注
5文章
657瀏覽量
22966
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
使用slavefifosync2bit與FPGA進(jìn)行數(shù)據(jù)傳輸時(shí),服務(wù)間隔是多少?
ADS1299與STM32f407通過(guò)SPI進(jìn)行數(shù)據(jù)傳輸的時(shí)候,可以直接使用HAL庫(kù)中的HAL_SPI_Receive函數(shù)進(jìn)行數(shù)據(jù)傳輸嗎?
請(qǐng)問(wèn)ldc1000在與主機(jī)進(jìn)行數(shù)據(jù)傳輸的過(guò)程中,數(shù)據(jù)傳輸速率設(shè)置為多大合適?
怎么用LABVIEW和FPGA控制W5300進(jìn)行數(shù)據(jù)傳輸
求助各位大神,51單片機(jī)如何通過(guò)藍(lán)牙與fpga進(jìn)行數(shù)據(jù)傳輸
關(guān)于EDMA PingPong傳輸和并行傳輸,請(qǐng)問(wèn)對(duì)于PingPong模式的數(shù)據(jù)傳輸,是否只是用一個(gè)channel進(jìn)行數(shù)據(jù)傳輸?
用E90-DTU進(jìn)行數(shù)據(jù)傳輸,怎么將數(shù)據(jù)傳到后臺(tái)轉(zhuǎn)化
如何通過(guò)單一數(shù)據(jù)線進(jìn)行數(shù)據(jù)傳輸?
如何通過(guò)SPI與單片機(jī)進(jìn)行數(shù)據(jù)傳輸?
如何去實(shí)現(xiàn)串口開(kāi)啟DMA進(jìn)行數(shù)據(jù)傳輸
DMA進(jìn)行數(shù)據(jù)傳輸和CPU進(jìn)行數(shù)據(jù)傳輸的疑問(wèn)
HT56R678使用I2C進(jìn)行數(shù)據(jù)傳輸的方法
HT56R678使用I2C進(jìn)行數(shù)據(jù)傳輸的方法
STM32CubeMX-串口開(kāi)啟DMA進(jìn)行數(shù)據(jù)傳輸

評(píng)論