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}
This commit is contained in:
Pim van Pelt
2018-02-12 18:25:36 +01:00
parent bb62e9b6ae
commit c72ea2af41

View File

@ -4,31 +4,47 @@
#include "main.h" #include "main.h"
#include "mgos_dht.h" #include "mgos_dht.h"
#include "mqtt.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) { static void dht_cb(void *ud) {
struct mgos_dht *dht = (struct mgos_dht *)ud; int dht_idx = (int)ud;
float t, h; float t, h;
if (!dht) { if (!s_dht[dht_idx]) {
LOG(LL_ERROR, ("No DHT handle to work with!")); LOG(LL_ERROR, ("No DHT handle to work with!"));
return; return;
} }
t = mgos_dht_get_temp(dht); t = mgos_dht_get_temp(s_dht[dht_idx]);
h = mgos_dht_get_humidity(dht); 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; 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); dht=mgos_dht_create(pin, type);
if (!dht) { if (!dht) {
LOG(LL_ERROR, ("Could not create DHT sensor on pin %d", pin)); 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() { void dht_init() {
memset(s_dht, 0, sizeof (struct mgos_dht *) * MAX_DHT);
dht_create(5, AM2302); dht_create(5, AM2302);
mgos_msleep(250); mgos_msleep(250);
dht_create(4, AM2302); dht_create(4, AM2302);