From c72ea2af416dbaa19cede38099b866f5fcfd910d Mon Sep 17 00:00:00 2001 From: Pim van Pelt Date: Mon, 12 Feb 2018 18:25:36 +0100 Subject: [PATCH] Keep a list of DHT sensors s_dht is a list of MAX_DHT elements. Pass the index to the callback so we can report on individual sensors by 0-based index. Mon Feb 12 18:26:12 2018 - esp8266_052EE8/stat/dht {"idx":0, "temp":18.80, "humidity":31.6} Mon Feb 12 18:26:12 2018 - esp8266_052EE8/stat/dht {"idx":1, "temp":18.70, "humidity":36.4} Mon Feb 12 18:26:12 2018 - esp8266_052EE8/stat/dht {"idx":2, "temp":18.80, "humidity":39.5} --- src/dht.c | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/src/dht.c b/src/dht.c index 945d94e..46dc6d7 100644 --- a/src/dht.c +++ b/src/dht.c @@ -4,31 +4,47 @@ #include "main.h" #include "mgos_dht.h" #include "mqtt.h" + +#define MAX_DHT 8 + +static struct mgos_dht *s_dht[MAX_DHT]; +static int s_num_dht = 0; + static void dht_cb(void *ud) { - struct mgos_dht *dht = (struct mgos_dht *)ud; + int dht_idx = (int)ud; float t, h; - if (!dht) { + if (!s_dht[dht_idx]) { LOG(LL_ERROR, ("No DHT handle to work with!")); return; } - t = mgos_dht_get_temp(dht); - h = mgos_dht_get_humidity(dht); + t = mgos_dht_get_temp(s_dht[dht_idx]); + h = mgos_dht_get_humidity(s_dht[dht_idx]); - mqtt_publish_stat("dht", "{temp=%.2f, humidity=%.1f}", t, h); + mqtt_publish_stat("dht", "{idx:%d, temp:%.2f, humidity:%.1f}", dht_idx, t, h); } -static void dht_create(int pin, enum dht_type type) { +static bool dht_create(int pin, enum dht_type type) { struct mgos_dht *dht; + if (s_num_dht == MAX_DHT) { + LOG(LL_ERROR, ("No more sensor slots available (%d added)", MAX_DHT)); + return false; + } + dht=mgos_dht_create(pin, type); if (!dht) { LOG(LL_ERROR, ("Could not create DHT sensor on pin %d", pin)); - return; + return false; } - mgos_set_timer(5000, true, dht_cb, (void*)dht); + s_dht[s_num_dht] = dht; + mgos_set_timer(5000, true, dht_cb, (void *)s_num_dht); + s_num_dht++; + + return true; } void dht_init() { + memset(s_dht, 0, sizeof (struct mgos_dht *) * MAX_DHT); dht_create(5, AM2302); mgos_msleep(250); dht_create(4, AM2302);