#!/usr/bin/env python3 import json import time import paho.mqtt.client as mqtt BROKER_ADDRESS = "192.168.1.12" #BROKER_ADDRESS = "192.168.1.33" # # Don't use a wild card or you risk looping. # TOPICS = [f"cfos_mqtt/get/M{i}" for i in [3, 8, 11, 15]] def extract_data_topic(client, data, topic): client.publish(topic + "/back/power_w", data["power_w"]) if topic == TOPICS[1]: client.publish(topic + "/back/soc", data["soc"]) def on_message(client, _userdata, message): extract_data_topic( client, json.loads(message.payload.decode("utf-8")), message.topic ) def on_connect(client, userdata, flags, rc): if rc==0: for topic in TOPICS: client.subscribe(topic) def main(): #client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, "YUN-Sensor") client = mqtt.Client("YUN") client.on_connect = on_connect client.on_message = on_message client.username_pw_set(username="yourusername", password="yourpassword") print("Connecting to broker", BROKER_ADDRESS) client.connect(BROKER_ADDRESS) client.loop_start() while True: time.sleep(1) if __name__ == "__main__": main()