#include <WiFi.h>
#include "PubSubClient.h"
#include "ArduinoJson.h"
#include "DHTesp.h"
const int DHT_PIN = 15;
DHTesp dhtSensor;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqttServer = "broker.hivemq.com";
int port = 1883;
String stMac;
char clientId[50];
WiFiClient espClient;
PubSubClient client(espClient);
const int ledPin = 32;
const int ledPin2 = 25;
const int ledPin3 = 14;
void setup() {
Serial.begin(9600);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
wifiConnect();
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println(WiFi.macAddress());
stMac = WiFi.macAddress();
stMac.replace(":", "_");
Serial.println(stMac);
client.setServer(mqttServer, port);
client.setCallback(callback);
pinMode(ledPin, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
}
void wifiConnect() {
WiFi.begin(ssid, password,6);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
void mqttReconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
sprintf(clientId, "clientId_%s", stMac.c_str());
if (client.connect(clientId)) {
Serial.print(clientId);
Serial.println(" connected");
client.subscribe("topicName/led");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String stMessage;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
stMessage += (char)message[i];
}
Serial.println();
if (String(topic) == "topicName/led") {
StaticJsonDocument<200> doc;
deserializeJson(doc, stMessage);
int val1 = doc["led1"];
int val2 = doc["led2"];
int val3 = doc["led3"];
Serial.println(val1);
Serial.println(val2);
Serial.println(val3);
Serial.print("Changing output to ");
if(val1 == 1){
Serial.println("on");
digitalWrite(ledPin, HIGH);
}
else if(val1 == 0){
Serial.println("off");
digitalWrite(ledPin, LOW);
}
if(val2 == 1){
digitalWrite(ledPin2, HIGH);
}
else{
digitalWrite(ledPin2, LOW);
}
if(val3 == 1){
digitalWrite(ledPin3, HIGH);
}
else{
digitalWrite(ledPin3, LOW);
}
}
}
void loop() {
TempAndHumidity data = dhtSensor.getTempAndHumidity();
int temp = data.temperature;
int humid = data.humidity;
String sdata = "{\"ClientID\": \"ClientID-Tuan_dz\",\"Temp\": " + String(temp)+ ", \"Humid\": " + String(humid) + "}";
if (!client.connected()) {
mqttReconnect();
}
else{
Serial.println("Sending data to broker ...");
client.publish("/out/esp", sdata.c_str());
delay(3000);
}
client.loop();
}