From c461eda661e4144e8798ca90ab9c6b0f9a1750df Mon Sep 17 00:00:00 2001 From: Noah Metz Date: Tue, 2 Jan 2024 20:36:30 -0700 Subject: [PATCH] Got timer working --- src/routes/+page.svelte | 46 ++++++++++++++++++++++++++++++----------- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 3e6e37d..a452458 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -15,9 +15,9 @@ let score_red = 0; let score_blue = 0; let teams_red = ["6659A", "6659B"]; let teams_blue = ["210Z", "210Y"]; -let timer_running = false; let timer_start = undefined; -let timer_duration = undefined; +let timer_end = undefined; +let timer_next_tick = undefined; let timer = "Scheduled"; const client = mqtt.connect("ws://127.0.0.1:8883"); @@ -49,6 +49,28 @@ client.on("connect", () => { }); }); +function stop_timer() { + if(timer_next_tick === undefined) { + } else { + clearInterval(timer_next_tick); + timer_next_tick = undefined; + } +} + +function tick_timer() { + const now = new Date() + const time_diff = timer_end - now; + if (time_diff <= 0) { + timer = "0:00"; + stop_timer(); + } else { + const seconds_total = Math.ceil(time_diff/ 1000); + const minutes = Math.floor(seconds_total / 60); + const seconds = seconds_total - (minutes * 60); + timer = `${minutes}:${seconds.toString().padStart(2, '0')}`; + } +} + client.on("message", (topic, message) => { let topic_str = topic.toString(); let message_str = message.toString(); @@ -63,39 +85,39 @@ client.on("message", (topic, message) => { // TODO: fill match name based off metadata break; case arena_state_topic: + stop_timer(); + const state_obj = JSON.parse(message_str); // Convert seconds to ms *1000 convert ns to ms /1000000 - const start_time = new Date((state_obj.start_s * 1000) + (state_obj.start_ns / 1000000)); + const start_ms = (state_obj.start_s * 1000) + (state_obj.start_ns / 1000000); + const start_time = new Date(start_ms); switch(state_obj.state) { case "SCHEDULED": timer = "Scheduled"; - timer_running = false; break; case "TIMEOUT": timer = "Timeout"; - timer_running = false; break; case "DRIVER": - timer_running = true; timer_start = start_time; - timer_duration = 105000; + timer_end = new Date(start_ms + 105000); + tick_timer(); + timer_next_tick = setInterval(tick_timer, 50); break; case "DRIVER_DONE": timer = "Driver Done"; - timer_running = false; break; case "AUTONOMOUS": - timer_running = true; timer_start = start_time; - timer_duration = 15000; + timer_end = new Date(start_ms + 15000); + tick_timer(); + timer_next_tick = setInterval(tick_timer, 50); break; case "AUTONOMOUS_DONE": timer = "Auton Done"; - timer_running = false; break; case "ABANDONED": timer = "Abandoned"; - timer_running = false; break; } break;