ha_mqtt_configd: Initial version of role
This commit is contained in:
parent
f114a2d5d9
commit
2fedbd505b
4 changed files with 132 additions and 0 deletions
70
roles/ha_mqtt_configd/files/ha_mqtt_configd.py
Executable file
70
roles/ha_mqtt_configd/files/ha_mqtt_configd.py
Executable file
|
@ -0,0 +1,70 @@
|
|||
#!/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(),
|
||||
"identifiers": [
|
||||
uniqueid,
|
||||
],
|
||||
},
|
||||
"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()
|
Loading…
Add table
Add a link
Reference in a new issue