Skip to content

Commit

Permalink
Cambios a las rondas, calculo del tiempo en rango, formateo de archivos
Browse files Browse the repository at this point in the history
Co-authored-by: Daniel Fernández Ocaña <[email protected]>
  • Loading branch information
Polinss3 and DaniFdz committed May 25, 2024
1 parent da0e9fe commit 1f3061f
Show file tree
Hide file tree
Showing 11 changed files with 66 additions and 166 deletions.
18 changes: 13 additions & 5 deletions web/src/components/Grafica.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import { useStore } from "@nanostores/react";
import { dataStore } from "@/stores/dataStore";
import { displayRefreshRateStore } from "@/stores/displayRefreshRateStore";
import { fetchStatusStore } from "@/stores/fetchStatusStore"; // Import the new store
import { timeInRangeStore } from "@/stores/timeInRangeStore";
import { timeElapsedStore } from "@/stores/timeElapsedStore";
import { internalRefreshRateStore } from "@/stores/internalRefreshRateStore";
import type { Data } from "@/types/Data";

const PUBLIC_BASE_URL = import.meta.env.PUBLIC_BASE_URL ?? 'http://localhost:3000';
Expand All @@ -20,7 +23,9 @@ const N_DATA = 500;
export default function Grafica() {
const displayRefreshRate = useStore(displayRefreshRateStore);
const fetchStatus = useStore(fetchStatusStore); // Get fetch status
const internalRefreshRate = useStore(internalRefreshRateStore)
const [data, setData] = useState<Data[]>([]);
let intervalId: NodeJS.Timeout;

useEffect(() => {
console.log(`Base url: ${PUBLIC_BASE_URL}`);
Expand All @@ -39,9 +44,9 @@ export default function Grafica() {
}

const body = await resp.json();
console.log(body);
// console.log(body);

let new_data: Data[] = [];
let new_data: Data[] = dataStore.get();
for (let i = 0; i < body.temp_max.length; i++) {
new_data.push({
temp_min: body.temp_min[i],
Expand All @@ -50,14 +55,17 @@ export default function Grafica() {
timestamp: body.timestamp[i],
} satisfies Data);
}
dataStore.set([...dataStore.get(), ...new_data]);
setData(dataStore.get().slice(-N_DATA));
dataStore.set(new_data);
setData(new_data.slice(-N_DATA));

timeInRangeStore.set(new_data.filter((d) => d.temperature >= d.temp_min && d.temperature <= d.temp_max).length * internalRefreshRate);
timeElapsedStore.set(new_data.length * internalRefreshRate)
// console.log(timeInRangeStore.get());
} catch (error) {
console.warn(`No se pudo recibir los datos del servidor; Elapsed: ${Date.now() - start}ms`);
}
};

let intervalId: NodeJS.Timeout;

if (fetchStatus === 'start') {
intervalId = setInterval(fetchData, displayRefreshRate);
Expand Down
4 changes: 3 additions & 1 deletion web/src/components/Inputs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useToast } from './ui/use-toast';
import Button from './Button';
import { useStore } from '@nanostores/react';
import { displayRefreshRateStore } from '@/stores/displayRefreshRateStore';
import { internalRefreshRateStore } from '@/stores/internalRefreshRateStore';
import { roundDurationStore } from '@/stores/roundDurationStore'; // New store

const Inputs = () => {
Expand Down Expand Up @@ -73,7 +74,8 @@ const Inputs = () => {
async function setParams(): Promise<void> {
if (validateInputs()) {
displayRefreshRateStore.set(parseInt(refreshRate));
roundDurationStore.set(roundDuration.split(';').map(Number)); // Store round duration
roundDurationStore.set(roundDuration.split(';').map(Number).reduce((p, a) => p+a, 0))
internalRefreshRateStore.set(parseInt(internalRate))

const password = localStorage.getItem('password') ?? '';

Expand Down
30 changes: 30 additions & 0 deletions web/src/components/RoundData.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import React from "react";
import { useStore } from "@nanostores/react";
import { timeInRangeStore } from "@/stores/timeInRangeStore";
import { timeElapsedStore } from "@/stores/timeElapsedStore";
import { roundDurationStore } from "@/stores/roundDurationStore";
import { roundNumberStore } from "@/stores/roundNumberStore";

export default function RoundData() {
const timeInRange = useStore(timeInRangeStore);
const timeElapsed = useStore(timeElapsedStore);
const roundDuration = useStore(roundDurationStore);

const roundNumber = useStore(roundNumberStore);

return roundNumber === 0 ? (
<></>
) : (
<div>
<h4>Ronda {roundNumber}</h4>
<p>
<span>Duración total de la ronda:</span>
{roundDuration}s
</p>
<p>
<span>Tiempo en el rango:</span>
<span>{timeInRange / 1000}s</span>/ {timeElapsed / 1000}s
</p>
</div>
);
}
163 changes: 5 additions & 158 deletions web/src/components/StartStop.tsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,24 @@
import React, { useState, useEffect } from "react";
import Button from "@/components/Button";
import { useToast } from "./ui/use-toast";
import { useStore } from "@nanostores/react";
import { displayRefreshRateStore } from "@/stores/displayRefreshRateStore";
import { fetchStatusStore } from "@/stores/fetchStatusStore";
import { dataStore } from "@/stores/dataStore";
import { roundDurationStore } from "@/stores/roundDurationStore"; // New store
import { roundNumberStore } from "@/stores/roundNumberStore";

const PUBLIC_BASE_URL =
import.meta.env.PUBLIC_BASE_URL ?? "http://localhost:3000";

export default function StartStop() {
const { toast } = useToast();
const displayRefreshRate = useStore(displayRefreshRateStore);
const roundDurations = useStore(roundDurationStore); // Get round durations
const [globalTimeLeft, setGlobalTimeLeft] = useState(0);
const [roundTimeLeft, setRoundTimeLeft] = useState(0);
const [isRunning, setIsRunning] = useState(false);
const [currentRound, setCurrentRound] = useState(0);
const [timeInRange, setTimeInRange] = useState(0); // State for time in range
const [dentroDeRango, setDentroDeRango] = useState(0); // State for count in range
const fetchStatus = useStore(fetchStatusStore);


const handleStart = async () => {
fetchStatusStore.set("start");
dataStore.set([]);
setIsRunning(true);
const response = await startRonda();
setCurrentRound(0);
roundNumberStore.set(roundNumberStore.get()+1)
await startRonda();
};

const handleStop = async () => {
Expand All @@ -39,8 +30,7 @@ export default function StartStop() {
},
body: JSON.stringify({ data: dataStore.get() }),
});
stopRonda();
setIsRunning(false);
await stopRonda();
};

const startRonda = async () => {
Expand All @@ -57,11 +47,6 @@ export default function StartStop() {
title: "Ok",
description: "Ronda iniciada correctamente",
});
const globalDuration =
roundDurations.reduce((acc, curr) => acc + curr, 0) * 10;
setGlobalTimeLeft(globalDuration);
console.log(`Round durations: ${roundDurations}`);
setRoundTimeLeft(roundDurations[0] * 10);
return true;
} catch {
toast({
Expand Down Expand Up @@ -101,117 +86,6 @@ export default function StartStop() {
}
};

useEffect(() => {
let globalInterval: NodeJS.Timeout;
let roundInterval: NodeJS.Timeout;

if (isRunning) {
globalInterval = setInterval(() => {
setGlobalTimeLeft((prev) => Math.max(prev - 1, 0));
}, 100);

roundInterval = setInterval(() => {
setRoundTimeLeft((prev) => {
if (prev - 1 <= 0) {
const nextRound = currentRound + 1;
if (nextRound < roundDurations.length) {
setCurrentRound(nextRound);
setRoundTimeLeft(roundDurations[nextRound] * 10);
} else {
setIsRunning(false);
clearInterval(globalInterval);
clearInterval(roundInterval);
return 0;
}
}
return prev - 1;
});
}, 100);
}

return () => {
clearInterval(globalInterval);
clearInterval(roundInterval);
};
}, [isRunning, currentRound, roundDurations]);

useEffect(() => {
if (isRunning) {
setRoundTimeLeft(roundDurations[currentRound] * 10);
}
}, [currentRound, roundDurations, isRunning]);

useEffect(() => {
console.log(`Base url: ${PUBLIC_BASE_URL}`);

const timeInRange = async () => {
const start = Date.now();
try {
const resp = await fetch(`${PUBLIC_BASE_URL}/temp`, {
headers: {
"Content-Type": "application/json",
},
});
if (!resp.ok) {
throw new Error(`HTTP error! status: ${resp.status}`);
}

const body = await resp.json();
console.log("ponemos algo por aqui1");
console.log(body);
console.log(body.temp_max);
console.log(body.temp_min);
console.log(body.temperatures);
console.log("ponemos algo por aqui2");

// Variables para calcular el tiempo en rango
let timeInRange = 0;
let dentroDeRango = 0;
const { temp_min, temp_max, temperatures, timestamp } = body;

// Calcular el tiempo y la cantidad de veces en el que la temperatura está dentro del rango
for (let i = 0; i < temperatures.length; i++) {
if (
temperatures[i] >= temp_min[i] &&
temperatures[i] <= temp_max[i]
) {
dentroDeRango++; // Incrementar el contador
if (i === 0) {
timeInRange += timestamp[i + 1] - timestamp[i];
} else {
timeInRange += timestamp[i] - timestamp[i - 1];
}
}
}

setTimeInRange(timeInRange); // Set state for time in range
setDentroDeRango(dentroDeRango); // Set state for count in range

console.log(`Tiempo en rango: ${timeInRange}ms`);
console.log(
`Cantidad de veces dentro de rango: ${dentroDeRango}`
);
} catch (error) {
console.warn(
`No se pudo recibir los datos del servidor; Elapsed: ${
Date.now() - start
}ms`
);
}
};
let intervalId: NodeJS.Timeout;

if (fetchStatus === "start") {
intervalId = setInterval(timeInRange, displayRefreshRate);
} else if (fetchStatus === "stop") {
clearInterval(intervalId);
// Cleat the graph
dataStore.set([]);
}

return () => clearInterval(intervalId);
}, [displayRefreshRate, fetchStatus]);

return (
<div className="flex flex-col w-[1000px] gap-4 mx-4 my-8">
<div className="flex flex-row gap-4">
Expand All @@ -229,33 +103,6 @@ export default function StartStop() {
</Button>
</div>
<hr className="w-full my-4 bg-fountain-blue-700 h-1" />
<div className="flex flex-col items-center mt-4">
<div className="text-guardsman-red-700">
<span className="flex flex-col items-center text-xl text-fountain-blue-500">
Round {currentRound + 1}
</span>
<br />
<span className="text-fountain-blue-500">
Global Time Left:{" "}
</span>
<span>{Math.round(globalTimeLeft / 10)} seconds</span>
<span> / {globalTimeLeft} deciseconds</span>
</div>
<div className="text-guardsman-red-700">
<span className="text-fountain-blue-500">
Round Time Left:{" "}
</span>
<span>{Math.round(roundTimeLeft / 10)} seconds</span>
<span> / {roundTimeLeft} deciseconds</span>
</div>
<div className="text-guardsman-red-700">
<span className="text-fountain-blue-500">
Time In Range:{" "}
</span>
<span>{Math.round(timeInRange / 1000)} seconds</span>
<span> / {Math.round(timeInRange / 100)} deciseconds</span>
</div>
</div>
</div>
);
}
2 changes: 2 additions & 0 deletions web/src/pages/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import Layout from "@/layouts/Layout.astro";
import StartStop from "@/components/StartStop.tsx";
import Inputs from "@/components/Inputs.tsx";
import Grafica from "@/components/Grafica";
import RoundData from "@/components/RoundData";
---

<Layout>
<main class="">
<Inputs client:load />
<Grafica client:load />
<StartStop client:load />
<RoundData client:load />
</main>
</Layout>
File renamed without changes.
3 changes: 3 additions & 0 deletions web/src/stores/internalRefreshRateStore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { atom } from "nanostores";

export const internalRefreshRateStore = atom<number>(0);
3 changes: 1 addition & 2 deletions web/src/stores/roundDurationStore.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// roundDurationStore.ts
import { atom } from 'nanostores';

export const roundDurationStore = atom<number[]>([]);
export const roundDurationStore = atom<number>(0);
3 changes: 3 additions & 0 deletions web/src/stores/roundNumberStore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { atom } from 'nanostores';

export const roundNumberStore = atom<number>(0);
3 changes: 3 additions & 0 deletions web/src/stores/timeElapsedStore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { atom } from 'nanostores';

export const timeElapsedStore = atom<number>(0);
3 changes: 3 additions & 0 deletions web/src/stores/timeInRangeStore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { atom } from 'nanostores';

export const timeInRangeStore = atom<number>(0);

0 comments on commit 1f3061f

Please sign in to comment.