summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDaniel Friesel <derf@finalrewind.org>2022-04-19 19:16:38 +0200
committerDaniel Friesel <derf@finalrewind.org>2022-04-19 19:16:38 +0200
commit848146b76cd67f62a74b88f97e95ace285f93711 (patch)
tree811a5685ab1419a719b8bf333eab1357442debae
parenta07247be87a77b6cc2f90c71b371bbf60766ef26 (diff)
add homeassistant integration
-rw-r--r--init.lua26
1 files changed, 21 insertions, 5 deletions
diff --git a/init.lua b/init.lua
index fe53b86..d558f70 100644
--- a/init.lua
+++ b/init.lua
@@ -2,11 +2,13 @@ station_cfg = {}
dofile("config.lua")
delayed_restart = tmr.create()
-chipid = node.chipid()
-mqtt_prefix = "sensor/esp8266_" .. chipid
-mqttclient = mqtt.Client("esp8266_" .. chipid, 120)
+chip_id = node.chipid()
+device_id = "esp8266_" .. chip_id
+mqtt_prefix = "sensor/" .. device_id
+mqttclient = mqtt.Client(device_id, 120)
-print("ESP8266 " .. chipid)
+
+print("ESP8266 " .. chip_id)
ledpin = 4
gpio.mode(ledpin, gpio.OUTPUT)
@@ -34,7 +36,7 @@ function connect_mqtt()
print("IP address: " .. wifi.sta.getip())
print("Connecting to MQTT " .. mqtt_host)
delayed_restart:stop()
- mqttclient:on("connect", setup_client)
+ mqttclient:on("connect", hass_register)
mqttclient:on("offline", log_restart)
mqttclient:lwt(mqtt_prefix .. "/state", "offline", 0, 1)
mqttclient:connect(mqtt_host)
@@ -70,6 +72,20 @@ function uart_callback(data)
end
end
+function hass_register()
+ local hass_device = string.format('{"connections":[["mac","%s"]],"identifiers":["%s"],"model":"ESP8266","name":"ESP8266 PM1006","manufacturer":"DIY"}', wifi.sta.getmac(), device_id)
+ local hass_entity_base = string.format('"device":%s,"state_topic":"%s/data","expire_after":600', hass_device, mqtt_prefix)
+ local hass_pm2_5 = string.format('{%s,"name":"PM2.5","object_id":"%s_pm2_5","unique_id":"%s_pm2_5","icon":"mdi:air-filter","unit_of_measurement":"µg/m³","value_template":"{{value_json.pm2_5_ugm3}}"}', hass_entity_base, device_id, device_id)
+ local hass_rssi = string.format('{%s,"name":"RSSI","object_id":"%s_rssi","unique_id":"%s_rssi","icon":"mdi:wifi","unit_of_measurement":"dBm","value_template":"{{value_json.rssi_dbm}}","entity_category":"diagnostic"}', hass_entity_base, device_id, device_id)
+
+ mqttclient:publish("homeassistant/sensor/" .. device_id .. "/pm2_5/config", hass_pm2_5, 0, 1, function(client)
+ mqttclient:publish("homeassistant/sensor/" .. device_id .. "/rssi/config", hass_rssi, 0, 1, function(client)
+ collectgarbage()
+ setup_client()
+ end)
+ end)
+end
+
delayed_restart:register(20 * 1000, tmr.ALARM_SINGLE, node.restart)
connect_wifi()