import datetime import sys import paho.mqtt.client as mqtt SHELLY_ID = "" POWER_THRESHOLD = 0 TIME_THRESHOLD = 15 * 60 LAST_TIME = None def on_message(client, userdata, msg): global LAST_TIME topic = msg.topic payload = msg.payload print(topic, file=sys.stderr) print(payload, file=sys.stderr) if topic.endswith("/relay/0/command") and payload.decode("UTF-8") == "on": if LAST_TIME == None: LAST_TIME = datetime.datetime.now() print("UPDATE TIME", file=sys.stderr) if topic.endswith("/relay/0/command") and payload.decode("UTF-8") == "off": LAST_TIME = None print("RESET TIME", file=sys.stderr) if topic.endswith("/relay/0/power") and LAST_TIME != None: if float(payload.decode("UTF-8")) > POWER_THRESHOLD: LAST_TIME = datetime.datetime.now() print("RESET POWER", file=sys.stderr) elif (datetime.datetime.now() - LAST_TIME).total_seconds() > TIME_THRESHOLD: #client.publish(f"shellies/{SHELLY_ID}/relay/0", "off") print('{ "state": "Free" }') sys.stdout.flush() LAST_TIME = None print("RESET STATE", file=sys.stderr) else: print("WAITING TIME", file=sys.stderr) sys.stderr.flush() def ask_exit(*args): STOP.set() def main(host): client = client = mqtt.Client(f"shelly_client_{SHELLY_ID}") client.on_message = on_message client.connect(host) client.subscribe(f"shellies/{SHELLY_ID}/relay/0/#") client.loop_forever() if __name__ == '__main__': host = sys.argv[1] SHELLY_ID = sys.argv[2] POWER_THRESHOLD = int(sys.argv[3]) main(host)