My server (Python – Django) response is a JSON object containig rx and tx expressed in bytes from a networking router, which then I need to show to the user as Download speed in Mbps and Upload speed in Mbps whether it’s in a Chart or a continuosly updating div until the user closes the modal where he sees the info. So the problem is I need to request two times for data to then calculate RX/TX rates and then keep requesting and calculating tx/rx speed rates.
Right now I’m achieving what I expected at my skill level but I certainly know its not the best way, I need your help to do it rigth and as efficient as possible.
Any help would be great, thanks
This is my server response expressed in bytes, I need to request 2 times so I can calculate differences:
{
"rx": "14986885547",
"tx": "228270858519"
}
This is what I have:
const custId = document.getElementById('customerId')
var bytesArr = [];
var timeout = null;
var traffic = (function getTraffic() {
let url = '/customer_detail/traffic/';
fetch(url+custId.innerText, { method: 'GET' })
.then(Result => Result.json())
.then(data => {
console.log(data);
update_data(data);
})
.catch(errorMsg => { console.log(errorMsg); });
return getTraffic;
})();
function update_data(data){
if (bytesArr.length<2){
let arrlenght = bytesArr.push(data);
}else{
bytesArr.shift();
}
calcRates(bytesArr);
}
function calcRates(array){
let startBytesIn, startBytesOut, endBytesIn, endBytesOut, txBytesPerSecond, rxBytesPerSecond = null;
if(array.length==2){
for (let i = 0; i < array.length; i++) {
if(i==0){
startBytesIn = array[i].rx;
startBytesOut = array[i].tx;
}else if(i==1){
endBytesIn = array[i].rx;
endBytesOut = array[i].tx;
}
}
txBytesPerSecond = (endBytesOut-startBytesOut)
rxBytesPerSecond = (endBytesIn-startBytesIn)
console.log('Down Speed Mbps ',(txBytesPerSecond/125000).toFixed(2));
console.log('Up Speed Mbps ',(rxBytesPerSecond/125000).toFixed(2));
}else{
txBytesPerSecond = txBytesPerSecond;
rxBytesPerSecond = rxBytesPerSecond;
}
timeout = setTimeout(traffic, 1000);
}
and right now I’m clearing the timeout when clicking a button.