/*
Для відправки по HTTP - розкоментувати виклик sendDHT22_http(); у void_loop()
Але затримка значно збільшується
*/
#include <WiFi.h>
#include <HTTPClient.h>
#include <LiquidCrystal_I2C.h>
#include <ArduinoJson.h>
#include "DHT.h"
#include <PubSubClient.h>
bool led_mode = false;
#define DHTPIN 2 // Визначаємо пін, до якого підключено датчик DHT
#define DHTTYPE DHT22 // Визначаємо тип датчика DHT (DHT22)
DHT dht (DHTPIN, DHTTYPE); // Створюємо об'єкт класу DHT з вказаним піном і типом
//DHT22 constants
const uint16_t DHT22_Ts = 5000; // Interval
//DHT22 variables
uint32_t DHT22_Timer = 0; //Timer_variable
uint32_t DHT22_deltaTimer = 0; //0..5000ms for LCD
float temperature;
//Json
JsonDocument doc_out;
String doc_out_str;
HTTPClient http;
//WiFi constants
const char* ssid = "Wokwi-GUEST";
const char* password = "";
//const String url1 = "https://sinoptik.ua/pohoda/kyiv";
const String url2 = "https://api.open-meteo.com/v1/forecast?latitude=50.4547&longitude=30.5238&hourly=temperature_2m&timezone=auto&forecast_days=1";
const String url_DHT22 = "https://webhook.site/600565da-c9f5-4587-ad96-374e8db99b00";
//MQTT
const char* mqttServer = "broker.hivemq.com";
const char* myTopic = "GroupRE/Temp/18";
const char* groupTopic = "GroupRE/#";
const uint16_t port = 1883;
const char * clientId = "Assholien_RE-22_18_1";
WiFiClient wifiClient;
PubSubClient client(wifiClient);
LiquidCrystal_I2C lcd(0x27, 20, 4);
LiquidCrystal_I2C lcd2(0x28, 20, 4);
void loadPage1();
void sendDHT22_http();
void sendDHT22_broker();
void reconnect();
void setup()
{
// put your setup code here, to run once:
// Ініціалізація порту для виведення даних у консоль
Serial.begin(115200);
Serial.println("Hello, ESP32-C3!");
dht.begin(); // Ініціалізуємо датчик DHT
// Ініціалізація дисплею
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
// Ініціалізація дисплею 2
lcd2.init();
lcd2.backlight();
lcd2.clear();
// Підключення до Wi-Fi
WiFi.begin(ssid, password);
lcd.print("Wi-Fi : Connecting");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
lcd.print (".");
}
lcd.clear();
lcd.println ("Wi-Fi: Online");
client.setServer(mqttServer, port);
loadPage1();
reconnect();
DHT22_Timer = millis();
}
void loop()
{
DHT22_deltaTimer = millis() - DHT22_Timer;
lcd.setCursor(0, 2);
lcd.printf("Timer: %.4lu ms", DHT22_deltaTimer);
if (DHT22_deltaTimer >= DHT22_Ts)
{
temperature = dht.readTemperature(); // Отримуємо значення температури з датчика DHT
DHT22_Timer = millis(); // кожні 5с
loadPage1();
Serial.print("DHT22 Temperature = ");
Serial.print(temperature, 1);
Serial.println(" *C");
lcd.setCursor(0, 3);
lcd.printf("DHT22 = %+.1f *C ", temperature);
//To Json
doc_out["temperature"] = temperature;
serializeJson(doc_out, doc_out_str);
Serial.println(doc_out_str);
// sendDHT22_http();
if(led_mode)
doc_out["led_mode"] = "on";
else
doc_out["led_mode"] = "off";
sendDHT22_broker();
Serial.println(doc_out_str);
led_mode = !led_mode;
}
}
void loadPage1()
{
//Перевірка наявності Wi-Fi підключення
if (WiFi.status() == WL_CONNECTED)
{
http.begin(url2);
// http.begin(url1);
uint16_t httpResponseCode = http.GET();
if (httpResponseCode > 0)
{
Serial.print("HTTP код відповіді: ");
Serial.println(httpResponseCode);
JsonDocument doc_in;
String payload = http.getString();
Serial.println(payload);
deserializeJson(doc_in, payload);
//Варіант №18, 17:00
float temp_var = doc_in["hourly"]["temperature_2m"][17];
Serial.print("Temperature for variant 18, 17:00: ");
Serial.print(temp_var, 1);
Serial.println(" *C");
lcd.setCursor(0, 1);
lcd.printf("T(17:00) = %+.1f *C ", temp_var);
lcd2.setCursor(0, 0);
lcd2.printf("T(00:00) = %+.1f *C ", (float) doc_in["hourly"]["temperature_2m"][0]);
lcd2.setCursor(0, 1);
lcd2.printf("T(06:00) = %+.1f *C ", (float) doc_in["hourly"]["temperature_2m"][6]);
lcd2.setCursor(0, 2);
lcd2.printf("T(12:00) = %+.1f *C ", (float) doc_in["hourly"]["temperature_2m"][12]);
lcd2.setCursor(0, 3);
lcd2.printf("T(18:00) = %+.1f *C ", (float) doc_in["hourly"]["temperature_2m"][18]);
}
else
{
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
}
else
{
Serial.println("З'єднання Wi-Fi втрачено");
}
}
void sendDHT22_http()
{
//Перевірка наявності Wi-Fi підключення
if (WiFi.status() == WL_CONNECTED)
{
http.begin(url_DHT22);
uint16_t httpResponseCode = http.GET();
if (httpResponseCode > 0)
{
Serial.print("HTTP код відповіді: ");
Serial.println(httpResponseCode);
Serial.println(doc_out_str);
http.POST(doc_out_str);
}
else
{
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
}
else
{
Serial.println("З'єднання Wi-Fi втрачено");
}
}
void sendDHT22_broker()
{
// Перевірка підключення по MQTT
if (!client.connected())
reconnect();
client.publish(myTopic, doc_out_str.c_str());
}
void reconnect()
{
while (!client.connected())
{
Serial.println ("Підключення по MQTT...");
if (client.connect(clientId))
{
client.subscribe(myTopic);
client.subscribe(groupTopic);
Serial.print("Клієнт: ");
Serial.print(clientId);
Serial.println(" підключений.");
}
else
{
Serial.print ("помилка: ");
Serial.print(client.state());
Serial.println(" повторна спроба через 3 секунди");
delay(3000);
}
}
}