lef_Tso
4 years ago
2 changed files with 89 additions and 0 deletions
@ -0,0 +1,72 @@ |
|||||
|
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)); |
||||
|
} |
@ -0,0 +1,17 @@ |
|||||
|
{ |
||||
|
"name": "client", |
||||
|
"version": "1.0.0", |
||||
|
"description": "", |
||||
|
"main": "index.js", |
||||
|
"scripts": { |
||||
|
"run": "node index.js", |
||||
|
"dev": "nodemon index.js" |
||||
|
}, |
||||
|
"keywords": [], |
||||
|
"author": "", |
||||
|
"license": "ISC", |
||||
|
"dependencies": { |
||||
|
"nodemon": "^2.0.7", |
||||
|
"socket.io-client": "^3.1.0" |
||||
|
} |
||||
|
} |
Loading…
Reference in new issue