#include "Wire.h"
#include "SPI.h"
#include "RTClib.h"
#include "LiquidCrystal_I2C.h"
#include <ArduinoJson.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include "DHTesp.h"
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const String endpoint = "http://api.openweathermap.org/data/2.5/weather?q=Vinnytsia,ua,pt&APPID=";
const String key = "3b8d3da2aeb98961bd150229e0e421d4";
LiquidCrystal_I2C lcd(0x27, 16, 2);
RTC_DS1307 rtc;
DHTesp dht;
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#define ssid "Wokwi-GUEST"
#define password ""
WiFiClientSecure espClient; // for no secure connection use WiFiClient instead of WiFiClientSecure
//WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int sensor1 = 0;
float sensor2 = 0;
int command1 = 0;
int command2 = 0;
const char* mqtt_server = "650e8d8eb31f42fca58099a38e91aff8.s1.eu.hivemq.cloud"; // replace with your broker url
const char* mqtt_username = "Abdul4ik02"; // you don't need the username and password for public connection
const char* mqtt_password = "Shaurmatop69";
const int mqtt_port = 8883;
const char* sensor1_topic = "sensor1";
const char* sensor2_topic = "sensor2";
//const char* sensor2_topic="sensor3";
const char* command1_topic = "command1";
const char* command2_topic = "command2";
static const char *root_ca PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTAT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NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
)EOF";
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP8266Client-"; // Create a random client ID
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
Serial.println("connected");
client.subscribe(command1_topic); // *********subscribe the topics here
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying
delay(5);
}
}
}
void callback(char* topic, byte* payload, unsigned int length) {
String incommingMessage = "";
for (int i = 0; i < length; i++) incommingMessage+=(char)payload[i];
////////////////////////////////////////////////
Serial.println("Message arrived ["+String(topic)+"]"+incommingMessage);
if( strcmp(topic,command1_topic) == 0){
if (incommingMessage.equals("0")) digitalWrite(17, HIGH); // Turn the LED on
else digitalWrite(17, LOW); // Turn the LED off
}
}
void setup_wifi() {
delay(10);
Serial.print("\nConnecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(50);
Serial.print(".");
}
randomSeed(micros());
Serial.println("\nWiFi connected\nIP address: ");
Serial.println(WiFi.localIP());
}
///////////////////////////////////////////////////
//======================================= publising as string
void publishMessage(const char* topic, String payload , boolean retained){
if (client.publish(topic, payload.c_str(), true))
Serial.println("Message publised ["+String(topic)+"]: "+payload);
}
class Timer{
public:
void timer_start(){
if(timer==0){
timer=millis();
}
if (millis() - timer >=30000){
active=true;
timer=millis();
}
else{
active=false;
}
}
bool get_status(){
return active;
}
private:
bool active=true;
unsigned long timer = 0;
};
Timer t;
class Weather {
public:
int temp=0;
int humidity=0;
void set_parametrs(int temp1, int hum){
temp=temp1-273,15;
humidity=hum;
}
void displayToLcd() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Weather");
lcd.setCursor(0, 1);
lcd.print("Temp: ");
lcd.print(temp);
lcd.print("C");
lcd.print(" Hum: ");
lcd.print("%");
lcd.print(humidity);
}
};
Weather w;
class RTCTime {
public:
int year;
int month;
int day;
int hour;
int minute;
int second;
void setParameters() {
year = rtc.now().year();
month = rtc.now().month();
day = rtc.now().day();
hour = rtc.now().hour();
minute = rtc.now().minute();
second = rtc.now().second();
}
void display() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(format(day));
lcd.print('.');
lcd.print(format(month));
lcd.print('.');
lcd.print(year);
lcd.setCursor(0, 1);
lcd.print(format(hour));
lcd.print(':');
lcd.print(format(minute));
lcd.print('.');
lcd.print(format(second));
}
private:
int format(int value) {
// if (String(value).length() == 1) {
// return "0" + value;
// }
// return String(value);
return value;
}
};
RTCTime rt;
void handleReceivedMessage(String message)
{
StaticJsonDocument<500> doc; //Memory pool. Размер с запасом
//разбор полученного сообщения как форматированного текста JSON
DeserializationError error = deserializeJson(doc, message);
// Если разбор прошел успешно
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return;
}
int temp = doc["main"]["temp"];
int humidity = doc["main"]["humidity"];
w.set_parametrs(temp,humidity);
}
int status = 1;
void displayInfo() {
if (status % 3 == 0) {
w.displayToLcd();
}
}
void setup() {
dht.setup(15, DHTesp::DHT22);
rtc.begin();
//Serial.begin(115200);
WiFi.begin(ssid, password);
lcd.init();
lcd.backlight();
Serial.println("Hello");
Serial.begin(9600);
while (!Serial) delay(1);
setup_wifi();
pinMode(2, OUTPUT); // Initialize the BUILTIN_LED pin as an output
#ifdef ESP8266
espClient.setInsecure();
#else // for the ESP32
espClient.setCACert(root_ca); // enable this line and the the "certificate" code for secure connection
#endif
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}
void processRtc() {
rt.setParameters();
rt.display();
}
void processDht() {
float temp = dht.getTemperature();
float hum = dht.getHumidity();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp in room");
lcd.setCursor(0, 1);
lcd.print("Temp: ");
lcd.print(temp);
sensor1 = temp;
sensor2 = hum;
publishMessage(sensor1_topic,String(sensor1),true);
publishMessage(sensor2_topic,String(sensor2),true);
}
void processWeather() {
if ((WiFi.status() == WL_CONNECTED))
{
w.displayToLcd();
if(t.get_status()==true){
// создаем объект для работы с HTTP
HTTPClient http;
// подключаемся к веб-странице OpenWeatherMap с указанными параметрами
http.begin(endpoint + key);
int httpCode = http.GET(); // Делаем запрос
// проверяем успешность запроса
if (httpCode > 0)
{
// выводим ответ сервера
String payload = http.getString();
Serial.println(httpCode);
handleReceivedMessage(payload);
}
else {
Serial.println("Ошибка HTTP-запроса");
}
http.end(); // освобождаем ресурсы микроконтроллера
}
}
}
int state = 0;
int last = 0;
int lastProcess = 0;
void loop() {
// if (!client.connected()) reconnect();
// client.loop();
Serial.println(millis() - last);
if (millis() - last >= 5000) {
last = millis();
state++;
}
if (millis() - lastProcess >= 1000) {
switch (state % 3) {
case 0: processRtc();
Serial.println("A");
break;
case 1: processWeather();
Serial.println("B");
break;
case 2: processDht();
break;
default:
break;
}
lastProcess = millis();
}
}