68 lines
1.8 KiB
Python
Raw Normal View History

2022-08-05 23:58:58 +02:00
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)
2022-08-08 14:13:17 +00:00
if topic.endswith("/relay/0") and payload.decode("UTF-8") == "on":
2022-08-05 23:58:58 +02:00
if LAST_TIME == None:
LAST_TIME = datetime.datetime.now()
print("UPDATE TIME")
2022-08-08 14:13:17 +00:00
if topic.endswith("/relay/0") and payload.decode("UTF-8") == "off":
2022-08-05 23:58:58 +02:00
LAST_TIME = None
print("RESET TIME")
2022-08-08 14:13:17 +00:00
if topic.endswith("/relay/0/power") and LAST_TIME != None:
if float(payload.decode("UTF-8")) > POWER_THRESHOLD:
2022-08-05 23:58:58 +02:00
LAST_TIME = None
print("RESET POWER")
elif (datetime.datetime.now() - LAST_TIME).total_seconds() > TIME_THRESHOLD:
2022-08-08 14:13:17 +00:00
#client.publish(f"shellies/{SHELLY_ID}/relay/0", "off")
2022-08-05 23:58:58 +02:00
print('{ "state": { "1.3.6.1.4.1.48398.612.2.4": { "state": "Free" } } }')
LAST_TIME = None
print("RESET STATE")
2022-08-08 14:13:17 +00:00
else:
print("WAITING TIME")
2022-08-05 23:58:58 +02:00
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)
2022-08-08 14:13:17 +00:00
loop.run_until_complete(main(host))