🚀 [Integracja] PSB History Engine – szybki bufor historii w RAM dla Twojego dashboardu

Cześć wszystkim!

Chciałbym podzielić się z Wami moim nowym projektem dla Home Assistant: PSB History Engine.

Każdy z nas wie, jak działa wbudowany Recorder – zapisuje wszystko do bazy SQLite / MariaDB / InfluxDB. O ile do długoterminowych statystyk jest niezbędny, o tyle odczytywanie bazy tylko po to, żeby wyrenderować prosty wykres z ostatnich 24h na karcie dashboardu, bywa utrapieniem:

  • :warning: Zajeżdża karty SD / dyski SSD niepotrzebnymi operacjami I/O,
  • :turtle: Zwalnia ładowanie dashboardów (zwłaszcza na Raspberry Pi czy słabszych terminalach),
  • :cross_mark: Alternatywy typu zapisywanie historii do input_text przez automatyzacje rozbijają się o limit 255 znaków i rozjeżdżają w czasie.

:light_bulb: Czym jest PSB History Engine?

To lekka integracja, która pozwala wybrać dowolne encje numeryczne (sensor, number, counter itp.) i tworzy dla nich encje pomocnicze sensor.<nazwa>_history.

W atrybutach tej encji przechowywana jest tablica [timestamp, wartość] z wybranego okresu.

  • :brain: Brak obciążenia dysku: Cały bufor żyje w pamięci RAM. Odczyt na dashboardzie jest natychmiastowy.
  • :counterclockwise_arrows_button: Trwałość po restarcie: Wykorzystuje natywny mechanizm Restore State z HA, więc po restarcie encje nie tracą pobranych punktów.
  • :desktop_computer: Pełne UI w Sidebarze: Brak konieczności dłubania w YAML! Dedykowana zakładka w menu bocznym pozwala łatwo dodawać encje, podglądać wykresy na żywo, dostosowywać parametry i robić backup konfiguracji.
  • :globe_with_meridians: Język polski: Panel jest w pełni przetłumaczony na język polski.

:gear: Kluczowe funkcje i możliwości konfiguracyjne:

  • :stopwatch: Idealne wyrównanie czasowe (Grid alignment): Próbkowanie następuje równo z zegarem (np. idealnie o HH:00:00), a nie w losowych odstępach od startu integracji.
  • :bullseye: Obsługa offsetu: Możesz ustawić np. offset -60s, żeby pobrać odczyt dokładnie na minutę przed zmianą taryfy prądu lub resetem dobowego licznika (np. o 23:59:00).
  • :chart_increasing: Tryby śledzenia (Value vs Counter):
    • Wartość bieżąca: Dla temperatur, wilgotności, mocy instant, poziomu baterii.
    • Licznik narastający: Dla energii, wody, gazu. Integracja wyłapuje resety liczników i oznacza je flagą "reset" zamiast generować błędne ujemne delty.
  • :shield: Bezpieczeństwo bufora: Twardy limit 500 punktów na encję chroni Home Assistanta przed przekroczeniem limitu 16 KiB na atrybut stanu.

:artist_palette: Jak z tego korzystać na Dashboardzie?

Integracja została stworzona jako zaplecze dla karty Piotras Smart Button (PSB), ale struktura w atrybutach jest w pełni uniwersalna. Bez problemu wyciągniecie z niej dane w custom:button-card, apexcharts-card czy dowolnej innej karcie wspierającej szablony JavaScript.

Struktura atrybutu sensor.power_meter_history:

state: 24                    # Liczba punktów aktualnie buforowanych
attributes:
  source_entity: sensor.power_meter
  tracking_mode: counter     # "value" lub  "counter"
  interval_seconds: 3600
  offset_seconds: -60
  depth: 48
  last_raw_value: 12.34
  unit_of_measurement: points
  source_unit_of_measurement: kWh
  history:
    - [1735689600, 0.42]
    - [1735693200, 0.51]
    - [1735696800, 0.07, "reset"]   # Licznik zresetowany automatycznie
    - [1735700400, 0.19]

:package: Instalacja

Najprościej zainstalować bezpośrednio przez przycisk My Home Assistant:

Open your Home Assistant instance and open a repository inside the Home Assistant Community Store.

Lub tradycyjnie w HACS:

  • Wybierz HACS :right_arrow: Integracje :right_arrow: 3 kropki w prawym górnym rogu :right_arrow: Niestandardowe repozytoria.
  • Wklej URL https://github.com/Piotras1/psb-history-engine Kategoria: Integracja .
  • Kliknij Zainstaluj, wykonaj restart HA i dodaj PSB History Engine w Ustawienia :right_arrow: Urządzenia oraz usługi.

Zapraszam do testowania! Chętnie wysłucham Waszych opinii i uwag co do dalszego rozwoju.

3 polubienia

Cześć! :waving_hand:

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!

piotras-smart-button-demo-wykres

:bar_chart: 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.

:laptop: 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!

1 polubienie