Cześć! 
Wracam do tematu naszej dyskusji o PSB History Engine – przygotowałem dla Was konkretny przykład, jak można w praktyce wykorzystać dane z tej integracji do stworzenia świetnej wizualizacji.
Poniższy kod karty Piotras Smart Button (PSB v3.0) pokazuje, jak w prosty i elegancki sposób wyciągnąć historię zbieraną przez PSB History Engine i zamienić ją w pełni interaktywny wykres bezpośrednio na dashboardzie Home Assistant!

Co zyskujemy dzięki temu połączeniu?
- Wizualizacja danych z PSB History Engine – karta bezpośrednio odpytuje i przetwarza tablicę historyczną dostarczaną przez naszą integrację.
- Interaktywny wykres SVG z płynnym gradientem i dynamiczną skalą osi Y (dopasowaną do temperatury, wilgotności itp.).
- Podgląd punktów w czasie – klikając w poszczególne słupki na wykresie, podejrzycie dokładną wartość i godzinę z historii (karta automatycznie wraca do trybu „Teraz” po kilku sekundach).
- Zmiana zakresu w locie – klikając w napis z liczbą punktów w lewym dolnym rogu (np. -24 pkt), możecie przełączać horyzont czasowy (np. 24, 48, 72 punkty).
- Progi alarmowe i statusy (Thresholds) – kolory ikon oraz stanów zmieniają się automatycznie w zależności od wartości (np. zimno, optymalnie, gorąco).
- Szybkie statystyki – gotowy podgląd wartości MIN, ŚRED. i MAX z wybranego zakresu.
Kod karty do skopiowania:
type: custom:piotras-smart-button
card_width: auto
card_height: 160
name_size: 15
border_width: 1
show_name: true
show_state: false
show_icon: false
show_shadow: false
show_filter: false
show_press_effect: false
background_color1: '#1c1c1e'
name: customData.Content
tap_action:
action: more-info
entity: sensor.sonoff_termometr_salon_temperature
custom_data:
Configuration: |-
p{{{
return {
title: "TEMPERATURE",
entity_id: "sensor.sonoff_termometr_salon_temperature",
history_entity_id: "sensor.sonoff_termometr_salon_temperature_history",
history_attribute: "history",
// Jednostka: puste = z atrybutu source_unit_of_measurement
unit: "",
chart_height: 80,
chart_width: 380,
stroke_width: 2,
fill_opacity: 0.45,
// Liczba punktów na starcie i kolejne kroki po kliknięciu w "-N pts"
max_points: 24,
points_steps: [24, 48, 72],
// Skala osi Y
y_axis_padding: 0.15,
min_y_range: 0.5, // temperatura: 2, wilgotność: 10, napięcie: 10
y_min: null, // null = automat
y_max: null, // null = automat
side_padding: 8,
show_last_dot: true,
show_time_labels: true,
idle_return_seconds: 10,
thresholds: [
{ max: 18, status: "Cold", color: "#2196F3", icon: "mdi:thermometer-low" },
{ max: 20, status: "Cool", color: "#03A9F4", icon: "mdi:thermometer" },
{ max: 24, status: "Ideal", color: "#4CAF50", icon: "mdi:thermometer-check" },
{ max: 26, status: "Warm", color: "#FF9800", icon: "mdi:thermometer-high" },
{ max: null, status: "Hot", color: "#F44336", icon: "mdi:thermometer-alert" }
],
fallback: {
status: "No Data",
color: "#888888",
icon: "mdi:thermometer-off"
}
};
}}}q
Stats: |-
p{{{
const cfg = customData.Configuration;
if (!cfg) return null;
const histEntity = states[cfg.history_entity_id];
if (!histEntity || !histEntity.attributes) return null;
const attrName = cfg.history_attribute || 'history';
const rawHistory = histEntity.attributes[attrName];
if (!Array.isArray(rawHistory) || rawHistory.length === 0) return null;
let historyPoints = [];
for (let i = 0; i < rawHistory.length; i++) {
const item = rawHistory[i];
if (Array.isArray(item) && item.length >= 2) {
const val = parseFloat(item[1]);
if (!isNaN(val)) {
historyPoints.push({
time: item[0],
val: val
});
}
}
}
if (historyPoints.length === 0) return null;
const currentMaxPts = card._maxPts || cfg.max_points || 24;
if (historyPoints.length > currentMaxPts) {
historyPoints = historyPoints.slice(-currentMaxPts);
}
const values = historyPoints.map(p => p.val);
const min = Math.min(...values);
const max = Math.max(...values);
const avg = values.reduce((a, b) => a + b, 0) / values.length;
return {
min: min.toFixed(1),
max: max.toFixed(1),
avg: avg.toFixed(1),
rawMin: min,
rawMax: max,
count: historyPoints.length,
values: values,
points: historyPoints
};
}}}q
Content: |-
p{{{
const cfg = customData.Configuration;
const stats = customData.Stats;
if (!cfg) return '';
const histEnt = states[cfg.history_entity_id];
const unit = cfg.unit
|| (histEnt && histEnt.attributes && histEnt.attributes.source_unit_of_measurement)
|| '';
const findThreshold = (v) =>
cfg.thresholds.find(t => t.max === null || t.max === undefined || v <= t.max) || cfg.fallback;
const mainEntity = states[cfg.entity_id];
const liveTemp = mainEntity ? parseFloat(mainEntity.state) : NaN;
const idleMs = (cfg.idle_return_seconds !== undefined ? cfg.idle_return_seconds : 15) * 1000;
const points = (stats && stats.points) ? stats.points : [];
const totalPts = points.length;
if (card._followLatest === undefined) card._followLatest = true;
if (card._followLatest || card._selectedIdx === undefined || card._selectedIdx >= totalPts) {
card._selectedIdx = totalPts > 0 ? totalPts - 1 : 0;
}
const isLiveSelected = card._followLatest || (card._selectedIdx === totalPts - 1);
const selectedPoint = totalPts > 0 ? points[card._selectedIdx] : null;
const activeTemp = isLiveSelected ? liveTemp : (selectedPoint ? selectedPoint.val : liveTemp);
let stateCfg = cfg.fallback;
if (!isNaN(activeTemp)) {
stateCfg = findThreshold(activeTemp);
}
let formattedTime = 'Now';
if (!isLiveSelected && selectedPoint && selectedPoint.time) {
const d = new Date(selectedPoint.time * 1000);
const hh = String(d.getHours()).padStart(2, '0');
const mm = String(d.getMinutes()).padStart(2, '0');
formattedTime = `${hh}:${mm}`;
}
let chartHtml = '';
if (!stats || !stats.values || stats.values.length < 2) {
chartHtml = '<div style="font-size: 0.8em; color: #888; text-align: center; padding: 10px;">No history points available...</div>';
} else {
const values = stats.values;
const width = cfg.chart_width || 280;
const height = cfg.chart_height || 50;
const showLabels = cfg.show_time_labels !== false;
const bottomPadding = showLabels ? 14 : 4;
const topPadding = 4;
const sidePad = cfg.side_padding !== undefined ? cfg.side_padding : 8;
const plotWidth = width - sidePad;
const padFactor = cfg.y_axis_padding !== undefined ? cfg.y_axis_padding : 0.15;
const pad = (stats.rawMax - stats.rawMin) * padFactor;
let minVal = stats.rawMin - pad;
let maxVal = stats.rawMax + pad;
const minRange = cfg.min_y_range !== undefined ? cfg.min_y_range : 2;
if ((maxVal - minVal) < minRange) {
const mid = (maxVal + minVal) / 2;
minVal = mid - minRange / 2;
maxVal = mid + minRange / 2;
}
if (cfg.y_min !== undefined && cfg.y_min !== null) minVal = cfg.y_min;
if (cfg.y_max !== undefined && cfg.y_max !== null) maxVal = cfg.y_max;
if (maxVal <= minVal) maxVal = minVal + 1;
const range = maxVal - minVal;
const drawHeight = height - topPadding - bottomPadding;
const pointsArray = values.map((val, idx) => {
const x = (idx / (values.length - 1)) * plotWidth;
const clamped = Math.min(maxVal, Math.max(minVal, val));
const y = height - bottomPadding - ((clamped - minVal) / range) * drawHeight;
return { x, y };
});
const pointsString = pointsArray.map(p => `${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(' ');
const activePointPos = pointsArray[card._selectedIdx] || pointsArray[pointsArray.length - 1];
const gradId = "psb_tempGrad_" + Math.random().toString(36).substr(2, 5);
const steps = (Array.isArray(cfg.points_steps) && cfg.points_steps.length) ? cfg.points_steps : [24, 48, 72];
const cyclePointsTap = customTap.id_js({
action: () => {
const current = card._maxPts || cfg.max_points || steps[0];
const idx = steps.indexOf(current);
card._maxPts = steps[(idx + 1) % steps.length];
card._followLatest = true;
card._updateState();
}
});
let clickOverlayHtml = '';
const colWidthPercent = 100 / totalPts;
for (let i = 0; i < totalPts; i++) {
const colTap = customTap.id_js({
action: () => {
card._selectedIdx = i;
card._followLatest = (i === totalPts - 1);
if (card._idleReturnTimer) clearTimeout(card._idleReturnTimer);
if (!card._followLatest) {
card._idleReturnTimer = setTimeout(() => {
card._followLatest = true;
card._idleReturnTimer = null;
card._updateState();
}, idleMs);
}
card._updateState();
}
});
clickOverlayHtml += `
<div ${colTap} style="
width: ${colWidthPercent}%;
height: 100%;
cursor: pointer;
touch-action: manipulation;
"></div>
`;
}
const overlayWidthPercent = (plotWidth / width) * 100;
chartHtml = `
<div style="position: relative; width: 100%; height: ${height}px;">
<svg width="100%" height="${height}" viewBox="0 0 ${width} ${height}" style="overflow: visible; display: block; pointer-events: none;">
<defs>
<linearGradient id="${gradId}" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="${stateCfg.color}" stop-opacity="${cfg.fill_opacity}"/>
<stop offset="100%" stop-color="${stateCfg.color}" stop-opacity="0.0"/>
</linearGradient>
</defs>
<polygon points="0,${height - bottomPadding} ${pointsString} ${plotWidth},${height - bottomPadding}" fill="url(#${gradId})" />
<polyline points="${pointsString}" fill="none" stroke="${stateCfg.color}" stroke-width="${cfg.stroke_width}" stroke-linecap="round" stroke-linejoin="round" />
${cfg.show_last_dot ? `
<circle cx="${activePointPos.x.toFixed(1)}" cy="${activePointPos.y.toFixed(1)}" r="5" fill="${stateCfg.color}" stroke="#1c1c1e" stroke-width="1.5" />
` : ''}
${showLabels ? `
<text ${cyclePointsTap} x="0" y="${height}" font-size="12" fill="${stateCfg.color}" font-weight="700" text-anchor="start" style="cursor: pointer; text-decoration: underline; pointer-events: auto;">-${stats.count} pts</text>
<text x="${width}" y="${height}" font-size="11" fill="${isLiveSelected ? '#666666' : stateCfg.color}" font-weight="600" text-anchor="end">${isLiveSelected ? 'Now' : formattedTime}</text>
` : ''}
</svg>
<div style="position: absolute; top: 0; left: 0; width: ${overlayWidthPercent}%; height: ${height - bottomPadding}px; display: flex; z-index: 10;">
${clickOverlayHtml}
</div>
</div>
`;
}
return `
<div style="display: flex; flex-direction: column; justify-content: space-between; height: 100%; padding: 5px; box-sizing: border-box; user-select: none;">
<div style="display: flex; align-items: center; justify-content: space-between; width: 100%;">
<div style="display: flex; align-items: center; gap: 8px;">
<ha-icon icon="${stateCfg.icon}" style="--mdc-icon-size: 24px; color: ${stateCfg.color};"></ha-icon>
<div style="display: flex; flex-direction: column; text-align: left;">
<span style="font-weight: 700; font-size: 0.9em; color: #ffffff; line-height: 1.1;">${cfg.title}</span>
<span style="font-size: 0.75em; color: ${stateCfg.color}; font-weight: 600;">${isLiveSelected ? stateCfg.status : formattedTime}</span>
</div>
</div>
<span style="font-weight: 800; font-size: 1.25em; color: ${stateCfg.color};">${isNaN(activeTemp) ? '--' : activeTemp.toFixed(1)} ${unit}</span>
</div>
<div style="width: 100%; margin-top: 4px;">
${chartHtml}
</div>
${stats ? `
<div style="display: flex; justify-content: space-between; align-items: center; width: 100%; font-size: 0.7em; color: #888888; border-top: 2px solid rgba(255,255,255,0.05); padding-top: 4px; margin-top: 2px;">
<span>MIN: <strong style="color: #ffffff;">${stats.min}${unit}</strong></span>
<span>AVG: <strong style="color: #ffffff;">${stats.avg}${unit}</strong></span>
<span>MAX: <strong style="color: #ffffff;">${stats.max}${unit}</strong></span>
</div>
` : ''}
</div>
`;
}}}q
grid_options:
columns: 9
rows: auto
Kod gotowy – zapraszam do testowania u siebie!
Będę wdzięczny za feedback, jak integracja z PSB History Engine działa w praktyce i jak podoba Wam się interaktywny wykres. Udanych testów!