Skip to content

Commit

Permalink
much more accurate bandwidth calculator
Browse files Browse the repository at this point in the history
  • Loading branch information
LoV432 committed Nov 12, 2023
1 parent 0e76f60 commit 2deac58
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions app/components/boundaries/SpeedBoundarie.client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,9 @@ export default function SpeedWrapper({
}) {
const [speed, setSpeed] = useRecoilState(allSpeedStates);
useEffect(() => {
let interval: NodeJS.Timeout;
(async () => {
interval = await fetchDataAndCalculateMbps(setSpeed);
})();
return () => {
clearInterval(interval);
};
fetchDataAndCalculateMbps(setSpeed);
}, []);
return <>{children}</>; //Everything inside this child will have access to allSpeedStates
return <>{children}</>; // Everything inside this child will have access to allSpeedStates
}

export const allSpeedStates = atom({
Expand All @@ -47,15 +41,25 @@ async function fetchDataAndCalculateMbps(
>
) {
const response = await fetch('/api/get-speed', { cache: 'no-cache' });
let lastFetchTime = Date.now();
const data = (await response.json()) as allUsersSpeedType;
let oldData = data;
let newData = data;
let tempNewData = data;
let totalMbpsUpload = 0;
let totalMbpsDownload = 0;

let interval = setInterval(async () => {
// Apparently you cant use await inside setInterval so we use a while loop
// TODO: Does this need cleanup? or maybe just use https://www.npmjs.com/package/set-interval-async instead and reset to old interval code
while (true) {
await new Promise((resolve) => setTimeout(resolve, 2000)); // TODO: make this dynamic using env vars?
const response = await fetch('/api/get-speed', { cache: 'no-cache' });

// calculate time elapsed since last fetch
const currentTime = Date.now();
const timeElapsed = (currentTime - lastFetchTime) / 1000;
lastFetchTime = currentTime;

const data = (await response.json()) as allUsersSpeedType;
if (response.status !== 200) {
return;
Expand All @@ -68,11 +72,11 @@ async function fetchDataAndCalculateMbps(
let inValue = parseFloat(user.in) - parseFloat(oldUser.in);
inValue = inValue * 8;
inValue = inValue / 1000000;
inValue = inValue / 2;
inValue = inValue / timeElapsed;
let outValue = parseFloat(user.out) - parseFloat(oldUser.out);
outValue = outValue * 8;
outValue = outValue / 1000000;
outValue = outValue / 2;
outValue = outValue / timeElapsed;
user.in = inValue.toFixed(2);
user.out = outValue.toFixed(2);
}
Expand All @@ -91,6 +95,5 @@ async function fetchDataAndCalculateMbps(
totalMbpsDownload: totalMbpsDownload.toFixed(2)
}
]);
}, 2000);
return interval;
}
}

0 comments on commit 2deac58

Please sign in to comment.