#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <WebSocketsServer.h>
WebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81); //create instance for
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define WIFI_CHANNEL 6
float temperature;
float humidity;
const char* openWeatherMapApiUrl = "http://api.openweathermap.org/data/2.5/weather?lat=20.9813695&lon=105.7803508&units=metric&appid=c04072091e7aaf8429080d6cb76364e0";
String modeTemp = "1";
String jsonString;
bool getWeatherData() {
HTTPClient http;
http.begin(openWeatherMapApiUrl);
int httpCode = http.GET();
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload);
temperature = doc["main"]["temp"].as<float>();
humidity = doc["main"]["humidity"].as<float>();
http.end();
return true;
} else {
http.end();
return false;
}
}
void setup() {
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.print("WiFi connected...!");
Serial.print("Got IP: ");
Serial.print(WiFi.localIP());
delay(100);
server.on("/", showHT);
server.begin();
Serial.println("HTTP server started");
server.begin(); // init the server
webSocket.begin(); // init the Websocketserver
webSocket.onEvent(webSocketEvent); // init the webSocketEvent function when
}
void loop() {
delay(2);
server.handleClient();
webSocket.loop();
}
void webSocketEvent(byte 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:
update_webpage();
break;
case WStype_TEXT:
Serial.println();
Serial.println(payload[0]);
modeTemp = payload[0];
break;
}
}
void update_webpage() {
getWeatherData();
String temp = String(modeTemp == "1" ? temperature : temperature * 1.8 + 32.00) + (modeTemp == "1" ? "Do C" : "Do F");
String hum = String(humidity);
StaticJsonDocument<100> doc;
// create an object
JsonObject object = doc.to<JsonObject>();
object["modeTemp"] = modeTemp;
object["Temp"] = temp;
object["Hum"] = hum;
serializeJson(doc, jsonString); // serialize the object and save teh result to teh string variable.
Serial.println( jsonString ); // print the string for debugging.
webSocket.broadcastTXT(jsonString); // send the JSON object through the websocket
jsonString = ""; // clear the String.
}
void showHT() {
server.send(200, "text/html", sendHtml());
}
String sendHtml() {
String response = "<!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 id=\"title\">Chuyen do F</h1> \
</button> \
</body> \
<script> \
var Socket; \
var modeTemp = '2'; \
document \
.getElementById('BTN_1') \
.addEventListener('click', button_1_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() { \
const title = document.getElementById('title'); \
modeTemp = modeTemp === '1' ? '2' : '1'; \
title.textContent = modeTemp === '1' ? 'Chuyen do C' : 'Chuyen do F'; \
Socket.send(modeTemp); \
} \
window.onload = function (event) { \
init(); \
}; \
</script> \
</html> \
";
return response;
}