You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

95 lines
1.9 KiB

#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <DHTesp.h>
#include "credential.h"
#define SLEEP_MINUTES 1
DHTesp dht;
char* mqtt_server = "ashpool.lan";
void callback( char * topic, byte* payload, unsigned int length) {
// do things!
}
WiFiClient wclient;
PubSubClient client(wclient, mqtt_server, 1883);
String nodeID;
void setup() {
Serial.begin(115200);
nodeID = "ESP_" + String(ESP.getChipId(), 16);
Serial.println("DHT MQTT Logger:" + nodeID + " Starting\n");
dht.setup(D4, DHTesp::DHT22);
wifi_set_sleep_type(LIGHT_SLEEP_T);
wifi();
if (client.connect((char*) nodeID.c_str())) {
Serial.println("Connected to MQTT broker");
}
}
void wifi() {
WiFi.persistent(false);
WiFi.mode(WIFI_OFF);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid_name, ssid_pass); // Access WiFi, details from credential.h
Serial.print("Connecting to ");
Serial.print(ssid_name);
Serial.print(" ...");
while (WiFi.status() != WL_CONNECTED) { // Wait for WiFi to connect
delay(250);
Serial.print(".");
}
Serial.println('\n');
Serial.println("WiFi connection established");
Serial.print("Device's IP address is ");
Serial.println(WiFi.localIP()); // Show device's IP address
}
template <typename T>
void publish(const char * topic, T msg)
{
if (!client.connected()) {
client.connect((char*) nodeID.c_str());
}
client.publish(nodeID + "/" + topic, String(msg));
Serial.println(nodeID + "/" + topic + ": " + String(msg));
}
void loop() {
delay(dht.getMinimumSamplingPeriod());
Serial.println ( "------------------------" ) ;
if (WiFi.status() != WL_CONNECTED) {
wifi();
}
float h = dht.getHumidity();
float t = dht.getTemperature();
float hic = dht.computeHeatIndex(t, h, false);
publish("temp", t);
publish("relative_humidity", h);
publish("heat_index", String(hic));
delay(SLEEP_MINUTES * 60 * 1000L);
}