Skip to content

Instantly share code, notes, and snippets.

@quarxpl
Created March 2, 2019 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quarxpl/1927156503f0b5e9e3e978e1706647d0 to your computer and use it in GitHub Desktop.
Save quarxpl/1927156503f0b5e9e3e978e1706647d0 to your computer and use it in GitHub Desktop.
automation.py
#!/usr/bin/python
import logging
import time
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import json
def on_message(client, userdata, msg):
global bathroom_last_closed
global bathroom_last_move
message = str(msg.payload)
logging.info("Incoming MQTT message: " + msg.topic + " " + message)
if msg.topic == "xiaomi/from":
message = json.loads(message)
status = ""
if "data" in message and "status" in message["data"]:
status = message["data"]["status"]
if message["sid"] == "158d0002b92f4a" and status == "motion":
logging.info("Motion detected in the bathroom")
client.publish("sonoff/10003ab53a_0/power", "1")
bathroom_last_move = time.time()
if message["sid"] == "158d0002a649b7" and status == "close":
logging.info("The bathroom door is now closed")
bathroom_last_closed = time.time()
if message["sid"] == "158d0002a649b7" and status == "open":
logging.info("The bathroom door is now opened")
bathroom_last_closed = None
def on_timer(client):
global bathroom_last_closed
global bathroom_last_move
# Turn off the lights, if the bathroom is empty
if bathroom_last_closed != None:
diff = time.time() - bathroom_last_closed
if diff > 3.0 and (bathroom_last_move == None or bathroom_last_move < bathroom_last_closed + 1.0):
bathroom_last_closed = None
logging.info("Lights in the bathroom will be turned off because it is (hopefully) empty")
client.publish("sonoff/10003ab53a_0/power", "0")
client.publish("sonoff/10003ab53a_1/power", "0")
def on_connect(client, userdata, flags, rc):
client.subscribe("xiaomi/from")
logging.basicConfig(level = logging.DEBUG, filename = "/var/log/ha/automation.log", filemode = "a+", format = "%(asctime)-15s %(levelname)-8s %(message)s")
logging.getLogger().addHandler(logging.StreamHandler())
bathroom_last_closed = bathroom_last_move = None
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("127.0.0.1", 1883, 60)
client.loop_start()
while True:
on_timer(client)
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment