Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions config.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `CalculateMissingSpotValues`: derive missing Pdc/Pac values from voltage × current when the inverter reports zero. **Set this if a tracker shows 0 W beside a real DC voltage and current** — older inverters such as the SB 2500 never send `DcMsWatt`, and their string power (and with it the efficiency) stays empty without it. The service logs a hint when it sees that combination. |
| `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`. |
Expand Down
10 changes: 10 additions & 0 deletions src/crates/smalog/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ pub struct ArchiveConfig {
pub event_months: u32,
}

fn default_true() -> bool {
true
}

fn default_one() -> u32 {
1
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(),
Expand Down
80 changes: 70 additions & 10 deletions src/crates/smalog/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -619,6 +620,10 @@ struct ApiState {
diagnostics: Arc<WriteQueue>,
transmission_ring: RingBounds,
log_buffer: Arc<LogBuffer>,
/// 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 {
Expand All @@ -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,
}
}
}
Expand Down Expand Up @@ -1046,6 +1052,7 @@ async fn history_handler(
},
params.serial,
params.strings,
state.show_temperature,
)
.await
{
Expand Down Expand Up @@ -1265,13 +1272,15 @@ fn parse_history_year(raw: Option<&str>) -> std::result::Result<Option<i32>, 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, <key>: value, … }` ready for the chart.
#[allow(clippy::too_many_arguments)]
async fn build_history(
db: &Db,
tz: Tz,
range: &str,
period: HistoryPeriod,
serial: Option<u32>,
strings: bool,
show_temperature: bool,
) -> Result<Value> {
use chrono::{Datelike, Duration, TimeZone, Timelike};

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);

Expand All @@ -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,
});
Expand Down Expand Up @@ -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<Value> {
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<DayMetricSample>,
power_samples: Vec<DayPowerSample>,
tz: Tz,
show_temperature: bool,
) -> Vec<Value> {
use chrono::{TimeZone, Timelike};

Expand Down Expand Up @@ -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()
}
Expand Down Expand Up @@ -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);
Expand All @@ -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<String, Map<String, Value>> = BTreeMap::new();
Expand Down
6 changes: 1 addition & 5 deletions src/ui/src/components/DayHistorySummary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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;
}
12 changes: 5 additions & 7 deletions src/ui/src/components/DayHistoryTables.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 (
<div className="flex flex-col gap-4">
Expand Down Expand Up @@ -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,
Expand Down
4 changes: 3 additions & 1 deletion src/ui/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,9 @@ export interface History {
keys: string[];
series?: HistorySeries[];
summary?: DaySummary | WeekSummary | MonthSummary | YearSummary;
rows: Array<Record<string, string | number>>;
// A metric an inverter does not report comes back as null, which is not
// the same as zero.
rows: Array<Record<string, string | number | null>>;
}

export interface DiagnosticMppt {
Expand Down
14 changes: 14 additions & 0 deletions src/ui/src/lib/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
22 changes: 22 additions & 0 deletions src/ui/test/history.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});