#include <WiFi.h>
#include <PubSubClient.h>
#include <DHTesp.h>
const int DHT_PIN = 13;
const int LED_PIN = 4;
DHTesp dht;
// Update these with values suitable for your network.
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
float temp = 0;
float hum = 0;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
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(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("Connected to " + clientId);
// Once connected, publish an announcement...
client.publish("/PTIT_Test/p/mqtt1", "PTIT_Test");
// ... and resubscribe
client.subscribe("/PTIT_Test/p/led2");
//client.subscribe("/PTIT_Test/p/temp1");
//client.subscribe("/PTIT_Test/p/hum1");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(2, OUTPUT);
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
setup_wifi();
client.setServer(mqtt_server, 1883);
dht.setup(DHT_PIN, DHTesp::DHT22);
}
const char* ledTopic = "/PTIT_Test/p/led2";
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Nhận dữ liệu từ topic: ");
Serial.println(topic);
Serial.print("Nội dung: ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
if (strcmp(topic, ledTopic) == 0) {
// Xử lý thông điệp cho đèn LED
if (payload[0] == '0') {
digitalWrite(LED_PIN, LOW); // Tắt đèn LED
} else if (payload[0] == '1') {
digitalWrite(LED_PIN, HIGH); // Bật đèn LED
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
TempAndHumidity data = dht.getTempAndHumidity();
int led_state = digitalRead(LED_PIN);
if (led_state == HIGH){
client.publish("/PTIT_Test/p/led1", "ON");
Serial.println("Led On");
}
if (led_state == LOW){
client.publish("/PTIT_Test/p/led1", "OFF");
Serial.println("Led Off");
}
String temp = String(data.temperature, 2);
client.publish("/PTIT_Test/p/temp1", temp.c_str());
String hum = String(data.humidity, 1);
client.publish("/PTIT_Test/p/hum1", hum.c_str());
Serial.print("Temperature: ");
Serial.println(temp);
Serial.print("Humidity: ");
Serial.println(hum);
}
}