import json from pathlib import Path import paho.mqtt.client as mqtt class MqttManager: def __init__(self, heaters): self.host = "192.168.0.100" self.username = "connorroy" self.password = "arkreactor7" self.object_ids = heaters self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.username_pw_set(username=self.username, password=self.password) self.client.connect(self.host, 1883, 60) self.client.loop_forever() def on_connect(self, client, userdata, flags, reason_code, properties): print(f"Connected with result code {reason_code}") discovery_topic = "homeassistant/climate/" json_payload = self._load_json() for index, i in enumerate(self.object_ids): json_topic = "hmd/climate/" + i["uid"] self.client.publish(topic=discovery_topic + i["uid"] + "/config", qos=0, retain=False, payload=json.dumps(json_payload[index])) for device_index, device in enumerate(self.object_ids): print(json_payload[device_index]["current_temperature_topic"]) self.client.publish(topic=json_payload[device_index]["current_temperature_topic"], qos=0, retain=False, payload=json.dumps(json_payload[index])) # # Subscribing in on_connect() means that if we lose the connection and # # reconnect then subscriptions will be renewed. # client.subscribe("$SYS/#") def on_message(self, client, userdata, msg): print(msg.topic + " " + str(msg.payload)) def publish_discovery(self): discovery_topic = "homeassistant/climate/" for i in self.object_ids: self.client.publish(topic=discovery_topic + i["uid"] + "/config", qos=0, retain=False) def _load_json(self): path = Path(__file__).parent json_list = [] with open(str(path) + "/climate.json") as j: data = json.load(j) for dev in self.object_ids: new_data = data.copy() for i in new_data: if "{name}" in str(new_data.get(i)): new_data[i] = new_data[i].replace("{name}", dev["name"]) elif "{uid}" in str(new_data.get(i)): new_data[i] = new_data[i].replace("{uid}", dev["uid"]) json_list.append(new_data) return json_list # test = MqttManager() # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface.