From 56aea445836562aa3cf27bdd25b5ea7f8fbdc39c Mon Sep 17 00:00:00 2001 From: Frank Gehann Date: Thu, 20 Aug 2026 13:04:06 +0200 Subject: [PATCH] feat(ui): make the temperature column optional, and stop faking it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two problems behind one symptom. A missing temperature arrived as JSON null, and `Number(null)` is 0, so every five-minute row and the day summary showed 0.00 °C for an inverter that has no sensor at all — a reading it never sent. The helper doing that was duplicated in two components; it now lives in lib/history.ts, treats null, undefined and blank as absent, and keeps a genuine zero. With that fixed the column would show dashes instead, which says no more than the zeros did, so it appears only where a reading exists — and the new service.show_temperature (default true) drops the series from the payload altogether for operators who never want it. The aggregate view never had a temperature series: averaging sensors across inverters would invent a reading. --- config.example.toml | 5 ++ docs/configuration.md | 1 + src/crates/smalog/src/config.rs | 10 +++ src/crates/smalog/src/service.rs | 80 ++++++++++++++++++--- src/ui/src/components/DayHistorySummary.tsx | 6 +- src/ui/src/components/DayHistoryTables.tsx | 12 ++-- src/ui/src/lib/api.ts | 4 +- src/ui/src/lib/history.ts | 14 ++++ src/ui/test/history.test.ts | 22 ++++++ 9 files changed, 131 insertions(+), 23 deletions(-) create mode 100644 src/ui/test/history.test.ts diff --git a/config.example.toml b/config.example.toml index 01e91e1..31c7833 100644 --- a/config.example.toml +++ b/config.example.toml @@ -23,7 +23,12 @@ listen = "0.0.0.0:8080" # Poll around the clock instead of only between sunrise and sunset. poll_at_night = false # Derive missing Pdc/Pac from voltage x current (SBFspot CalcMissingSpot). +# Set this if a tracker shows 0 W beside a real DC voltage and current: +# older inverters such as the SB 2500 never report DC power. calc_missing_spot = false +# Show inverter temperature in the day view. Inverters without a sensor +# leave the column empty; false drops it entirely. +show_temperature = true # Poll household consumption from the inverter's consumer-power LRIs and # fill the Consumption table. Off by default and only useful with an SMA # consumption meter attached; inverters without one report "LRI not diff --git a/docs/configuration.md b/docs/configuration.md index bd16ca8..3dff25f 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -47,6 +47,7 @@ Optional. Controls the poll loop and the HTTP status endpoint. | `listen` | string (socket addr) | *(unset → disabled)* | Address for the `/healthz` and `/status` HTTP endpoints, e.g. `0.0.0.0:8080`. Omit to disable the HTTP server. Required if you use the [`healthcheck`](operations.md#healthcheck) subcommand. | | `poll_at_night` | bool | `false` | When `false`, polling only happens between sunrise and sunset (plus [`sun_rs_offset`](#plant) slack). Set `true` to poll around the clock. | | `calc_missing_spot` | bool | `false` | SBFspot `CalcMissingSpot`: derive missing Pdc/Pac values from voltage × current when the inverter reports zero. | +| `show_temperature` | bool | `true` | Carry inverter temperature in the day view. Inverters without a sensor answer "LRI not available", so their column stays empty; set `false` to drop it from the payload and the dashboard entirely. | | `poll_consumption` | bool | `false` | Poll the inverter's consumer-power LRIs (`MeteringCsmpTotWIn` / `TotWhIn`) and fill canonical `site_consumption_measurements`. Not in SBFspot, which never queries these; only useful with an SMA consumption meter attached (inverters without one report "LRI not available"). | | `transmission_log_retention_hours` | integer (hours) | `48` | How long recorded inverter exchanges are kept for the dashboard's System area. `0` switches recording off; rows already stored are **not** deleted. Must be `0`–`8760`. | | `application_log_retention_hours` | integer (hours) | `48` | How long captured application log records are kept **in the service's memory**. They are never written to the database and are lost on restart. `0` switches capture off entirely. Must be `0`–`8760`. | diff --git a/src/crates/smalog/src/config.rs b/src/crates/smalog/src/config.rs index b8483c0..bf44178 100644 --- a/src/crates/smalog/src/config.rs +++ b/src/crates/smalog/src/config.rs @@ -58,6 +58,10 @@ pub struct ArchiveConfig { pub event_months: u32, } +fn default_true() -> bool { + true +} + fn default_one() -> u32 { 1 } @@ -91,6 +95,11 @@ pub struct ServiceConfig { /// from voltage × current. #[serde(default)] pub calc_missing_spot: bool, + /// Show inverter temperature in the dashboard's day view. Inverters + /// without a temperature sensor answer "LRI not available", leaving the + /// column empty; set this to false to drop it entirely. + #[serde(default = "default_true")] + pub show_temperature: bool, /// Poll household consumption from the inverter's consumer-power LRIs /// and fill the `Consumption` table. Off by default: SBFspot never /// queries these (its `Consumption` table is written by external @@ -127,6 +136,7 @@ impl Default for ServiceConfig { listen: None, poll_at_night: false, calc_missing_spot: false, + show_temperature: true, poll_consumption: false, transmission_log_retention_hours: default_diagnostics_retention_hours(), application_log_retention_hours: default_diagnostics_retention_hours(), diff --git a/src/crates/smalog/src/service.rs b/src/crates/smalog/src/service.rs index 3ff1750..a8c427c 100644 --- a/src/crates/smalog/src/service.rs +++ b/src/crates/smalog/src/service.rs @@ -262,6 +262,7 @@ impl Service { diagnostics: self.diagnostics.clone(), transmission_ring: self.transmission_ring, log_buffer: self.log_buffer.clone(), + show_temperature: self.config.service.show_temperature, }; tokio::spawn(async move { if let Err(e) = serve_http(addr, state).await { @@ -619,6 +620,10 @@ struct ApiState { diagnostics: Arc, transmission_ring: RingBounds, log_buffer: Arc, + /// Whether the day view carries inverter temperature at all. Inverters + /// without a temperature sensor answer "LRI not available", and a column + /// of dashes for every reading is noise the operator can switch off. + show_temperature: bool, } impl ApiState { @@ -632,6 +637,7 @@ impl ApiState { diagnostics: WriteQueue::new(crate::diagnostics::QUEUE_CAPACITY), transmission_ring: RingBounds::new(48, 50_000), log_buffer: LogBuffer::new(48, 50_000), + show_temperature: true, } } } @@ -1046,6 +1052,7 @@ async fn history_handler( }, params.serial, params.strings, + state.show_temperature, ) .await { @@ -1265,6 +1272,7 @@ fn parse_history_year(raw: Option<&str>) -> std::result::Result, Str /// `month`, and `year` select a local calendar period. `strings` (day + serial) /// splits DC power per string. The result is `{ range, unit, keys, rows }` /// where each row is `{ label, : value, … }` ready for the chart. +#[allow(clippy::too_many_arguments)] async fn build_history( db: &Db, tz: Tz, @@ -1272,6 +1280,7 @@ async fn build_history( period: HistoryPeriod, serial: Option, strings: bool, + show_temperature: bool, ) -> Result { use chrono::{Datelike, Duration, TimeZone, Timelike}; @@ -1353,10 +1362,13 @@ async fn build_history( let mut series = Vec::new(); let total_power_key = "total_power".to_string(); let total_energy_key = "total_energy".to_string(); + // The aggregate view has no temperature series of its own; + // averaging sensors across inverters would invent a reading. let total_rows = build_day_metric_rows( db.day_metrics(start, start + 86_400, None).await?, db.day_power(start, start + 86_400, None).await?, tz, + false, ); merge_inverter_day_rows( @@ -1395,6 +1407,7 @@ async fn build_history( db.day_power(start, start + 86_400, Some(inverter_serial)) .await?, tz, + show_temperature, ); merge_inverter_day_rows(&mut merged_rows, rows, &power_key, &energy_key); @@ -1439,7 +1452,7 @@ async fn build_history( let samples = db.day_metrics(start, start + 86_400, serial).await?; let power = db.day_power(start, start + 86_400, serial).await?; - let rows = build_day_metric_rows(samples, power, tz); + let rows = build_day_metric_rows(samples, power, tz, show_temperature); let previous_energy = previous_day_energy(db, tz, selected_day, serial).await?; let summary = build_day_summary(&rows, "power", "energy", previous_energy); @@ -1449,12 +1462,8 @@ async fn build_history( "today": today.to_string(), "live": selected_day == today, "unit": "mixed", - "keys": ["power", "energy", "temperature"], - "series": [ - { "key": "power", "label": "Power", "metric": "power" }, - { "key": "energy", "label": "Energy Generated", "metric": "energy" }, - { "key": "temperature", "label": "Temperature", "metric": "temperature" }, - ], + "keys": day_keys(show_temperature), + "series": day_series(show_temperature), "summary": summary, "rows": rows, }); @@ -1896,10 +1905,36 @@ fn merge_inverter_day_rows( } } +/// The keys of a single-inverter day payload. +fn day_keys(show_temperature: bool) -> Vec<&'static str> { + if show_temperature { + vec!["power", "energy", "temperature"] + } else { + vec!["power", "energy"] + } +} + +/// The series of a single-inverter day payload. +fn day_series(show_temperature: bool) -> Vec { + let mut series = vec![ + json!({ "key": "power", "label": "Power", "metric": "power" }), + json!({ "key": "energy", "label": "Energy Generated", "metric": "energy" }), + ]; + if show_temperature { + series.push(json!({ + "key": "temperature", + "label": "Temperature", + "metric": "temperature", + })); + } + series +} + fn build_day_metric_rows( samples: Vec, power_samples: Vec, tz: Tz, + show_temperature: bool, ) -> Vec { use chrono::{TimeZone, Timelike}; @@ -1981,12 +2016,15 @@ fn build_day_metric_rows( let temperature = (point.temperature_count > 0) .then(|| point.temperature_sum / point.temperature_count as f64); let power_w = archive_power.get(&ts).copied().unwrap_or(point.power_w); - Some(json!({ + let mut row = json!({ "label": format!("{:02}:{:02}", t.hour(), t.minute()), "power": power_w as f64 / 1000.0, "energy": point.energy_wh as f64 / 1000.0, - "temperature": temperature, - })) + }); + if show_temperature { + row["temperature"] = json!(temperature); + } + Some(row) }) .collect() } @@ -3119,6 +3157,7 @@ mod tests { ], vec![(0, 1, 900), (0, 2, 1_800), (300, 1, 1_400)], Tz::UTC, + true, ); assert_eq!(rows[0]["power"], 2.7); @@ -3129,6 +3168,27 @@ mod tests { assert_eq!(rows[1]["temperature"], 21.5); } + #[test] + fn day_rows_carry_no_temperature_when_it_is_switched_off() { + let samples = vec![(0, 1, 1_000, 10_000, Some(20.0))]; + let power = vec![(0, 1, 900)]; + + let shown = build_day_metric_rows(samples.clone(), power.clone(), Tz::UTC, true); + assert_eq!(shown[0]["temperature"], 20.0); + assert_eq!( + crate::service::day_keys(true), + vec!["power", "energy", "temperature"] + ); + assert_eq!(crate::service::day_series(true).len(), 3); + + // Off: the field is absent rather than null, so the dashboard has no + // column to draw and no dashes to fill it with. + let hidden = build_day_metric_rows(samples, power, Tz::UTC, false); + assert!(hidden[0].get("temperature").is_none()); + assert_eq!(crate::service::day_keys(false), vec!["power", "energy"]); + assert_eq!(crate::service::day_series(false).len(), 2); + } + #[test] fn inverter_day_rows_keep_each_inverters_series_separate() { let mut merged: BTreeMap> = BTreeMap::new(); diff --git a/src/ui/src/components/DayHistorySummary.tsx b/src/ui/src/components/DayHistorySummary.tsx index d199c79..04dbff7 100644 --- a/src/ui/src/components/DayHistorySummary.tsx +++ b/src/ui/src/components/DayHistorySummary.tsx @@ -4,7 +4,7 @@ import { formatNumber, formatPowerKilowatts, } from "@/lib/format"; -import { aggregateHistorySeries } from "@/lib/history"; +import { aggregateHistorySeries, numericValue } from "@/lib/history"; import { HistoryMetricCard } from "@/components/MonthHistoryView"; import { useI18n } from "@/lib/i18n"; @@ -96,7 +96,3 @@ function inferSeries(history: History): HistorySeries[] { })); } -function numericValue(value: string | number | undefined): number | null { - const numeric = Number(value); - return value === undefined || !Number.isFinite(numeric) ? null : numeric; -} diff --git a/src/ui/src/components/DayHistoryTables.tsx b/src/ui/src/components/DayHistoryTables.tsx index bf4b796..1e566f2 100644 --- a/src/ui/src/components/DayHistoryTables.tsx +++ b/src/ui/src/components/DayHistoryTables.tsx @@ -9,7 +9,7 @@ import { formatNumber, formatPowerKilowatts, } from "@/lib/format"; -import { aggregateHistorySeries } from "@/lib/history"; +import { aggregateHistorySeries, numericValue } from "@/lib/history"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area"; import { @@ -55,7 +55,10 @@ export function DayHistoryTables({ [series, selectedLabel], ); const rows = useMemo(() => [...history.rows].reverse(), [history.rows]); - const showTemperature = summaries.some((item) => item.temperatureKey); + // A column of dashes says nothing: show it only where a reading exists. + const showTemperature = summaries.some( + (item) => latestValue(history, item.temperatureKey) !== null, + ); return (
@@ -243,11 +246,6 @@ function latestValue(history: History, key?: string): number | null { return null; } -function numericValue(value: string | number | undefined): number | null { - const numeric = Number(value); - return value === undefined || !Number.isFinite(numeric) ? null : numeric; -} - function formatMetric( metric: HistoryMetric, value: number, diff --git a/src/ui/src/lib/api.ts b/src/ui/src/lib/api.ts index 78ff09f..20fde06 100644 --- a/src/ui/src/lib/api.ts +++ b/src/ui/src/lib/api.ts @@ -89,7 +89,9 @@ export interface History { keys: string[]; series?: HistorySeries[]; summary?: DaySummary | WeekSummary | MonthSummary | YearSummary; - rows: Array>; + // A metric an inverter does not report comes back as null, which is not + // the same as zero. + rows: Array>; } export interface DiagnosticMppt { diff --git a/src/ui/src/lib/history.ts b/src/ui/src/lib/history.ts index ce56b72..0b68b9c 100644 --- a/src/ui/src/lib/history.ts +++ b/src/ui/src/lib/history.ts @@ -19,3 +19,17 @@ export function aggregateHistorySeries( (item.key === "power" || item.key === "energy"), ); } + +/** One row value as a number, or null when the metric is absent. + * + * A metric the inverter does not report arrives as `null`, and `Number(null)` + * is `0` — which is how a missing temperature came to be shown as 0.00 °C. */ +export function numericValue( + value: string | number | null | undefined, +): number | null { + if (value === null || value === undefined) return null; + // `Number("")` is 0 as well; an empty cell is not a reading either. + if (typeof value === "string" && value.trim() === "") return null; + const numeric = Number(value); + return Number.isFinite(numeric) ? numeric : null; +} diff --git a/src/ui/test/history.test.ts b/src/ui/test/history.test.ts new file mode 100644 index 0000000..75c821e --- /dev/null +++ b/src/ui/test/history.test.ts @@ -0,0 +1,22 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { numericValue } from "../src/lib/history.ts"; + +test("a metric the inverter does not report reads as absent, not as zero", () => { + // The SB 2500 has no temperature sensor: the API sends null, and + // Number(null) would be 0. + assert.equal(numericValue(null), null); + assert.equal(numericValue(undefined), null); +}); + +test("real values survive, including a genuine zero", () => { + assert.equal(numericValue(0), 0); + assert.equal(numericValue("21.5"), 21.5); + assert.equal(numericValue(1_234), 1_234); +}); + +test("anything unparseable counts as absent", () => { + assert.equal(numericValue("nope"), null); + assert.equal(numericValue(""), null); +});