From be5772e4885d313fa5582786f754031ddab3d0c1 Mon Sep 17 00:00:00 2001 From: Klagarge Date: Sat, 30 May 2026 21:40:35 +0200 Subject: [PATCH] refactor(db): using moving average for room history History is now a moving average over 5min by slice of 1min Assisted-by: Junie:gemini-3-flash Signed-off-by: Klagarge --- db/src/rest/rest.go | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/db/src/rest/rest.go b/db/src/rest/rest.go index d31a734..7441383 100644 --- a/db/src/rest/rest.go +++ b/db/src/rest/rest.go @@ -450,18 +450,28 @@ func (g *RestGateway) getRoomHistory(c *gin.Context) { nodeFilter := buildNodeFilter(nodes) query := fmt.Sprintf(` + WITH binned AS ( + SELECT + date_bin(INTERVAL '1 minute', time)::TIMESTAMP AS time, + AVG(co2_ppm) AS co2_ppm, + AVG(temp) AS temp, + AVG(humidity) AS humidity, + MAX(window_open) AS window_open + FROM "%s" + WHERE time > now() - INTERVAL '%s' - INTERVAL '5 minutes' + AND %s + GROUP BY date_bin(INTERVAL '1 minute', time) + ) SELECT - date_bin(INTERVAL '5 minutes', time)::TIMESTAMP AS time, - ROUND(AVG(co2_ppm)) AS co2_ppm, - ROUND(AVG(temp), 2) AS temp, - ROUND(AVG(humidity), 2) AS humidity, - MAX(window_open) AS window_open - FROM "%s" - WHERE time > now() - INTERVAL '%s' - AND %s - GROUP BY date_bin(INTERVAL '5 minutes', time) + time, + ROUND(AVG(co2_ppm) OVER (ORDER BY time RANGE BETWEEN INTERVAL '4 minutes' PRECEDING AND CURRENT ROW)) AS co2_ppm, + ROUND(AVG(temp) OVER (ORDER BY time RANGE BETWEEN INTERVAL '4 minutes' PRECEDING AND CURRENT ROW), 2) AS temp, + ROUND(AVG(humidity) OVER (ORDER BY time RANGE BETWEEN INTERVAL '4 minutes' PRECEDING AND CURRENT ROW), 2) AS humidity, + window_open + FROM binned + WHERE time > now() - INTERVAL '%s' ORDER BY time ASC - `, g.measurementName, window, nodeFilter, + `, g.measurementName, window, nodeFilter, window, ) // Using context.Background() as seen in working snippet