#include <WiFi.h>
#include "PubSubClient.h"
const char * MQTTServer = "broker.emqx.io";
const char* leds = "IoT/leds";
// Tạo ID ngẫu nhiên tại: https://www.guidgen.com/
const char * MQTT_ID = "8748c87e-736d-4327-9e75-a52a0e497dd8";
int Port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
const int ledPins[] = {5,17,16};
// Biến toàn cục để theo dõi trạng thái LED và thời gian
unsigned long ledTimers[3];
bool ledStates[3] = {false, false, false};
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.print("WiFi connected");
Serial.print(", IP address: ");
Serial.println(WiFi.localIP());
}
void MQTT_Reconnect() {
while (!client.connected()) {
if (client.connect(MQTT_ID)) {
Serial.print("MQTT Topic: ");
Serial.print(leds);
Serial.println(" connected");
client.subscribe(leds);
Serial.println("");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void activateLed(int ledIndex, int duration) {
digitalWrite(ledPins[ledIndex], HIGH);
ledStates[ledIndex] = true;
ledTimers[ledIndex] = millis() + duration * 1000; // Set the time to turn off
}
void updateLeds() {
for (int i = 0; i < 3; i++) {
if (ledStates[i] && millis() >= ledTimers[i]) {
digitalWrite(ledPins[i], LOW);
ledStates[i] = false;
}
}
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.println(topic);
Serial.print("Message: ");
char strMessage[length + 1];
for (int i = 0; i < length; i++) {
strMessage[i] = (char)message[i];
}
strMessage[length] = '\0';
String strPayload = String(strMessage);
Serial.println(strPayload);
int firstSemiColon = strPayload.indexOf(';');
int secondSemiColon = strPayload.indexOf(';', firstSemiColon + 1);
int timeLed1 = strPayload.substring(0, firstSemiColon).toInt();
int timeLed2 = strPayload.substring(firstSemiColon + 1, secondSemiColon).toInt();
int timeLed3 = strPayload.substring(secondSemiColon + 1).toInt();
if (timeLed1 > 0) activateLed(0, timeLed1);
if (timeLed2 > 0) activateLed(1, timeLed2);
if (timeLed3 > 0) activateLed(2, timeLed3);
// Send back a confirmation message to the web application
String confirmation = String("LED1: ") + timeLed1 + "s, LED2: " + timeLed2 + "s, LED3: " + timeLed3 + "s";
client.publish(leds, confirmation.c_str());
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
WIFIConnect();
client.setServer(MQTTServer, Port);
client.setCallback(callback);
for (int i = 0; i < 3; i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop() {
if (!client.connected()) {
MQTT_Reconnect();
}
client.loop();
updateLeds();
delay(10);
}
/*
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Led</title>
</head>
<body>
<div class="container">
<div class="group">
<h2>Thời gian đèn xanh bật (đơn vị giây)</h2>
<input type="number" id="led1">
</div>
<div class="group">
<h2>Thời gian đèn vàng bật (đơn vị giây)</h2>
<input type="number" id="led2">
</div>
<div class="group">
<h2>Thời gian đèn đỏ bật (đơn vị giây)</h2>
<input type="number" id="led3">
</div>
<button type="submit" id="btnLed" style="background-color: red; color: white; width:100px; margin-top:50px;">Lưu</button>
<div id="statusMessage" style="margin-top: 50px ;"></div>
</div>
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script>
const client = mqtt.connect('ws://broker.emqx.io:8083/mqtt');
client.on('connect', function() {
console.log('Connected to MQTT broker');
});
document.getElementById('btnLed').addEventListener('click', function() {
let led1 = document.getElementById('led1').value || 0;
let led2 = document.getElementById('led2').value || 0;
let led3 = document.getElementById('led3').value || 0;
let mess = `${led1};${led2};${led3}`;
client.publish('IoT/leds',mess);
document.getElementById('statusMessage').innerHTML = 'Thao tác thành công';
});
</script>
</body>
</html>
*/