diff --git a/README.cs.md b/README.cs.md index 1c723d5..d5e70b7 100644 --- a/README.cs.md +++ b/README.cs.md @@ -99,6 +99,7 @@ Senzory výkonu mohou být ve W nebo kW. | `show_w_not_kw` | `false` | Vždy zobrazovat watty. | | `show_statistics` | `true` | Zobrazit sekci s bilancí energie. | | `statistics` | panel Energie | Vlastní senzory energie: `pv`, `grid_import`, `grid_export`, `battery_charge`, `battery_discharge` (u každého jedno id nebo seznam). | +| `statistics.max_power_kw` | `100` | Nejvyšší výkon, kterého instalace reálně dosáhne, například podle hlavního jističe domu. Řádek statistik s větší energií, než by tento výkon za daný čas dodal, je chybný skok počítadla (měřič spadl na nulu a vrátil se) a vynechá se; karta napíše, kolik jich vynechala. | ### Bilance energie diff --git a/README.md b/README.md index d56721d..337871b 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,7 @@ Power sensors may be in W or kW. | `show_w_not_kw` | `false` | Always show watts. | | `show_statistics` | `true` | Show the energy balance section. | | `statistics` | Energy dashboard | Override the energy sensors: `pv`, `grid_import`, `grid_export`, `battery_charge`, `battery_discharge` (one id or a list each). | +| `statistics.max_power_kw` | `100` | Highest power your installation can really reach, for example the main breaker of the house. A statistics row with more energy than that power could deliver in the time it covers is a counter glitch (the meter dropped to zero and came back) and is left out; the card says how many it skipped. | ### Energy balance diff --git a/package-lock.json b/package-lock.json index 8919d81..4121132 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ultimate-power-card", - "version": "0.2.1", + "version": "0.2.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ultimate-power-card", - "version": "0.2.1", + "version": "0.2.2", "license": "Apache-2.0", "dependencies": { "custom-card-helpers": "^1.9.0", diff --git a/package.json b/package.json index ddafb03..07a4ee9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ultimate-power-card", - "version": "0.2.1", + "version": "0.2.2", "description": "Home Assistant custom Lovelace card — Tesla-style power flow with multi-battery and multi-appliance support", "main": "dist/ultimate-power-card.js", "type": "module", diff --git a/src/statistics.ts b/src/statistics.ts index 92d4693..16c4e56 100644 --- a/src/statistics.ts +++ b/src/statistics.ts @@ -18,6 +18,8 @@ export interface StatsResult { cons: number[]; imp: number[]; exp: number[]; + /** Number of implausible jumps (counter glitches) left out of the sums. */ + skipped: number; } interface StatRow { @@ -38,7 +40,10 @@ export const resolveStatIds = async ( ): Promise => { const ids: StatIds = { pv: [], gridIn: [], gridOut: [], batIn: [], batOut: [] }; const s = cfg.statistics; - if (s) { + // `statistics` may hold only max_power_kw; the sensors then still come from + // the Energy dashboard. + const own = !!s && [s.pv, s.grid_import, s.grid_export, s.battery_charge, s.battery_discharge].some((v) => list(v).length); + if (s && own) { ids.pv = list(s.pv); ids.gridIn = list(s.grid_import); ids.gridOut = list(s.grid_export); @@ -155,6 +160,14 @@ const periodRange = ( }; }; +/** + * Statistics are fetched one step finer than they are shown (hours for day, + * week and month, days for a year) so that a single bad row can be told apart + * from real energy. A meter that drops to zero and comes back makes Home + * Assistant book its whole lifetime reading as one hour of energy; any row + * above what `maxKw` (the highest real power, e.g. the main breaker of the + * house) could deliver in the time it covers is such a glitch and is skipped. + */ export const fetchStats = async ( hass: HomeAssistant, ids: StatIds, @@ -162,9 +175,14 @@ export const fetchStats = async ( offset: number, lang: string, words: { today: string; yesterday: string; thisWeek: string; lastWeek: string }, + maxKw = 100, ): Promise => { const range = periodRange(kind, offset, lang, words); const n = range.labels.length; + const fine = kind === 'year' ? 'day' : 'hour'; + const limit = maxKw * (fine === 'day' ? 24 : 1); + const stepMs = (fine === 'day' ? 24 : 1) * 3600000; + let skipped = 0; const all = [...new Set([...ids.pv, ...ids.gridIn, ...ids.gridOut, ...ids.batIn, ...ids.batOut])]; const rows = await hass.callWS>({ @@ -172,7 +190,7 @@ export const fetchStats = async ( start_time: range.start.toISOString(), end_time: range.end.toISOString(), statistic_ids: all, - period: range.bucket, + period: fine, types: ['change'], units: { energy: 'kWh' }, }); @@ -180,9 +198,17 @@ export const fetchStats = async ( const bucket = (statIds: string[]): number[] => { const out = new Array(n).fill(0); for (const id of statIds) { + let previous: number | null = null; for (const row of rows?.[id] ?? []) { + // After an outage there are no rows and the first one back holds all the + // energy measured meanwhile, so it may hold the limit for every step missed. + const at = new Date(row.start).getTime(); + const steps = previous === null ? 1 : Math.max(1, (at - previous) / stepMs); + previous = at; const i = range.index(new Date(row.start)); - if (i >= 0 && i < n && typeof row.change === 'number') out[i] += Math.max(0, row.change); + if (i < 0 || i >= n || typeof row.change !== 'number') continue; + if (row.change > limit * steps) skipped++; + else out[i] += Math.max(0, row.change); } } return out; @@ -196,5 +222,5 @@ export const fetchStats = async ( // Same energy balance as the live house load, per bucket. const cons = pv.map((p, i) => Math.max(0, p + imp[i] + batOut[i] - exp[i] - batIn[i])); - return { title: range.title, labels: range.labels, pv, cons, imp, exp }; + return { title: range.title, labels: range.labels, pv, cons, imp, exp, skipped }; }; diff --git a/src/styles.ts b/src/styles.ts index 2defacd..4d8c983 100644 --- a/src/styles.ts +++ b/src/styles.ts @@ -62,13 +62,13 @@ export const cardStyles = css` stroke-linecap: round; animation: up-flow linear infinite; } - /* Base speeds: the stream covers its 16 px period in 1 s, the lead dot runs + /* Base speeds: the stream covers its 24 px period in 1 s, the lead dot runs 100 px/s. The card scales both through the animation playback rate. */ .stream { - --p: 16; + --p: 24; animation-duration: 1s; stroke-width: 3; - stroke-dasharray: 0.1 15.9; + stroke-dasharray: 0.1 23.9; opacity: 0.8; } .stream.main { diff --git a/src/types.ts b/src/types.ts index cabc463..0580e5b 100644 --- a/src/types.ts +++ b/src/types.ts @@ -33,6 +33,12 @@ export interface StatisticsConfig { grid_export?: string | string[]; battery_charge?: string | string[]; battery_discharge?: string | string[]; + /** + * Highest power (kW) any of these meters can really reach. A statistics row + * showing more energy than this allows is treated as a counter glitch and + * left out. Default 100. + */ + max_power_kw?: number; } export interface UltimatePowerCardConfig extends LovelaceCardConfig { diff --git a/src/ultimate-power-card.ts b/src/ultimate-power-card.ts index 32ceb9d..1d70ed4 100644 --- a/src/ultimate-power-card.ts +++ b/src/ultimate-power-card.ts @@ -21,7 +21,7 @@ import { } from './statistics'; import type { UltimatePowerCardConfig } from './types'; -const VERSION = '0.2.1'; +const VERSION = '0.2.2'; type Pt = [number, number]; type Tone = 'pos' | 'neg'; @@ -30,6 +30,10 @@ type NodeState = Tone | 'idle'; /** Below this power (W) a node counts as idle and its flow is not animated. */ const IDLE_W = 5; const MAX_OFFSET = 120; +/** Distance between the small flow dots (px); must match --p of .stream in the styles. */ +const DOT_GAP = 24; +/** Fastest flow (px/s): about a seventh of DOT_GAP per frame on a 60 Hz screen. */ +const MAX_SPEED = 200; const PERIODS: PeriodKind[] = ['day', 'week', 'month', 'year']; const ICONS = { @@ -50,6 +54,7 @@ const WORDS = { prev: 'Předchozí období', next: 'Další období', loading: 'Načítám statistiky…', noStats: 'Statistiky nejsou k dispozici. Nastav panel Energie v Home Assistantu nebo volbu statistics v kartě.', statsError: 'Statistiky se nepodařilo načíst.', + skipped: 'Vynechané chybné skoky počítadla: {n}. Oprav je v Nástroje pro vývojáře → Statistiky.', }, en: { production: 'Production', consumption: 'Consumption', battery: 'Battery', grid: 'Grid', @@ -61,6 +66,7 @@ const WORDS = { prev: 'Previous period', next: 'Next period', loading: 'Loading statistics…', noStats: 'No statistics available. Set up the Energy dashboard in Home Assistant or the statistics option of the card.', statsError: 'Statistics could not be loaded.', + skipped: 'Meter glitches left out: {n}. Fix them in Developer tools → Statistics.', }, }; @@ -215,11 +221,17 @@ export class UltimatePowerCard extends LitElement { if (entity) fireEvent(this, 'hass-more-info', { entityId: entity }); } - /** Dot speed in px/s. Grows steeply with power so that the difference is obvious. */ + /** + * Dot speed in px/s. Grows steeply with power so that the difference is + * obvious, but stays capped: the dots repeat every DOT_GAP px, and once they + * travel a large part of that gap per screen frame the eye no longer sees + * movement, only a still, denser dotted line. + */ private _speed(w: number): number { const max = this._config?.max_power ?? 10000; - const k = Math.min(w, 1.2 * max) / max; - return (10 + 200 * Math.pow(k, 0.8)) * Math.max(0.1, this._config?.animation_speed ?? 1); + const k = Math.min(w, max) / max; + const speed = (8 + 132 * Math.pow(k, 0.8)) * Math.max(0.1, this._config?.animation_speed ?? 1); + return Math.min(speed, MAX_SPEED); } // ------------------------------------------------------------- flow diagram @@ -234,7 +246,7 @@ export class UltimatePowerCard extends LitElement { return svg` + data-rate=${(speed / DOT_GAP).toFixed(3)}> ${main ? svg`` @@ -425,7 +437,10 @@ export class UltimatePowerCard extends LitElement { this._statsState = 'none'; return; } - const stats = await fetchStats(hass, this._statIds, this._period, this._offset, hass.language ?? 'en', this._w); + const stats = await fetchStats( + hass, this._statIds, this._period, this._offset, hass.language ?? 'en', this._w, + Number(cfg.statistics?.max_power_kw) > 0 ? Number(cfg.statistics!.max_power_kw) : 100, + ); if (request !== this._request) return; this._stats = stats; this._statsState = 'ready'; @@ -497,6 +512,7 @@ export class UltimatePowerCard extends LitElement { kWh ${this._renderChart(st)} + ${st.skipped ? html`
${t.skipped.replace('{n}', String(st.skipped))}
` : nothing} `} `;