Kreisdiagramm Visualisierung hinzugefügt.

Zeigt Eigenvrebrauchsquote und Autarkiergrad an.
This commit is contained in:
belevo\mh
2025-12-22 08:31:28 +01:00
parent 57d247bd83
commit 81b0b6ee50
5 changed files with 557 additions and 0 deletions

67
Energy_Pie/README.md Normal file
View File

@@ -0,0 +1,67 @@
# Manager_1
Beschreibung des Moduls.
### Inhaltsverzeichnis
1. [Funktionsumfang](#1-funktionsumfang)
2. [Voraussetzungen](#2-voraussetzungen)
3. [Software-Installation](#3-software-installation)
4. [Einrichten der Instanzen in IP-Symcon](#4-einrichten-der-instanzen-in-ip-symcon)
5. [Statusvariablen und Profile](#5-statusvariablen-und-profile)
6. [WebFront](#6-webfront)
7. [PHP-Befehlsreferenz](#7-php-befehlsreferenz)
### 1. Funktionsumfang
*
### 2. Voraussetzungen
- IP-Symcon ab Version 7.1
### 3. Software-Installation
* Über den Module Store das 'Manager_1'-Modul installieren.
* Alternativ über das Module Control folgende URL hinzufügen
### 4. Einrichten der Instanzen in IP-Symcon
Unter 'Instanz hinzufügen' kann das 'Manager_1'-Modul mithilfe des Schnellfilters gefunden werden.
- Weitere Informationen zum Hinzufügen von Instanzen in der [Dokumentation der Instanzen](https://www.symcon.de/service/dokumentation/konzepte/instanzen/#Instanz_hinzufügen)
__Konfigurationsseite__:
Name | Beschreibung
-------- | ------------------
|
|
### 5. Statusvariablen und Profile
Die Statusvariablen/Kategorien werden automatisch angelegt. Das Löschen einzelner kann zu Fehlfunktionen führen.
#### Statusvariablen
Name | Typ | Beschreibung
------ | ------- | ------------
| |
| |
#### Profile
Name | Typ
------ | -------
|
|
### 6. WebFront
Die Funktionalität, die das Modul im WebFront bietet.
### 7. PHP-Befehlsreferenz
`boolean GEF_BeispielFunktion(integer $InstanzID);`
Erklärung der Funktion.
Beispiel:
`GEF_BeispielFunktion(12345);`

8
Energy_Pie/form.json Normal file
View File

@@ -0,0 +1,8 @@
{
"elements": [
{ "type": "SelectVariable", "name": "VarProduction", "caption": "Produktion (kWh)" },
{ "type": "SelectVariable", "name": "VarConsumption", "caption": "Verbrauch (kWh)" },
{ "type": "SelectVariable", "name": "VarFeedIn", "caption": "Einspeisung (kWh)" },
{ "type": "SelectVariable", "name": "VarGrid", "caption": "Bezug Netz (kWh)" }
]
}

217
Energy_Pie/module.html Normal file
View File

@@ -0,0 +1,217 @@
<div id="wrap" style="padding:12px;font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif;">
<!-- Controls -->
<div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;">
<label style="display:flex;gap:6px;align-items:center;">
<span>Zeitraum</span>
<select id="range">
<option value="day">Tag</option>
<option value="week">Woche</option>
<option value="month">Monat</option>
<option value="year">Jahr</option>
<option value="total">Gesamt</option>
</select>
</label>
<label style="display:flex;gap:6px;align-items:center;">
<span>Datum</span>
<input id="date" type="date" />
</label>
<button id="prev" type="button"></button>
<button id="today" type="button">Heute</button>
<button id="next" type="button"></button>
</div>
<div id="period" style="margin-top:10px;font-size:15px;font-weight:600;"></div>
<div id="hint" style="margin-top:6px;font-size:15px;font-weight:700;"></div>
<div id="grid"
style="margin-top:14px;
display:grid;
grid-template-columns:repeat(2,minmax(0,1fr));
gap:14px;">
</div>
<div id="err" style="margin-top:8px;color:#ffb4b4;font-size:13px;"></div>
</div>
<style>
@media (max-width:720px){
#grid{grid-template-columns:1fr}
}
#wrap{
position:relative;
overflow:hidden;
min-height:100vh;
background:#121216;
}
#wrap::before{
content:"";
position:absolute;
inset:-35%;
background:
radial-gradient(520px 420px at 18% 18%, rgba(99,179,255,.42), transparent 60%),
radial-gradient(560px 460px at 82% 28%, rgba(168,85,247,.38), transparent 62%),
radial-gradient(620px 520px at 55% 85%, rgba(99,179,255,.26), transparent 64%);
filter:blur(18px);
pointer-events:none;
}
#wrap>*{position:relative;z-index:1}
#hint .kv{margin-right:14px;white-space:nowrap}
#hint .kv b{font-weight:900}
</style>
<script>
(function(){
const elRange = document.getElementById('range');
const elDate = document.getElementById('date');
const elPrev = document.getElementById('prev');
const elToday = document.getElementById('today');
const elNext = document.getElementById('next');
const elPeriod = document.getElementById('period');
const elHint = document.getElementById('hint');
const elGrid = document.getElementById('grid');
const elErr = document.getElementById('err');
function showErr(e){
elErr.textContent = e?.message || e;
}
function ra(){
return window.requestAction || window.parent?.requestAction || null;
}
function send(id,val){
const f = ra();
if(f) try{f(id,val)}catch(e){showErr(e)}
}
function fmt(d){
const p=n=>String(n).padStart(2,'0');
return `${p(d.getDate())}.${p(d.getMonth()+1)}.${d.getFullYear()}`;
}
function monthName(m){
return ['Jan','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'][m];
}
function isoWeek(d){
d=new Date(Date.UTC(d.getFullYear(),d.getMonth(),d.getDate()));
d.setUTCDate(d.getUTCDate()+4-(d.getUTCDay()||7));
const y=d.getUTCFullYear();
const s=new Date(Date.UTC(y,0,1));
return Math.ceil((((d-s)/86400000)+1)/7)+" "+y;
}
function render(data){
if(!data) return;
elRange.value = data.range || 'day';
elDate.value = data.date || '';
elDate.disabled = (data.range === 'total');
// Zeitraum-Anzeige
if (data.range === 'total') {
// ✅ Wunsch: bei Gesamt nix anzeigen
elPeriod.textContent = '';
} else if (data.tStart && data.tEnd) {
const s = new Date(data.tStart * 1000);
const e = new Date(data.tEnd * 1000 - 1000);
if (data.range === 'day')
elPeriod.textContent = `Zeitraum: ${fmt(s)}`;
else if (data.range === 'week')
elPeriod.textContent = `Zeitraum: Woche ${isoWeek(s)}`;
else if (data.range === 'month')
elPeriod.textContent = `Zeitraum: ${monthName(s.getMonth())} ${s.getFullYear()}`;
else if (data.range === 'year')
elPeriod.textContent = `Zeitraum: ${s.getFullYear()}`;
else
elPeriod.textContent = ''; // fallback: lieber leer als falsch
} else {
elPeriod.textContent = '';
}
// Keine Daten
if(data.hasData === false){
elHint.innerHTML = `<b>Letzter Zeitpunkt</b> <span style="opacity:.7">(Keine Werte für diesen Zeitraum)</span>`;
elGrid.innerHTML = '';
return;
}
// Werte
const v = data.values || {};
elHint.innerHTML = `
<span class="kv"><b>Produktion:</b> ${v.Produktion?.toFixed(2) || 0} kWh</span>
<span class="kv"><b>Verbrauch:</b> ${v.Hausverbrauch?.toFixed(2) || 0} kWh</span>
<span class="kv"><b>Netzbezug:</b> ${v.Netz?.toFixed(2) || 0} kWh</span>
<span class="kv"><b>Einspeisung:</b> ${v.Einspeisung?.toFixed(2) || (0)} kWh</span>
`;
const donut = (t, p, c) => {
const r = 56;
const C = 2 * Math.PI * r;
const dash = (Math.max(0, Math.min(100, p)) / 100) * C;
return `
<div style="text-align:center;display:flex;flex-direction:column;align-items:center;gap:10px;">
<div style="font-weight:900">${t}</div>
<div style="position:relative;width:160px;height:160px;">
<svg width="160" height="160" viewBox="0 0 160 160">
<circle cx="80" cy="80" r="${r}"
stroke="rgba(255,255,255,0.18)"
stroke-width="18"
fill="none" />
<circle cx="80" cy="80" r="${r}"
stroke="${c}"
stroke-width="18"
fill="none"
stroke-linecap="butt"
stroke-dasharray="${dash} ${C}"
transform="rotate(-90 80 80)"
style="filter: drop-shadow(0 0 12px ${c});" />
</svg>
<div style="position:absolute;inset:0;
display:flex;align-items:center;justify-content:center;
font-size:24px;font-weight:900;">
${Number(p).toFixed(1)}%
</div>
</div>
</div>
`;
};
const prod = v.Produktion || 0;
const cons = v.Hausverbrauch || 0;
const grid = v.Netz || 0;
const feed = v.Einspeisung || 0;
const eigen = Math.max(cons - grid, 0);
elGrid.innerHTML =
donut('Eigenverbrauchsquote', prod ? (eigen / prod * 100) : 0, '#63B3FF') +
donut('Autarkiegrad', cons ? (eigen / cons * 100) : 0, '#A855F7');
}
window.handleMessage = d=>{
try{if(typeof d==='string')d=JSON.parse(d)}catch{}
render(d);
};
elRange.onchange = ()=>send('SetRange',elRange.value);
elDate.onchange = ()=>send('SetDate',elDate.value);
elPrev.onclick = ()=>send('Prev',1);
elNext.onclick = ()=>send('Next',1);
elToday.onclick = ()=>send('Today',1);
})();
</script>

13
Energy_Pie/module.json Normal file
View File

@@ -0,0 +1,13 @@
{
"id": "{97BFC43B-9BE5-AB7D-EC5A-E31BB54878E0}",
"name": "Energy_Pie",
"type": 3,
"vendor": "Belevo AG",
"aliases": [],
"parentRequirements": [],
"childRequirements": [],
"implemented": [],
"prefix": "",
"url": ""
}

252
Energy_Pie/module.php Normal file
View File

@@ -0,0 +1,252 @@
<?php
declare(strict_types=1);
class Energy_Pie extends IPSModule
{
private const ATTR_RANGE = 'Range';
private const ATTR_DATE = 'Date';
public function Create(): void
{
parent::Create();
// Source variables (logged counters, kWh)
$this->RegisterPropertyInteger('VarProduction', 0);
$this->RegisterPropertyInteger('VarConsumption', 0);
$this->RegisterPropertyInteger('VarFeedIn', 0);
$this->RegisterPropertyInteger('VarGrid', 0);
// Persisted UI state
$this->RegisterAttributeString(self::ATTR_RANGE, 'day');
$this->RegisterAttributeString(self::ATTR_DATE, date('Y-m-d'));
// Enable individual visualization (HTML-SDK)
$this->SetVisualizationType(1);
// IMPORTANT: Timer calls global helper below (must exist!)
$this->RegisterTimer('AutoPush', 0, 'IPS_RequestAction($_IPS["TARGET"], "Refresh", 1);');
}
public function ApplyChanges(): void
{
parent::ApplyChanges();
// ensure range valid
$range = $this->ReadAttributeString(self::ATTR_RANGE);
if (!in_array($range, ['day', 'week', 'month', 'year', 'total'], true)) {
$this->WriteAttributeString(self::ATTR_RANGE, 'day');
}
// ensure date valid (not empty/invalid/future)
$date = $this->ReadAttributeString(self::ATTR_DATE);
if ($date === '' || !$this->isValidDate($date) || strtotime($date . ' 00:00:00') > time()) {
$this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d'));
}
// Fullscreen-Fix: push periodically (adjust as you like)
// 2000ms = alle 2 Sekunden (stabil, aber nicht ganz so brutal wie 1000ms)
$this->SetTimerInterval('AutoPush', 2000);
$this->RecalculateAndPush();
}
public function GetVisualizationTile(): string
{
$path = __DIR__ . '/module.html';
if (!file_exists($path)) {
return '<div style="padding:12px;font-family:sans-serif;">module.html fehlt</div>';
}
return file_get_contents($path);
}
public function RequestAction($Ident, $Value): void
{
switch ($Ident) {
case 'SetRange':
$range = (string)$Value;
if (!in_array($range, ['day', 'week', 'month', 'year', 'total'], true)) {
return;
}
$this->WriteAttributeString(self::ATTR_RANGE, $range);
$this->RecalculateAndPush();
break;
case 'SetDate':
$date = (string)$Value;
if (!$this->isValidDate($date)) {
return;
}
$this->WriteAttributeString(self::ATTR_DATE, $date);
$this->RecalculateAndPush();
break;
case 'Prev':
case 'Next':
case 'Today':
$this->ShiftDate($Ident);
$this->RecalculateAndPush();
break;
case 'Refresh':
$this->RecalculateAndPush();
break;
default:
// ignore unknown
return;
}
}
private function RecalculateAndPush(): void
{
$range = $this->ReadAttributeString(self::ATTR_RANGE);
$date = $this->ReadAttributeString(self::ATTR_DATE);
[$tStart, $tEnd] = $this->getRange($range, $date);
$dbgProd = [];
$dbgFeed = [];
$dbgGrid = [];
$prod = $this->readDelta($this->ReadPropertyInteger('VarProduction'), $tStart, $tEnd, $dbgProd);
$feed = $this->readDelta($this->ReadPropertyInteger('VarFeedIn'), $tStart, $tEnd, $dbgFeed);
$grid = $this->readDelta($this->ReadPropertyInteger('VarGrid'), $tStart, $tEnd, $dbgGrid);
$hasData = (($dbgProd['count'] ?? 0) > 0) || (($dbgFeed['count'] ?? 0) > 0) || (($dbgGrid['count'] ?? 0) > 0);
$noDataHint = (!$hasData && $range !== 'total') ? 'Letzter Zeitpunkt' : '';
// House = Prod - Feed + Grid
$house = $prod - $feed + $grid;
if ($house < 0) $house = 0.0;
$payload = [
'range' => $range,
'date' => $date,
'tStart' => $tStart,
'tEnd' => $tEnd,
'hasData' => $hasData,
'noDataHint' => $noDataHint,
'values' => [
'Produktion' => (float)$prod,
'Einspeisung' => (float)$feed,
'Netz' => (float)$grid,
'Hausverbrauch' => (float)$house
],
// kannst du später entfernen
'debug' => [
'prod' => $dbgProd,
'feed' => $dbgFeed,
'grid' => $dbgGrid
]
];
$this->UpdateVisualizationValue(json_encode($payload, JSON_THROW_ON_ERROR));
}
private function getRange(string $range, string $dateYmd): array
{
$now = time();
if ($range === 'total') {
return [0, $now];
}
$base = strtotime($dateYmd . ' 00:00:00') ?: strtotime(date('Y-m-d') . ' 00:00:00');
switch ($range) {
case 'day':
return [$base, $base + 86400];
case 'week':
$dow = (int)date('N', $base); // 1=Mon..7=Sun
$start = $base - (($dow - 1) * 86400);
return [$start, $start + 7 * 86400];
case 'month':
$start = strtotime(date('Y-m-01 00:00:00', $base));
$end = strtotime(date('Y-m-01 00:00:00', strtotime('+1 month', $start)));
return [$start, $end];
case 'year':
$start = strtotime(date('Y-01-01 00:00:00', $base));
$end = strtotime(date('Y-01-01 00:00:00', strtotime('+1 year', $start)));
return [$start, $end];
default:
return [$base, $base + 86400];
}
}
public function GetVisualizationPopup(): string
{
// Popup (Fullscreen) soll das gleiche HTML wie das Tile anzeigen
$this->RecalculateAndPush();
return $this->GetVisualizationTile();
}
private function readDelta(int $varId, int $tStart, int $tEnd, array &$dbg): float
{
$dbg = [
'varId' => $varId,
'archiveId' => 0,
'count' => 0,
'first' => null,
'last' => null,
'vStart' => null,
'vEnd' => null
];
if ($varId <= 0 || !IPS_VariableExists($varId)) {
return 0.0;
}
$archiveID = IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}')[0] ?? 0;
$dbg['archiveId'] = $archiveID;
if ($archiveID <= 0) {
return 0.0;
}
$values = @AC_GetLoggedValues($archiveID, $varId, $tStart - 86400, $tEnd + 86400, 0);
if (empty($values)) {
return 0.0;
}
usort($values, static fn($a, $b) => (int)$a['TimeStamp'] <=> (int)$b['TimeStamp']);
$dbg['count'] = count($values);
$dbg['first'] = (float)$values[0]['Value'];
$dbg['last'] = (float)$values[count($values) - 1]['Value'];
$vStart = null;
$vEnd = null;
foreach ($values as $v) {
$ts = (int)$v['TimeStamp'];
if ($ts <= $tStart) $vStart = (float)$v['Value'];
if ($ts <= $tEnd) $vEnd = (float)$v['Value'];
if ($ts > $tEnd) break;
}
if ($vStart === null) $vStart = $dbg['first'];
if ($vEnd === null) $vEnd = $dbg['last'];
$dbg['vStart'] = $vStart;
$dbg['vEnd'] = $vEnd;
$diff = $vEnd - $vStart;
return ($diff < 0) ? 0.0 : (float)$diff;
}
private function getLastLogTimestamp(int $varId): int
{
if ($varId <= 0 || !IPS_VariableExists($varId)) {
return 0;
}
$archiveID = IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}')[0] ?? 0;
if ($archiveID <= 0) {
return 0;
}
$values = @AC_GetLoggedValues($archiveID, $varId, 0, time(), 1);
if (empty($values)) {
return 0;
}
return (int)$values[0]['TimeStamp'];
}
private function ShiftDate(string $action): void
{
$range = $this->ReadAttributeString(self::ATTR_RANGE);
if ($range === 'total') {
return;
}
if ($action === 'Today') {
$this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d'));
return;
}
$date = $this->ReadAttributeString(self::ATTR_DATE);
$base = strtotime($date . ' 00:00:00') ?: strtotime(date('Y-m-d') . ' 00:00:00');
$sign = ($action === 'Prev') ? -1 : 1;
switch ($range) {
case 'day':
$base = strtotime(($sign === -1 ? '-1 day' : '+1 day'), $base);
break;
case 'week':
$base = strtotime(($sign === -1 ? '-7 day' : '+7 day'), $base);
break;
case 'month':
$base = strtotime(($sign === -1 ? '-1 month' : '+1 month'), $base);
break;
case 'year':
$base = strtotime(($sign === -1 ? '-1 year' : '+1 year'), $base);
break;
}
$this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d', $base));
}
private function isValidDate(string $ymd): bool
{
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $ymd)) {
return false;
}
[$y, $m, $d] = array_map('intval', explode('-', $ymd));
return checkdate($m, $d, $y);
}
}
?>