// Libraries
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <time.h>
// Rele
int relay = 22;
// Variables
double t_casa;
double t_mansarda;
// WiFi - MQTT variables
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.hivemq.com";
const char* stopic = "temperature/locali2";
WiFiClient espClient;
PubSubClient client(espClient);
// Messages variables
String message_received;
int sender = 0;
double temperature = 0;
// Setup. of the WiFi connection of the board
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
// Setup. of the MQTT connection
void setup_MQTT(){
client.setSocketTimeout(60);
client.setKeepAlive(5000); // Time in which the MQTT connection to the server is alive
client.setServer(mqtt_server, 1883);
client.setCallback(callback); // Set callback function to receive messages published on the topic
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP8266_Receive", "", "" )) { //Sign in to the broker
Serial.println("Connected to broker");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
client.subscribe(stopic); // MQTT subscription to the topic
}
// Callback function
void callback(char* topic, byte* payload, unsigned int length) {
message_received = ""; // Cancellation of the content of the message_received string to process only the new messages
for (int i = 0; i < length; i++) {
message_received = message_received + (char)payload[i];
}
Serial.print(message_received); // Print the messsage on the terminal
//Deserialize BEACON
DynamicJsonDocument message(600);
// Deserialize the JSON document
DeserializationError error1 = deserializeJson(message, message_received);
// Test if parsing succeeds
if (error1) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error1.f_str());
return;
}
sender = message["Sender"];
temperature = message["Temperature"];
}
void setup() {
Serial.begin(115200);
pinMode(relay, OUTPUT);
digitalWrite(relay, LOW);
setup_wifi();
setup_MQTT();
}
void loop() {
if(sender == 1){
t_mansarda = temperature;
}
if(sender == 2){
t_casa = temperature;
}
if(t_mansarda < 20 && t_mansarda != 0 && t_casa > 20){
digitalWrite(relay, HIGH);
}
else{
digitalWrite(relay,LOW);
}
client.loop();
}