[英]MQTT: Python script should subscribe to subtopics
我們正在開發一個項目,其中一些傳感器將數據發送到 mqtt 代理,我們編寫了一個 python 腳本,該腳本獲取這些數據並將其存儲在 csv 文件中。
現在,當我們添加更多傳感器時,我們的主題會發生如下變化:
主題/傳感器1
主題/傳感器2
等等。 現在,我們希望在此腳本中自動化子主題,以便在添加或刪除傳感器時不對其進行硬編碼。
您有什么建議,我們如何循環訂閱所有子主題?
到目前為止,我們有以下內容:
import paho.mqtt.client as mqtt
import logging
from datetime import datetime
def on_subscribe(mosq, obj, mid, granted_qos):
print("Subscribed: " + str(mid))
def on_log(client, userdata, level, buf):
print(buf)
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("envdata/#")
def on_message(client, userdata, msg):
f = open("log.csv", "a")
msg_decoded = str(msg.payload, 'utf-8')
msg_decoded = msg_decoded.replace("\n","")
msg_decoded = msg_decoded + "\ttime:" + datetime.now().strftime("%d/%m/%Y %H:%M:%S") + "\n"
f.write(msg_decoded)
f.close()
print(msg.topic+" "+msg_decoded)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.on_log = on_log
client.on_subscribe = on_subscribe
client.username_pw_set(user, password=password)
client.connect(url, 1883, 60)
client.loop_forever()
我們想通了。 因此,當我們使用client.subscribe("topic/#")
訂閱每個子主題時,我們可以使用msg.topic
訪問on_message
回調中的所有主題。
現在我們可以將此主題存儲在代表.csv
文件的字符串中。 所以我們的on_message
回調現在如下所示:
def on_message(client, userdata, msg):
filename = msg.topic
filename = filename.replace("/","-")
f = open(filename + ".csv", "a")
msg_decoded = str(msg.payload, 'utf-8')
msg_decoded = msg_decoded.replace("\n","")
msg_decoded = msg_decoded + "\ttime:" + datetime.now().strftime("%d/%m/%Y %H:%M:%S") + "\n"
f.write(msg_decoded)
f.close()
print(msg.topic+" "+msg_decoded)
這對於我們希望使用此腳本達到的效果很好。 現在,當腳本識別出新消息時,它會打開或創建一個類似topic-subtopic.csv
的文件,並用預期的數據填充它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.