init project

This commit is contained in:
2022-06-02 08:34:19 +03:00
commit 1997b8c2d9
8 changed files with 245 additions and 0 deletions

16
src/config.h.tmpl Normal file
View File

@@ -0,0 +1,16 @@
// Настройки WiFi
#define WIFI_SSID "SSID_HERE"
#define WIFI_PASS "PASS_HERE"
// Сервер MQTT
#define MQTT_SERVER "MQTT_SERVER_HERE"
#define MQTT_PORT 5319
#define MQTT_LOGIN "MQTT_LOGIN_HERE"
#define MQTT_PASS "MQTT_PASS_HERE"
#define DHTPIN D4 // pin gpio 2 in sensor
#define DHTTYPE DHT22 // DHT 22 Change this if you have a DHT11
#define CLIENT_ID "CLIENT_ID_HERE"
#define HUMIDITY_TOPIC "sensor/humidity"
#define TEMPERATURE_TOPIC "sensor/temperature"

96
src/main.cpp Normal file
View File

@@ -0,0 +1,96 @@
#include <Arduino.h>
#include <DHT.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <config.h>
WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(DHTPIN, DHTTYPE);
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(WIFI_SSID);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
// If you do not want to use a username and password, change next line to
// if (client.connect("ESP8266Client")) {
if (client.connect("ESP8266Client", MQTT_LOGIN, MQTT_PASS)) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
bool checkBound(float newValue, float prevValue, float maxDiff) {
return !isnan(newValue) &&
(newValue < prevValue - maxDiff || newValue > prevValue + maxDiff);
}
long lastMsg = 0;
float temp = 0.0;
float hum = 0.0;
float diff = 1.0;
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(MQTT_SERVER, MQTT_PORT);
dht.begin();
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 10000) {
lastMsg = now;
float newTemp = dht.readTemperature();
float newHum = dht.readHumidity();
if (checkBound(newTemp, temp, diff)) {
temp = newTemp;
Serial.print("New temperature:");
Serial.println(String(temp).c_str());
client.publish(TEMPERATURE_TOPIC, String(temp).c_str(), true);
}
if (checkBound(newHum, hum, diff)) {
hum = newHum;
Serial.print("New humidity:");
Serial.println(String(hum).c_str());
client.publish(HUMIDITY_TOPIC, String(hum).c_str(), true);
}
}
}