X-Git-Url: https://the.earth.li/gitweb/?a=blobdiff_plain;f=mqtt-power;h=f74a3374c6be4794d9b02592d073b5f21389b9a2;hb=05ee67a050dd758773efde0bfd28e3a2eb8687d6;hp=ee7b67246332803ca39e2f994f38b4c025fc1509;hpb=7a3fef65363947580a3bacad07281f7c9e53c688;p=energenie-attiny.git diff --git a/mqtt-power b/mqtt-power index ee7b672..f74a337 100755 --- a/mqtt-power +++ b/mqtt-power @@ -20,6 +20,7 @@ import time import sys import hid +import json import paho.mqtt.client as mqtt debug = False @@ -61,6 +62,28 @@ def mqtt_message(client, device, message): control_relay(device, relay, state) +def mqtt_connect(client, userdata, flags, rc): + if debug: + print("Connected to MQTT server") + + client.publish("relay/{}/LWT".format(serno_str), "Online", retain=True) + print("Subscribing to %s" % prefix.format(serno_str)) + client.subscribe(prefix.format(serno_str)) + + +def uptime(): + with open('/proc/uptime', 'r') as f: + seconds = int(float(f.readline().split()[0])) + + days = seconds // 86400 + seconds %= 86400 + hours = seconds // 3600 + seconds %= 3600 + minutes = seconds // 60 + seconds %= 60 + + return "{}T{}:{}:{}".format(days, hours, minutes, seconds) + relay = None for dev in hid.enumerate(0x16c0, 0x05df): if dev['manufacturer_string'] == 'www.dcttech.com': @@ -80,10 +103,15 @@ client.tls_set(ca_certs='/etc/ssl/certs/ca-certificates.crt') client.username_pw_set(auth['username'], auth['password']) client.user_data_set(relay) client.on_message = mqtt_message +client.on_connect = mqtt_connect client.connect(Broker, port=8883) -print("Subscribing to %s" % prefix.format(serno_str)) -client.subscribe(prefix.format(serno_str)) client.loop_start() +client.will_set("relay/{}/LWT".format(serno_str), "Offline", retain=True) while True: - time.sleep(60) + state = { + 'Time': time.strftime('%Y-%m-%dT%H:%M:%S', time.gmtime()), + 'Uptime': uptime() + } + client.publish("relay/{}/state".format(serno_str), json.dumps(state)) + time.sleep(300)