diff --git a/main.py b/main.py new file mode 100644 index 0000000..25b838d --- /dev/null +++ b/main.py @@ -0,0 +1,65 @@ +import asyncio +import signal +import datetime +import sys + +from gmqtt import Client as MQTTClient + +SHELLY_ID = "" +POWER_THRESHOLD = 0 +TIME_THRESHOLD = 15 * 60 + +LAST_TIME = None + +STOP = asyncio.Event() + +def on_message(client, topic, payload, qos, properties): + global LAST_TIME + + print(topic) + print(payload) + + if topic.endswith("/relay/0") and int(payload) == 1: + if LAST_TIME == None: + LAST_TIME = datetime.datetime.now() + print("UPDATE TIME") + if topic.endswith("/relay/0") and int(payload) == 0: + LAST_TIME = None + print("RESET TIME") + + if topic.endswith("/relay/0/energy") and LAST_TIME != None: + if int(payload) > POWER_THRESHOLD: + LAST_TIME = None + print("RESET POWER") + elif (datetime.datetime.now() - LAST_TIME).total_seconds() > TIME_THRESHOLD: + client.publish(f"shellies/{SHELLY_ID}/relay/0", "off") + print('{ "state": { "1.3.6.1.4.1.48398.612.2.4": { "state": "Free" } } }') + LAST_TIME = None + print("RESET STATE") + +def ask_exit(*args): + STOP.set() + +async def main(host): + client = MQTTClient("shelly_client") + + client.on_message = on_message + + await client.connect(host) + client.subscribe(f"shellies/{SHELLY_ID}/relay/0") + client.subscribe(f"shellies/{SHELLY_ID}/relay/0/energy") + + await STOP.wait() + await client.disconnect() + +if __name__ == '__main__': + loop = asyncio.get_event_loop() + + host = sys.argv[1] + SHELLY_ID = sys.argv[2] + POWER_THRESHOLD = int(sys.argv[3]) + + loop.add_signal_handler(signal.SIGINT, ask_exit) + loop.add_signal_handler(signal.SIGTERM, ask_exit) + + loop.run_until_complete(main(host)) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..ca1b7a1 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +gmqtt +uvloop \ No newline at end of file