简体   繁体   中英

Update payload message from mqtt broker

I have an script where every new value from my mqtt broker gets written into an csv. I subscribed to multiple topics. For now it works for 80% how i want it. To test it i subscribed to 3 topics and i see every topicname in a new line with a value, but not the right one.

def on_message(client, userdata, msg):
    with open(r'file.csv', 'a+', newline='') as f:
        f.write(topic.rsplit('/', 1)[-1] + ' ' + str(msg.payload.decode("utf-8")) + "\n")
    with open(r'file.csv', 'a+', newline='') as f:
        f.write(topic2.rsplit('/', 1)[-1] + ' ' + str(msg.payload.decode("utf-8")) + "\n")
    with open(r'file.csv', 'a+', newline='') as f:
        f.write(topic3.rsplit('/', 1)[-1] + ' ' + str(msg.payload.decode("utf-8")) + "\n")

and the output looks like this in the csv:

ONLINE TRUE
COOLER_MODE TRUE
TOTAL_CURRENTFLOWTIME TRUE
ONLINE AUTO
COOLER_MODE AUTO
TOTAL_CURRENTFLOWTIME AUTO
ONLINE 857.0
COOLER_MODE 857.0
TOTAL_CURRENTFLOWTIME 857.0

it should look like this:

ONLINE TRUE
COOLER_MODE AUTO
TOTAL_CURRENTFLOWTIME 857.0

so how can i update the payload and give it the right topic everytime?

You only need one output line (assuming all the topics have the same pattern)

def on_message(client, userdata, msg):
    with open(r'file.csv', 'a+', newline='') as f:
        f.write(msg.topic.rsplit('/', 1)[-1] + ' ' + str(msg.payload.decode("utf-8")) + "\n")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM