diff options
author | Daniel Friesel <derf@finalrewind.org> | 2022-04-29 19:40:02 +0200 |
---|---|---|
committer | Daniel Friesel <derf@finalrewind.org> | 2022-04-29 19:40:02 +0200 |
commit | f6d4dcb42da4901944da1bc5d96c9ec6fbfbe134 (patch) | |
tree | 8ce4e4129b8e0807f0161e69eeb4098960d4bafb | |
parent | bb8baa21195aa673ba4c8debd6fd9233f5241ee3 (diff) |
average ten PM2.5 readings before reporting to HASS
-rw-r--r-- | init.lua | 33 |
1 files changed, 22 insertions, 11 deletions
@@ -7,7 +7,6 @@ device_id = "esp8266_" .. chip_id mqtt_prefix = "sensor/" .. device_id mqttclient = mqtt.Client(device_id, 120) - print("ESP8266 " .. chip_id) ledpin = 4 @@ -16,6 +15,8 @@ gpio.write(ledpin, 0) pm1006 = require("pm1006") +pm_values = {} + function log_restart() print("Network error " .. wifi.sta.status() .. ". Restarting in 20 seconds.") delayed_restart:start() @@ -58,22 +59,32 @@ function uart_callback(data) print("Invalid PM1006 frame") return else - local json_str = string.format('{"pm2_5_ugm3": %d, "rssi_dbm": %d}', pm2_5, wifi.sta.getrssi()) - if not publishing then - publishing = true - gpio.write(ledpin, 0) - mqttclient:publish(mqtt_prefix .. "/data", json_str, 0, 0, function(client) - publishing = false - gpio.write(ledpin, 1) - collectgarbage() - end) + table.insert(pm_values, pm2_5) + if table.getn(pm_values) == 10 then + local pm_sum = 0 + for i, pm_value in ipairs(pm_values) do + pm_sum = pm_sum + pm_value + end + local pm_int = pm_sum / 10 + local pm_frac = pm_sum % 10 + local json_str = string.format('{"pm2_5_ugm3": %d.%d, "rssi_dbm": %d}', pm_int, pm_frac, wifi.sta.getrssi()) + pm_values = {} + if not publishing then + publishing = true + gpio.write(ledpin, 0) + mqttclient:publish(mqtt_prefix .. "/data", json_str, 0, 0, function(client) + publishing = false + gpio.write(ledpin, 1) + collectgarbage() + end) + end end end end function hass_register() local hass_device = string.format('{"connections":[["mac","%s"]],"identifiers":["%s"],"model":"ESP8266 + PM1006","name":"Vindriktning %s","manufacturer":"derf"}', wifi.sta.getmac(), device_id, chip_id) - local hass_entity_base = string.format('"device":%s,"state_topic":"%s/data","expire_after":60', hass_device, mqtt_prefix) + local hass_entity_base = string.format('"device":%s,"state_topic":"%s/data","expire_after":90', hass_device, mqtt_prefix) local hass_pm2_5 = string.format('{%s,"name":"PM2.5","object_id":"%s_pm2_5","unique_id":"%s_pm2_5","device_class":"pm25","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","device_class":"signal_strength","unit_of_measurement":"dBm","value_template":"{{value_json.rssi_dbm}}","entity_category":"diagnostic"}', hass_entity_base, device_id, device_id) |