nixos-config/mqtt/heater.py

79 lines
2.3 KiB
Python
Raw Normal View History

2021-03-16 22:00:45 +01:00
import time
2021-03-16 21:09:22 +01:00
import paho.mqtt.client as mqtt
2021-03-16 22:00:45 +01:00
import json
import threading
2021-03-16 21:09:22 +01:00
2021-03-16 22:00:45 +01:00
# initial scene
scene = "default"
2021-03-16 21:09:22 +01:00
# The callback for when the client receives a CONNACK response from the server.
2021-03-16 22:00:45 +01:00
def on_connect(client, _userdata, _flags, rc):
2021-03-16 21:09:22 +01:00
print("Connected with result code " + str(rc))
2021-03-16 22:00:45 +01:00
threading.Thread(target=loop_thread, args=(client,), daemon=True).start()
2021-03-16 21:09:22 +01:00
# 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.
2021-03-16 22:00:45 +01:00
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":
2021-03-16 22:14:50 +01:00
publish_heater(client, 12)
2021-03-16 22:00:45 +01:00
elif scene == "default":
publish_heater(client, 26)
elif scene == "outside":
2021-03-16 22:14:50 +01:00
publish_heater(client, 10)
2021-03-16 22:00:45 +01:00
else:
2021-03-16 22:14:50 +01:00
publish_heater(client, 10)
2021-03-16 21:09:22 +01:00
2021-03-16 22:00:45 +01:00
def loop_thread(client):
while True:
publish_heater_depending_on_scene(client)
time.sleep(300)
2021-03-16 21:09:22 +01:00
2021-03-16 22:00:45 +01:00
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()