2023-12-13 16:32:12 +00:00
|
|
|
var gateway = `ws://${window.location.hostname}/ws`;
|
|
|
|
var websocket;
|
|
|
|
// Init web socket when the page loads
|
2023-12-13 18:30:06 +00:00
|
|
|
window.addEventListener("load", onload);
|
2023-12-13 16:32:12 +00:00
|
|
|
|
|
|
|
function onload(event) {
|
2023-12-13 18:30:06 +00:00
|
|
|
initWebSocket();
|
2023-12-13 16:32:12 +00:00
|
|
|
}
|
|
|
|
|
2023-12-13 18:30:06 +00:00
|
|
|
function getReadings() {
|
|
|
|
websocket.send("getReadings");
|
2023-12-13 16:32:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function initWebSocket() {
|
2023-12-13 18:30:06 +00:00
|
|
|
console.log("Trying to open a WebSocket connection...");
|
|
|
|
websocket = new WebSocket(gateway);
|
|
|
|
websocket.onopen = onOpen;
|
|
|
|
websocket.onclose = onClose;
|
|
|
|
websocket.onmessage = onMessage;
|
2023-12-13 16:32:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// When websocket is established, call the getReadings() function
|
|
|
|
function onOpen(event) {
|
2023-12-13 18:30:06 +00:00
|
|
|
console.log("Connection opened");
|
|
|
|
getReadings();
|
2023-12-13 16:32:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function onClose(event) {
|
2023-12-13 18:30:06 +00:00
|
|
|
console.log("Connection closed");
|
|
|
|
setTimeout(initWebSocket, 2000);
|
2023-12-13 16:32:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Function that receives the message from the ESP32 with the readings
|
|
|
|
function onMessage(event) {
|
2023-12-13 18:30:06 +00:00
|
|
|
console.log(event.data);
|
|
|
|
var myObj = JSON.parse(event.data);
|
|
|
|
var keys = Object.keys(myObj);
|
|
|
|
|
|
|
|
for (var i = 0; i < keys.length - 1; i++) {
|
|
|
|
var key = keys[i];
|
|
|
|
document.getElementById(key).innerHTML = myObj[key];
|
|
|
|
}
|
|
|
|
var today = new Date();
|
|
|
|
var date =
|
|
|
|
today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate();
|
|
|
|
var time =
|
|
|
|
today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
|
|
|
|
var dateTime = date + " " + time;
|
|
|
|
document.getElementById("time").innerHTML = dateTime;
|
|
|
|
}
|