Add WebSocket connection error handling and JSON in to array

This commit is contained in:
Dano van den Bosch
2024-03-05 13:38:09 +01:00
parent 902031cfd5
commit d127a6001d
2 changed files with 36 additions and 29 deletions

View File

@@ -10,6 +10,7 @@ let valueArray = [1, 2, 3, 4, 5];
let newValueArray = [4, 5, 6];
let myValue = 1;
let intervalDelay = 50;
const sendorData = [];
// const socket = new WebSocket("ws://127.0.0.1:8001");
@@ -53,7 +54,14 @@ function openConnection() {
// Message handling
socket.addEventListener("message", (event) => {
console.log('Message from server:', event.data);
try {
const jsonData = JSON.parse(event.data);
// Use the parsed JSON data as needed
handleIncomingData(jsonData);
} catch (error) {
console.error("Error parsing JSON:", error);
}
});
// Close handling
@@ -62,6 +70,7 @@ function openConnection() {
// Attempt to reconnect
setTimeout(openConnection, 1000); // Retry after 1 second
});
console.log("Connected to the WebSocket server!!!!!!!!");
}
// Open the connection
@@ -69,34 +78,29 @@ openConnection();
function handleIncomingData(data) {
temperature = data.Temp;
humidity = data.Humi;
CO2 = data.eCO2;
TVOC = data.TVOC;
// console.log("Temperature: ", temperature);
// console.log("Humidity: ", humidity);
// console.log("CO2: ", CO2);
// console.log("TVOC: ", TVOC);
// socket.onopen = function(e) {
// alert("[open] Connection established");
// alert("Sending to server");
// socket.send("My name is John");
// };
// socket.onmessage = function(event) {
// // alert(`[message] Data received from server: ${event.data}`);
// console.log("Data received from server: ", event.data);
// };
// socket.addEventListener("message", (event) => {
// console.log(event.data);
// });
// function openPort() {
// socket.addEventListener('open', function (event) {
// console.log('Connected to the WebSocket server');
// });
// console.log("Connected to the WebSocket server");
// }
// socket.addEventListener('message', function (event) {
// console.log('Message from server:', event.data);
// // Here you can handle the received message and update your UI accordingly
// });
sendorData.push({
'temp': temperature,
'humi': humidity,
'CO2': CO2,
'TVOC': TVOC,
});
console.log(sendorData);
if (sendorData.length >= 10) {
sendorData.shift();
}
}
function pushArray(array) {
for (let i = 0; i < 10; i++) {
@@ -249,4 +253,7 @@ function createNodeData(node) {
createNodeData(1);
createNodeData(2);
createNodeData(3);
createNodeData(4);
createNodeData(4);
// openConnection();