From 7f1fb35c9b18b723c34b2a9d42e804234bae0c1e Mon Sep 17 00:00:00 2001 From: Daniel Friesel Date: Sat, 21 May 2022 06:20:12 +0200 Subject: allow reading report mode; add query command --- init.lua | 19 +++++++++++++++++++ sds011.lua | 21 +++++++++++++++------ 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/init.lua b/init.lua index 6dc32d0..4c38550 100644 --- a/init.lua +++ b/init.lua @@ -18,6 +18,9 @@ gpio.write(ledpin, 0) sds011 = require("sds011") +poll = tmr.create() +polling = false + function log_restart() print("Network error " .. wifi.sta.status()) end @@ -65,6 +68,17 @@ function uart_callback(data) work_period = string.format("%d min", sds011.work_period) end + if sds011.work_period == 0 and not polling then + polling = true + port:write(sds011.set_report_mode(false)) + poll:start() + end + if sds011.work_period > 0 and polling then + polling = false + port:write(sds011.set_report_mode(true)) + poll:stop() + end + local json_str = string.format('{"rssi_dbm":%d,"period":"%s"', wifi.sta.getrssi(), work_period) if sds011.pm2_5i ~= nil then json_str = string.format('%s,"pm2_5_ugm3":%d.%d,"pm10_ugm3":%d.%d', json_str, sds011.pm2_5i, sds011.pm2_5f, sds011.pm10i, sds011.pm10f) @@ -99,6 +113,10 @@ function publish_influx(payload) end end +function query_data() + port:write(sds011.query()) +end + function hass_config(client, topic, message) if topic == "config/" .. device_id .. "/set/work_period" then local work_period = 0 @@ -133,6 +151,7 @@ function hass_register() end watchdog:register(20 * 60 * 1000, tmr.ALARM_SEMI, node.restart) +poll:register(10 * 1000, tmr.ALARM_AUTO, query_data) watchdog:start() connect_wifi() diff --git a/sds011.lua b/sds011.lua index 98f5b09..8d5dd58 100644 --- a/sds011.lua +++ b/sds011.lua @@ -30,13 +30,22 @@ function sds011.finish_cmd(cmd) return cmd end +function sds011.query() + local cmd = string.char(c_head, c_id, c_query) + cmd = cmd .. string.char(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + return sds011.finish_cmd(cmd) +end + function sds011.set_report_mode(active) - local cmd = string.char(c_head, c_id, c_report_mode, c_write) - if active then - cmd = cmd .. string.char(c_active) - else - cmd = cmd .. string.char(c_passive) + local op = c_write + local cmd = c_passive + if active == nil then + op = c_read + active = false + elseif active then + cmd = c_active end + local cmd = string.char(c_head, c_id, c_report_mode, op, cmd) cmd = cmd .. string.char(0, 0, 0, 0, 0, 0, 0, 0, 0, 0) return sds011.finish_cmd(cmd) end @@ -82,7 +91,7 @@ function sds011.parse_frame(data) sds011.pm10f = pm10 % 10 return true end - if command == 0xc5 then + if command == 0xc5 and pm25l == 0x08 then sds011.work_period = pm10l return true end -- cgit v1.2.3