62 lines
1.7 KiB
Python
Raw Normal View History

2022-08-05 23:58:58 +02:00
import datetime
import sys
2022-08-13 14:31:00 +02:00
import paho.mqtt.client as mqtt
2022-08-05 23:58:58 +02:00
SHELLY_ID = ""
POWER_THRESHOLD = 0
TIME_THRESHOLD = 15 * 60
LAST_TIME = None
2022-08-13 14:31:00 +02:00
def on_message(client, userdata, msg):
2022-08-05 23:58:58 +02:00
global LAST_TIME
2022-08-13 14:31:00 +02:00
topic = msg.topic
payload = msg.payload
2022-08-22 19:08:59 +02:00
print(topic, file=sys.stderr)
print(payload, file=sys.stderr)
if topic.endswith("/relay/0/command") and payload.decode("UTF-8") == "on":
2022-08-05 23:58:58 +02:00
if LAST_TIME == None:
LAST_TIME = datetime.datetime.now()
2022-08-22 19:08:59 +02:00
print("UPDATE TIME", file=sys.stderr)
if topic.endswith("/relay/0/command") and payload.decode("UTF-8") == "off":
2022-08-05 23:58:58 +02:00
LAST_TIME = None
2022-08-22 19:08:59 +02:00
print("RESET TIME", file=sys.stderr)
2022-08-05 23:58:58 +02:00
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-22 19:08:59 +02:00
LAST_TIME = datetime.datetime.now()
print("RESET POWER", file=sys.stderr)
2022-08-05 23:58:58 +02:00
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-22 19:08:59 +02:00
print('{ "state": "Free" }')
sys.stdout.flush()
2022-08-05 23:58:58 +02:00
LAST_TIME = None
2022-08-22 19:08:59 +02:00
print("RESET STATE", file=sys.stderr)
2022-08-08 14:13:17 +00:00
else:
2022-08-22 19:08:59 +02:00
print("WAITING TIME", file=sys.stderr)
sys.stderr.flush()
2022-08-05 23:58:58 +02:00
def ask_exit(*args):
STOP.set()
2022-08-13 14:31:00 +02:00
def main(host):
2022-08-22 19:08:59 +02:00
client = client = mqtt.Client(f"shelly_client_{SHELLY_ID}")
2022-08-05 23:58:58 +02:00
client.on_message = on_message
2022-08-22 19:08:59 +02:00
2022-08-13 14:31:00 +02:00
client.connect(host)
2022-08-22 19:08:59 +02:00
client.subscribe(f"shellies/{SHELLY_ID}/relay/0/#")
2022-08-13 14:31:00 +02:00
client.loop_forever()
2022-08-05 23:58:58 +02:00
if __name__ == '__main__':
host = sys.argv[1]
SHELLY_ID = sys.argv[2]
POWER_THRESHOLD = int(sys.argv[3])
2022-08-13 14:31:00 +02:00
main(host)