From 6686936465eedf3ea0e8dee88e0b8e8ee3cccb71 Mon Sep 17 00:00:00 2001 From: lef_Tso Date: Sun, 24 Jan 2021 10:42:40 +0000 Subject: [PATCH] Add Client --- client/index.js | 72 +++++++++++++++++++++++++++++++++++++++++++++ client/package.json | 17 +++++++++++ 2 files changed, 89 insertions(+) create mode 100644 client/index.js create mode 100644 client/package.json diff --git a/client/index.js b/client/index.js new file mode 100644 index 0000000..3183126 --- /dev/null +++ b/client/index.js @@ -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)); +} diff --git a/client/package.json b/client/package.json new file mode 100644 index 0000000..fcb6db9 --- /dev/null +++ b/client/package.json @@ -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" + } +}