You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
1.8 KiB
73 lines
1.8 KiB
4 years ago
|
const io = require('socket.io-client');
|
||
|
const socket = io('http://localhost:3000');
|
||
|
|
||
|
let timeFlag; // Flag to keep track of time passed
|
||
|
let prevData; // Object to store and compare previously sent data
|
||
|
|
||
|
socket.on('connect', () => {
|
||
|
console.log('Connected to server!'); // Client connects to server
|
||
|
|
||
|
// Only happens the first time the client connects to the server
|
||
|
timeFlag = new Date();
|
||
|
prevData = {
|
||
|
temperature: getTemp(),
|
||
|
humAir: getHumAir(),
|
||
|
humGround: getHumGround(),
|
||
|
airSpeed: getAirSpeed(),
|
||
|
}
|
||
|
});
|
||
|
|
||
|
setInterval(() => {
|
||
|
let data = {
|
||
|
temperature: getTemp(),
|
||
|
humAir: getHumAir(),
|
||
|
humGround: getHumGround(),
|
||
|
airSpeed: getAirSpeed(),
|
||
|
}
|
||
|
|
||
|
const now = new Date();
|
||
|
let timeDiff = now - timeFlag;
|
||
|
timeDiff /= 1000;
|
||
|
|
||
|
// If more than 5 minutes have passed or compareData is true
|
||
|
if ((timeDiff > 5) || compareData(data)) {
|
||
|
prevData = data;
|
||
|
timeFlag = new Date();
|
||
|
socket.emit('data', data);
|
||
|
}
|
||
|
}, 2 * 1000); // Every 30s
|
||
|
|
||
|
// Return a test temp from 1-50
|
||
|
getTemp = () => {
|
||
|
return Math.floor(Math.random() * 50);
|
||
|
}
|
||
|
|
||
|
// Return a test air humidity from 1-100
|
||
|
getHumAir = () => {
|
||
|
return Math.floor(Math.random() * 100);
|
||
|
}
|
||
|
|
||
|
// Return a test ground humidity from 1-100
|
||
|
getHumGround = () => {
|
||
|
return Math.floor(Math.random() * 100);
|
||
|
}
|
||
|
|
||
|
// Return a test wind speed from 1-12
|
||
|
getAirSpeed = () => {
|
||
|
return Math.floor(Math.random() * 12);
|
||
|
}
|
||
|
|
||
|
// Compare data with prevData and determine if they need to be send to server
|
||
|
compareData = (data) => {
|
||
|
for (const key in data) {
|
||
|
if (diff(data[key], prevData[key]) > 10)
|
||
|
return true;
|
||
|
}
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
// Handy function to calculate the % difference
|
||
|
diff = (x, y) => {
|
||
|
return 100 * Math.abs((x - y) / ((x + y) / 2));
|
||
|
}
|