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
1 change: 1 addition & 0 deletions README.cs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
34 changes: 30 additions & 4 deletions src/statistics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -38,7 +40,10 @@ export const resolveStatIds = async (
): Promise<StatIds | null> => {
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);
Expand Down Expand Up @@ -155,34 +160,55 @@ 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,
kind: PeriodKind,
offset: number,
lang: string,
words: { today: string; yesterday: string; thisWeek: string; lastWeek: string },
maxKw = 100,
): Promise<StatsResult> => {
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<Record<string, StatRow[]>>({
type: 'recorder/statistics_during_period',
start_time: range.start.toISOString(),
end_time: range.end.toISOString(),
statistic_ids: all,
period: range.bucket,
period: fine,
types: ['change'],
units: { energy: 'kWh' },
});

const bucket = (statIds: string[]): number[] => {
const out = new Array<number>(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;
Expand All @@ -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 };
};
6 changes: 3 additions & 3 deletions src/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
6 changes: 6 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
28 changes: 22 additions & 6 deletions src/ultimate-power-card.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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 = {
Expand All @@ -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',
Expand All @@ -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.',
},
};

Expand Down Expand Up @@ -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
Expand All @@ -234,7 +246,7 @@ export class UltimatePowerCard extends LitElement {
return svg`
<path class="wire on" d=${d}></path>
<path class="stream ${tone} ${main ? 'main' : ''} ${rev}" d=${d}
data-rate=${(speed / 16).toFixed(3)}></path>
data-rate=${(speed / DOT_GAP).toFixed(3)}></path>
${main
? svg`<path class="lead ${tone} ${rev}" d=${d} data-rate=${(speed / 100).toFixed(3)}
style=${`--p:${len};stroke-dasharray:0.1 ${len};animation-duration:${(len / 100).toFixed(2)}s`}></path>`
Expand Down Expand Up @@ -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';
Expand Down Expand Up @@ -497,6 +512,7 @@ export class UltimatePowerCard extends LitElement {
<span>kWh</span>
</div>
${this._renderChart(st)}
${st.skipped ? html`<div class="note">${t.skipped.replace('{n}', String(st.skipped))}</div>` : nothing}
`}
</div>
`;
Expand Down
Loading