fix: added energy-management

This commit is contained in:
Willem Serruys
2026-08-19 18:35:47 +02:00
parent fece1603e7
commit 53fa112aa8
38 changed files with 6060 additions and 0 deletions

View File

@@ -0,0 +1,51 @@
import type { QueryApi } from "@influxdata/influxdb-client";
import type { Env } from "../env.js";
import type { PowerSample } from "../types.js";
/**
* Fetches raw power samples between `sinceMs` and now.
* Converts the configured field to watts based on INFLUX_FIELD_UNIT.
*/
export async function fetchPowerSamplesSince(
queryApi: QueryApi,
env: Env,
sinceMs: number,
): Promise<PowerSample[]> {
const sinceIso = new Date(sinceMs).toISOString();
const flux = `
from(bucket: "${env.INFLUX_BUCKET}")
|> range(start: ${sinceIso})
|> filter(fn: (r) => r["_measurement"] == "${env.INFLUX_FIELD_UNIT}")
|> filter(fn: (r) => r["_field"] == "${env.INFLUX_FIELD}")
|> filter(fn: (r) => r["domain"] == "${env.INFLUX_DOMAIN}")
|> filter(fn: (r) => r["entity_id"] == "${env.INFLUX_ENTITY_ID}")
|> sort(columns: ["_time"])
`;
const unitMultiplier = env.INFLUX_FIELD_UNIT === "kW" ? 1000 : 1;
const samples: PowerSample[] = [];
for await (const { values, tableMeta } of queryApi.iterateRows(flux)) {
const row = tableMeta.toObject(values) as { _time: string; _value: number };
samples.push({
timestampMs: new Date(row._time).getTime(),
watts: row._value * unitMultiplier,
});
}
return samples;
}
/** Fetches the single most recent power sample, if any exists within the lookback window. */
export async function fetchLatestPowerSample(
queryApi: QueryApi,
env: Env,
lookbackMs = 60_000,
): Promise<PowerSample | null> {
const samples = await fetchPowerSamplesSince(
queryApi,
env,
Date.now() - lookbackMs,
);
return samples.length > 0 ? samples[samples.length - 1] : null;
}