nixos-config/mqtt/main.py
2021-03-16 22:00:45 +01:00

78 lines
2.3 KiB
Python

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):
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):
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'])
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
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()