From 84d84b4313457cf24c001801c6d9fa1d304ea6bb Mon Sep 17 00:00:00 2001 From: Thomas Klaehn Date: Tue, 21 Feb 2023 08:06:05 +0100 Subject: [PATCH] Sauna: Add update timestamp to sauna api --- main.go | 15 +++++++++++---- webui/src/routes/sauna/+page.svelte | 11 +++++++++-- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/main.go b/main.go index ed76a51..4d92c14 100644 --- a/main.go +++ b/main.go @@ -6,13 +6,16 @@ import ( "log" "net/http" "sync" + "time" mqtt "github.com/eclipse/paho.mqtt.golang" ) type temperature struct { - Value float64 `json:"value"` - Unit string `json:"unit"` + Value float64 `json:"value"` + Unit string `json:"unit"` + Time time.Time `json:"time"` + Valid bool `json:"valid"` } var ( @@ -33,11 +36,15 @@ var saunaHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message log.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic()) sauna_mutex.Lock() err := json.Unmarshal(msg.Payload(), &sauna_temperature) - sauna_mutex.Unlock() + sauna_temperature.Time = time.Now() if err != nil { + sauna_temperature.Valid = false + sauna_mutex.Unlock() logger.Print(err) return } + sauna_temperature.Valid = true + sauna_mutex.Unlock() } var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) { @@ -99,7 +106,7 @@ func main() { // Serve files from static folder http.Handle("/", http.FileServer(http.Dir(webui_path))) - http.HandleFunc("/sauna/sample", http_endpoint_sauna) + http.HandleFunc("/api/sauna", http_endpoint_sauna) port := ":5000" logger.Println("Server is running on port" + port) diff --git a/webui/src/routes/sauna/+page.svelte b/webui/src/routes/sauna/+page.svelte index ccf9119..c69ad47 100644 --- a/webui/src/routes/sauna/+page.svelte +++ b/webui/src/routes/sauna/+page.svelte @@ -2,10 +2,12 @@ import { onMount } from "../../../node_modules/svelte/internal"; import icon from "$lib/images/sauna.svg" - let backend_url = "https://home.blackfinn.de/sauna/sample"; + let backend_url = "https://home.blackfinn.de/api/sauna"; let temperature_value = 0.0 let temperature_unit = "°C" + let time = "00:00:00"; + let updated = false; function get_temperature() { fetch(backend_url) @@ -13,6 +15,8 @@ .then(data => { temperature_unit = data.unit temperature_value = data.value + time = data.time.slice(11, 19) + updated = JSON.parse(data.valid); }).catch(error => { console.log(error); return []; @@ -38,5 +42,8 @@
Sauna
-

{temperature_value} {temperature_unit}

+ {#if updated} +
{time} Uhr:
+

{temperature_value} {temperature_unit}

+ {/if}