#include <WiFi.h>
#include <HTTPClient.h>
#include <LiquidCrystal_I2C.h>
#include <ArduinoJson.h>
#include "DHT.h"
#include <PubSubClient.h>
#define LED 23
#define DHTPIN 15 // Визначаємо пін, до якого підключено датчик DHT
#define DHTTYPE DHT22 // Визначаємо тип датчика DHT (DHT22)
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const String url1 = "https://ua.sinoptik.ua/погода-київ";
const String url2 = "https://api.open-meteo.com/v1/forecast?latitude=50.4547&longitude=30.5238&hourly=temperature_2m&timezone=auto&forecast_days=1";
LiquidCrystal_I2C lcd(0x27, 20, 4);
LiquidCrystal_I2C lcd1(0x28, 20, 4);
DHT dht(DHTPIN, DHTTYPE); // Створюємо об'єкт класу DHT з вказаним піном і типом
const char* mqttServer = "broker.hivemq.com";
const char* myTopic = "GroupRE/Temp/13"; // N - замінити на ваш номер варіанту
const char* groupTopic = "GroupRE/#";
int port = 1883;
const char* clientId = "vvdn"; // Ідентифікатор клієнта
WiFiClient wifiClient;
PubSubClient client(wifiClient);
void setup() {
dht.begin(); // Ініціалізуємо датчик DHT
pinMode(LED, OUTPUT);
// Ініціалізація дисплею
lcd.init();
lcd.backlight();
lcd.setCursor(0,0);
lcd1.init();
lcd1.backlight();
lcd1.setCursor(0,0);
// Ініціалізація порту для виведення даних у консоль
Serial.begin(115200);
// Підключення до 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");
loadPageHTTP();
client.setServer(mqttServer, port);
client.setCallback(callback);
}
void loop() {
delay(1000);
// Перевірка підключення по MQTT
if (!client.connected()) {
reconnect();
}
// Відправка повідомлення в топік
String temperature = String(dht.readTemperature());
client.publish(myTopic, temperature.c_str());
client.loop();
}
void loadPageHTTP(){
String payload;
HTTPClient http;
int httpResponseCode;
//Перевірка наявності Wi-Fi підключення
if(WiFi.status()== WL_CONNECTED){
http.begin(url1);
httpResponseCode = http.GET();
if (httpResponseCode > 0){
Serial.print("HTTP код відповіді: ");
Serial.println(httpResponseCode);
payload = http.getString();
Serial.println(payload);
long index = payload.indexOf("today-temp");
lcd.setCursor(0,1);
lcd.print("Sinoptik.ua: ");
lcd.print(payload.substring(index + 12, index + 15));
lcd.print(" C");
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
delay(100);
http.begin(url2);
httpResponseCode = http.GET();
if (httpResponseCode > 0){
Serial.print("HTTP код відповіді: ");
Serial.println(httpResponseCode);
payload = http.getString();
Serial.println(payload);
char json[payload.length()];
payload.toCharArray(json, payload.length());
JsonDocument doc;
deserializeJson(doc, json);
double temp = doc["hourly"]["temperature_2m"][12];
lcd.setCursor(0,2);
lcd.print("T(12:00) = ");
lcd.print(temp);
lcd.print(" C");
temp = doc["hourly"]["temperature_2m"][8];
lcd1.setCursor(0,0);
lcd1.print("T(8:00) = ");
lcd1.print(temp);
lcd1.print(" C");
temp = doc["hourly"]["temperature_2m"][15];
lcd1.setCursor(0,1);
lcd1.print("T(15:00) = ");
lcd1.print(temp);
lcd1.print(" C");
temp = doc["hourly"]["temperature_2m"][20];
lcd1.setCursor(0,2);
lcd1.print("T(20:00) = ");
lcd1.print(temp);
lcd1.print(" C");
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
} else{
Serial.println("З'єднання Wi-Fi втрачено");
}
}
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);
}
}
}
void callback(char* topic, byte* message, unsigned int length){
String stMessage;
for (int i = 0; i < length; i++) {
stMessage += (char)message[i];
}
//Вивід всіх повідомлень крім власних
if (String(topic) != myTopic){
Serial.print("Отримано повідомлення з топіка ");
Serial.print(topic);
Serial.print(": ");
Serial.println(stMessage);
if (stMessage == "on") digitalWrite(LED, HIGH);
else if(stMessage == "off") digitalWrite(LED, LOW);
lcd.setCursor(0,3);
lcd.print("Last msg:");
lcd.println(stMessage);
}
}