diff --git a/mqtt/main.py b/mqtt/main.py index 2ca6067..0eb132b 100644 --- a/mqtt/main.py +++ b/mqtt/main.py @@ -1,30 +1,78 @@ +import time import paho.mqtt.client as mqtt +import json +import threading +# initial scene +scene = "default" # The callback for when the client receives a CONNACK response from the server. -def on_connect(client, userdata, flags, rc): +def on_connect(client, _userdata, _flags, rc): print("Connected with result code " + str(rc)) + threading.Thread(target=loop_thread, args=(client,), daemon=True).start() + # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("control/lights/set") # The callback for when a PUBLISH message is received from the server. -def on_message(client, userdata, msg): - print(msg.topic + " " + str(msg.payload)) +def on_message(client, _userdata, msg): + global scene + (topic, payload) = parse_message(msg) + print("set scene %s -> %s" % (scene, payload['scene'])) + scene = payload['scene'] + publish_heater_depending_on_scene(client) + # print(topic + " " + payload['scene']) -client = mqtt.Client() -client.on_connect = on_connect -client.on_message = on_message -client.username_pw_set("homeassistant", password="password") +def parse_message(msg): + m_decode = str(msg.payload.decode("utf-8", "ignore")) + payload = json.loads(m_decode) # decode json data + return msg.topic, payload -client.connect("pepe.private", 1883, 60) -# 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. -client.loop_forever() +mqttClient = mqtt.Client() +mqttClient.on_connect = on_connect +mqttClient.on_message = on_message +mqttClient.username_pw_set("homeassistant", password="password") + +mqttClient.connect("pepe.private", 1883, 60) + + +def publish_heater(client, temperature=10): + payload = { + "system_mode": "auto", + "current_heating_setpoint": str(temperature), + "eurotronic_host_flags": {"window_open": True} + } + client.publish("zigbee2mqtt/heater1/set", json.dumps(payload)) + client.publish("zigbee2mqtt/heater2/set", json.dumps(payload)) + client.publish("zigbee2mqtt/heater3/set", json.dumps(payload)) + + +def publish_heater_depending_on_scene(client): + if scene == "night": + publish_heater(client, 10) + elif scene == "default": + publish_heater(client, 26) + elif scene == "outside": + publish_heater(client, 8) + else: + publish_heater(client, 8) + + +def loop_thread(client): + while True: + publish_heater_depending_on_scene(client) + time.sleep(300) + + +if __name__ == "__main__": + # 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. + mqttClient.loop_forever()