Implement publish function for cleaner code
This commit is contained in:
parent
cc268b5cd5
commit
9356c436bc
@ -19,7 +19,7 @@
|
||||
#define ID_HUMID ID_BASE "/temperature"
|
||||
#define ID_HEAT ID_BASE "/temperature"
|
||||
|
||||
#define OPERATION_BLINK_EN true // blink continously if in correct operation
|
||||
#define OPERATION_BLINK_EN true // blink continuously if in correct operation
|
||||
|
||||
#define DHTPIN 4 // Digital pin connected to the DHT sensor
|
||||
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
|
||||
@ -96,6 +96,18 @@ long lastSent = 0;
|
||||
bool published = false;
|
||||
bool forcePublish = false;
|
||||
|
||||
bool publish (String desc, char *topic, float val, float &val_r, int diff, bool force){
|
||||
if (checkBound(val, val_r, 0.3) or force) {
|
||||
val_r = val;
|
||||
Serial.print("New " + desc + ": ");
|
||||
Serial.println(String(val).c_str());
|
||||
client.publish(topic, String(val).c_str(), true);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (!client.connected()) {
|
||||
reconnect();
|
||||
@ -121,7 +133,6 @@ void loop() {
|
||||
|
||||
float hi = dht.computeHeatIndex(t, h, false);
|
||||
|
||||
|
||||
Serial.print(F("Humidity: "));
|
||||
Serial.print(h);
|
||||
Serial.print(F("% Temperature: "));
|
||||
@ -137,30 +148,9 @@ void loop() {
|
||||
lastSent = 0;
|
||||
}
|
||||
|
||||
if (checkBound(t, t_r, 0.3) or forcePublish) {
|
||||
t_r = t;
|
||||
Serial.print("New temperature:");
|
||||
Serial.println(String(t).c_str());
|
||||
client.publish(ID_TEMP, String(t).c_str(), true);
|
||||
published = true;
|
||||
}
|
||||
|
||||
if (checkBound(h, h_r, 2.5) or forcePublish) {
|
||||
h_r = h;
|
||||
Serial.print("New humidity:");
|
||||
Serial.println(String(h).c_str());
|
||||
client.publish(ID_HUMID, String(h).c_str(), true);
|
||||
published = true;
|
||||
}
|
||||
|
||||
|
||||
if (checkBound(hi, hi_r, 0.2) or forcePublish) {
|
||||
hi_r = hi;
|
||||
Serial.print("New heat index:");
|
||||
Serial.println(String(hi).c_str());
|
||||
client.publish(ID_HEAT, String(hi).c_str(), true);
|
||||
published = true;
|
||||
}
|
||||
published += publish("temperature", ID_TEMP, t, t_r, 0.3, forcePublish);
|
||||
published += publish("humidity", ID_HUMID, h, h_r, 2.5, forcePublish);
|
||||
published += publish("heat index", ID_HEAT, hi, hi_r, 0.2, forcePublish);
|
||||
|
||||
if (published == false) {
|
||||
lastSent = lastSent + 1;
|
||||
|
Loading…
Reference in New Issue
Block a user