#include <WiFi.h>
#include <WebServer.h>
#include <ArduinoJson.h>
#include "DHT.h"
#include <WebSocketsServer.h>
#define DHTPIN 21
#define DHTTYPE DHT22
const char* ssid = "Hữu Tú";
const char* password = "27092002";
int interval = 1000;
unsigned long previousMillis = 0;
String web = "<!DOCTYPE html><html><head> <title>Arduino and ESP32 Websocket</title> <meta name='viewport' content='width=device-width, initial-scale=1.0' /> <meta charset='UTF-8'> <style> body { background-color: #E6D8D5; text-align: center; } </style></head><body> <h1>Temperature: <span id='temp'>-</span></h1> <h1>Humidity: <span id='hum'>-</span></h1> <h1>Received message: <span id='message'>-</span></h1><button type='button' id='BTN_1'> <h1>ON</h1> </button><button type='button' id='BTN_2'> <h1>OFF</h1> </button><button type='button' id='BTN_3'> <h1>Toggle Unit</h1> </button></body><script> var Socket; document.getElementById('BTN_1').addEventListener('click', button_1_pressed); document.getElementById('BTN_2').addEventListener('click', button_2_pressed); document.getElementById('BTN_3').addEventListener('click', button_3_pressed); function init() { Socket = new WebSocket('ws://' + window.location.hostname + ':81/'); Socket.onmessage = function(event) { processCommand(event); }; } function processCommand(event) { var obj = JSON.parse(event.data); document.getElementById('message').innerHTML = obj.PIN_Status; document.getElementById('temp').innerHTML = obj.Temp; document.getElementById('hum').innerHTML = obj.Hum; console.log(obj.PIN_Status); console.log(obj.Temp); console.log(obj.Hum); } function button_1_pressed() { Socket.send('1'); } function button_2_pressed() { Socket.send('0'); } function button_3_pressed() { Socket.send('2'); } window.onload = function(event) { init(); }</script></html>";
String jsonString;
String pin_status = "";
float t;
float h;
bool isCelsius = true;
DHT dht(DHTPIN, DHTTYPE);
WebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);
void setup() {
pinMode(22, OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
server.on("/", []() {
server.send(200, "text/html", web);
});
server.begin();
webSocket.begin();
webSocket.onEvent(webSocketEvent);
dht.begin();
randomSeed(analogRead(0));
}
void loop() {
server.handleClient();
webSocket.loop();
unsigned long currentMillis = millis();
if ((unsigned long)(currentMillis - previousMillis) >= interval) {
update_temp_hum();
update_webpage();
previousMillis = currentMillis;
}
}
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
switch (type) {
case WStype_DISCONNECTED:
Serial.print("WS Type ");
Serial.print(type);
Serial.println(": DISCONNECTED");
break;
case WStype_CONNECTED:
Serial.print("WS Type ");
Serial.print(type);
Serial.println(": CONNECTED");
if (digitalRead(22) == HIGH) {
pin_status = "ON";
update_webpage();
} else {
pin_status = "OFF";
update_webpage();
}
break;
case WStype_TEXT:
Serial.println();
Serial.println(payload[0]);
if (payload[0] == '1') {
pin_status = "ON";
digitalWrite(22, HIGH);
}
if (payload[0] == '0') {
pin_status = "OFF";
digitalWrite(22, LOW);
}
if (payload[0] == '2') {
// Toggle temperature unit between Celsius and Fahrenheit
isCelsius = !isCelsius;
}
break;
}
}
void update_temp_hum() {
h = dht.readHumidity();
t = dht.readTemperature();
if (!isCelsius) {
t = (t * 9.0 / 5.0) + 32.0; // Convert temperature to Fahrenheit
}
}
void update_webpage() {
StaticJsonDocument<100> doc;
JsonObject object = doc.to<JsonObject>();
object["PIN_Status"] = pin_status;
object["Temp"] = t;
object["Hum"] = h;
serializeJson(doc, jsonString);
Serial.println(jsonString);
webSocket.broadcastTXT(jsonString);
jsonString = "";
}