1
0

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 <remi@heredero.ch>
This commit is contained in:
2026-05-30 21:40:35 +02:00
parent 53fbc87af6
commit be5772e488

View File

@@ -450,18 +450,28 @@ func (g *RestGateway) getRoomHistory(c *gin.Context) {
nodeFilter := buildNodeFilter(nodes) nodeFilter := buildNodeFilter(nodes)
query := fmt.Sprintf(` query := fmt.Sprintf(`
WITH binned AS (
SELECT SELECT
date_bin(INTERVAL '5 minutes', time)::TIMESTAMP AS time, date_bin(INTERVAL '1 minute', time)::TIMESTAMP AS time,
ROUND(AVG(co2_ppm)) AS co2_ppm, AVG(co2_ppm) AS co2_ppm,
ROUND(AVG(temp), 2) AS temp, AVG(temp) AS temp,
ROUND(AVG(humidity), 2) AS humidity, AVG(humidity) AS humidity,
MAX(window_open) AS window_open MAX(window_open) AS window_open
FROM "%s" FROM "%s"
WHERE time > now() - INTERVAL '%s' WHERE time > now() - INTERVAL '%s' - INTERVAL '5 minutes'
AND %s AND %s
GROUP BY date_bin(INTERVAL '5 minutes', time) GROUP BY date_bin(INTERVAL '1 minute', time)
)
SELECT
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 ORDER BY time ASC
`, g.measurementName, window, nodeFilter, `, g.measurementName, window, nodeFilter, window,
) )
// Using context.Background() as seen in working snippet // Using context.Background() as seen in working snippet