#include <WiFi.h>
#include "PubSubClient.h"
#include <ArduinoJson.h>
const char *MQTTServer = "broker.emqx.io";
const char *MQTT_Topic = "DENGT"; // Topic để nhận dữ liệu
const char *MQTT_ID = "a881b542-8dda-4d4d-bdd4-e8aa5ea3cbda";
int Port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
const int ledPins[] ={2,4,18}; // Các chân LED
const int ledCount = sizeof(ledPins) / sizeof(ledPins[0]);
void WIFIConnect() {
Serial.println("Connecting to SSID: Wokwi-GUEST");
WiFi.begin("Wokwi-GUEST", "");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void MQTT_Reconnect() {
while (!client.connected()) {
if (client.connect(MQTT_ID)) {
Serial.println("MQTT connected");
client.subscribe(MQTT_Topic);
Serial.print("Subscribed to topic: ");
Serial.println(MQTT_Topic);
} else {
Serial.print("Failed to connect, 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.println(topic);
String jsonMessage;
for (unsigned int i = 0; i < length; i++) {
jsonMessage += (char)message[i];
}
Serial.print("Message: ");
Serial.println(jsonMessage);
// Parse JSON message
int times[ledCount] = {0}; // Thời gian cho từng LED
if (jsonMessage.length() > 0) {
// Tách giá trị thời gian từ JSON
DynamicJsonDocument doc(256); // Dùng thư viện ArduinoJson
DeserializationError error = deserializeJson(doc, jsonMessage);
if (!error) {
times[0] = doc["greenTime"] | 0; // Lấy thời gian bật LED xanh
times[1] = doc["yellowTime"] | 0; // Lấy thời gian bật LED vàng
times[2] = doc["redTime"] | 0; // Lấy thời gian bật LED đỏ
// Điều khiển các LED
for (int i = 0; i < ledCount; i++) {
if (times[i] > 0) {
digitalWrite(ledPins[i], HIGH);
delay(times[i] * 1000); // Bật LED theo thời gian nhận được
digitalWrite(ledPins[i], LOW);
}
}
} else {
Serial.println("Error parsing JSON");
}
}
}
void setup() {
Serial.begin(115200);
WIFIConnect();
client.setServer(MQTTServer, Port);
client.setCallback(callback);
for (int i = 0; i < ledCount; i++) {
pinMode(ledPins[i], OUTPUT);
digitalWrite(ledPins[i], LOW);
}
}
void loop() {
if (!client.connected()) {
MQTT_Reconnect();
}
client.loop();
}