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.
115 lines
2.4 KiB
115 lines
2.4 KiB
#include <PubSubClient.h> |
|
#include <ESP8266WiFi.h> |
|
#include <DHTesp.h> |
|
|
|
#include <SPI.h> |
|
#include <Wire.h> |
|
#include <Adafruit_GFX.h> |
|
#include <Adafruit_SSD1306.h> |
|
|
|
#include "credential.h" |
|
|
|
#define SLEEP_MINUTES 1 |
|
|
|
DHTesp dht; |
|
|
|
char* mqtt_server = "ashpool.lan"; |
|
|
|
WiFiClient wclient; |
|
|
|
PubSubClient client(wclient, mqtt_server, 1883); |
|
|
|
String nodeID; |
|
|
|
|
|
#define SCREEN_WIDTH 128 |
|
#define SCREEN_HEIGHT 64 |
|
|
|
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1); |
|
|
|
void setup() { |
|
Serial.begin(115200); |
|
nodeID = "ESP_" + String(ESP.getChipId(), 16); |
|
|
|
Serial.println("DHT MQTT Logger:" + nodeID + " Starting\n"); |
|
|
|
dht.setup(D4, DHTesp::DHT22); |
|
|
|
Wire.begin(D6, D5); |
|
|
|
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3c)) { |
|
Serial.println("SSD1306 allocation failed"); |
|
} |
|
|
|
wifi_set_sleep_type(LIGHT_SLEEP_T); |
|
wifi(); |
|
|
|
if (client.connect((char*) nodeID.c_str())) { |
|
Serial.println("Connected to MQTT broker"); |
|
} |
|
|
|
display.display(); |
|
display.drawPixel(10, 10, SSD1306_WHITE); |
|
display.clearDisplay(); |
|
display.setTextSize(4); |
|
display.setTextColor(SSD1306_WHITE); |
|
|
|
} |
|
|
|
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)); |
|
|
|
display.clearDisplay(); |
|
display.setCursor(10,0); |
|
display.println(String(t)); |
|
display.display(); |
|
|
|
delay(SLEEP_MINUTES * 60 * 1000L); |
|
|
|
}
|
|
|