71 lines
1.9 KiB
Python
Executable file
71 lines
1.9 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
|
|
import hashlib
|
|
import json
|
|
import paho.mqtt.client as mqtt
|
|
import socket
|
|
import ssl
|
|
import syslog
|
|
import time
|
|
|
|
notify = {}
|
|
|
|
|
|
def on_message(client, userdata, msg):
|
|
if not msg.topic in notify:
|
|
syslog.syslog(syslog.LOG_INFO, f"Publish config for {msg.topic}")
|
|
elif notify[msg.topic] < time.monotonic() - 600:
|
|
syslog.syslog(syslog.LOG_INFO, f"Refresh config for {msg.topic}")
|
|
else:
|
|
return
|
|
topic = msg.topic.split("/")
|
|
uniqueid = hashlib.md5(msg.topic.encode()).hexdigest()
|
|
config = {
|
|
"dev": {
|
|
"name": topic[2].capitalize(),
|
|
"suggested_area": topic[1].capitalize().replace("_", " "),
|
|
"identifiers": [
|
|
uniqueid,
|
|
],
|
|
},
|
|
"icon": "mdi:lightning-bolt",
|
|
"name": "Power Usage",
|
|
"state_topic": msg.topic,
|
|
"unit_of_measurement": "W",
|
|
"unique_id": uniqueid,
|
|
}
|
|
client.publish(
|
|
topic=f"homeassistant/sensor/{uniqueid}/config", payload=json.dumps(config)
|
|
)
|
|
notify[msg.topic] = time.monotonic()
|
|
|
|
|
|
def connect(hostname):
|
|
client = mqtt.Client(protocol=mqtt.MQTTv5)
|
|
client.tls_set(
|
|
certfile=f"/etc/ssl/{socket.gethostname()}.crt",
|
|
keyfile=f"/etc/ssl/private/{socket.gethostname()}.key",
|
|
ca_certs="/etc/ssl/ca.crt",
|
|
cert_reqs=ssl.CERT_REQUIRED,
|
|
)
|
|
client.on_message = on_message
|
|
client.connect(hostname, 8883)
|
|
syslog.syslog(syslog.LOG_INFO, f"Connected to MQTT broker {hostname}")
|
|
return client
|
|
|
|
|
|
def main():
|
|
syslog.openlog(
|
|
"ha_mqtt_configd", logoption=syslog.LOG_PID, facility=syslog.LOG_DAEMON
|
|
)
|
|
client = connect(socket.gethostname())
|
|
try:
|
|
client.subscribe("home/+/+/power")
|
|
client.loop_forever()
|
|
except KeyboardInterrupt:
|
|
client.disconnect()
|
|
syslog.closelog()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|