From 627a5a84192d5dd8b5579120cec506f2def1f7f6 Mon Sep 17 00:00:00 2001 From: Sunnyka <71286632+Sunnyka98@users.noreply.github.com> Date: Mon, 14 Apr 2025 16:03:08 +0200 Subject: [PATCH 1/9] WIP LHG Report --- .gitignore | 3 +- PDFReportLHG/form.json | 98 +++++++++++ PDFReportLHG/locale.json | 9 ++ PDFReportLHG/module.json | 14 ++ PDFReportLHG/module.php | 340 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 463 insertions(+), 1 deletion(-) create mode 100644 PDFReportLHG/form.json create mode 100644 PDFReportLHG/locale.json create mode 100644 PDFReportLHG/module.json create mode 100644 PDFReportLHG/module.php diff --git a/.gitignore b/.gitignore index fd9f40a..5665460 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,5 @@ composer.phar .php_cs.cache .phpunit.result.* .phpunit.cache -.php-cs-fixer.cache \ No newline at end of file +.php-cs-fixer.cache +/.vscode diff --git a/PDFReportLHG/form.json b/PDFReportLHG/form.json new file mode 100644 index 0000000..2530086 --- /dev/null +++ b/PDFReportLHG/form.json @@ -0,0 +1,98 @@ +{ + "status": [ + { + "code": 200, + "icon": "error", + "caption": "The Counter has no data for last month" + } + ], + "elements": [ + { + "type": "RowLayout", + "items": [ + { + "type": "SelectFile", + "caption": "Logo", + "extensions": ".png, .svg", + "name": "LogoData" + }, + { + "type": "Select", + "caption": "Decimal Separator", + "name": "DecimalSeparator", + "options": [ + { + "caption": "Comma", + "value": "," + }, + { + "caption": "Dot", + "value": "." + } + ] + }, + { + "type": "Select", + "name": "AggregationLevel", + "caption": "Aggregation Level", + "options": [ + { + "caption": "Hourly", + "value": 0 + }, + { + "caption": "Daily", + "value": 1 + }, + { + "caption": "Weekly", + "value": 2 + }, + { + "caption": "Monthly", + "value": 3 + } + ] + }, + { + "type": "SelectModule", + "name": "SMTP", + "caption": "E-Mail SMTP", + "moduleID": "{375EAF21-35EF-4BC4-83B3-C780FD8BD88A}" + } + ] + }, + { + "type": "List", + "caption": "Energy Counters", + "name": "EnergyVariables", + "columns": [ + { + "caption": "Name", + "name": "Name", + "width": "250px", + "edit": { + "type": "ValidationTextBox" + }, + "add": "" + }, + { + "caption": "Counter", + "name": "CounterVariable", + "width": "auto", + "add": 0, + "edit": { + "type": "SelectVariable", + "requireLogging": 4, + "validVariableTypes": [ + 1, + 2 + ] + } + } + ], + "add": true, + "delete": true + } + ] +} \ No newline at end of file diff --git a/PDFReportLHG/locale.json b/PDFReportLHG/locale.json new file mode 100644 index 0000000..3017800 --- /dev/null +++ b/PDFReportLHG/locale.json @@ -0,0 +1,9 @@ +{ + "translations": { + "de": { + "Decimal Separator Comma": "Dezimaltrennzeichen", + "Dot": "Punkt", + "Comma": "Komma" + } + } +} \ No newline at end of file diff --git a/PDFReportLHG/module.json b/PDFReportLHG/module.json new file mode 100644 index 0000000..175fd50 --- /dev/null +++ b/PDFReportLHG/module.json @@ -0,0 +1,14 @@ +{ + "id": "{9DD58AF0-495C-2620-BF4A-2F2EF96C8927}", + "name": "PDF Report LHG", + "type": 3, + "vendor": "", + "aliases": [ + "Report (PDF, LHG)" + ], + "parentRequirements": [], + "childRequirements": [], + "implemented": [], + "prefix": "RAC", + "url": "https://www.symcon.de/en/service/documentation/module-reference/symconreport/pdfreport-lhg/" +} \ No newline at end of file diff --git a/PDFReportLHG/module.php b/PDFReportLHG/module.php new file mode 100644 index 0000000..857b679 --- /dev/null +++ b/PDFReportLHG/module.php @@ -0,0 +1,340 @@ +RegisterPropertyString('LogoData', ""); + $this->RegisterPropertyInteger('AggregationLevel', 1); + $this->RegisterPropertyString('DecimalSeparator', ','); + $this->RegisterPropertyString('EnergyVariables', '[]'); + + //Variables + $this->RegisterVariableInteger('Start', $this->Translate('Start'), '~UnixTimestampDate', 1); + $this->EnableAction('Start'); + if ($this->GetValue('Start') == 0) { + $this->SetValue('Start', time() - (60 * 60 * 24)); + } + $this->RegisterVariableInteger('End', $this->Translate('End'), '~UnixTimestampDate', 2); + $this->EnableAction('End'); + if ($this->GetValue('End') == 0) { + $this->SetValue('End', time()); + } + + $this->RegisterScript('Generate', 'Generate', "RegisterMedia(5, 'ReportPDF', $this->Translate('Report (PDF)'), 'pdf', 4); + $this->RegisterMedia(4, 'MediaChart', $this->Translate('Chart'), 'chart', 5); + + } + + public function GenerateMultiEnergyReport(): bool + { + if (count(json_decode($this->ReadPropertyString('EnergyVariables'), true)) === 0) { + echo $this->Translate('No Variables are selected.'); + return false; + } + + $pdfContent = $this->GeneratePDF('IP-Symcon ' . IPS_GetKernelVersion(), 'report.pdf'); + + if ($this->GetStatus() >= IS_EBASE) { + return false; + } + + $mediaID = $this->GetIDForIdent('ReportPDF'); + IPS_SetMediaContent($mediaID, base64_encode($pdfContent)); + + return true; + } + + public function RequestAction($Ident, $Value): void + { + $this->SetValue($Ident, intval($Value)); + } + + public function ApplyChanges() + { + + // crate MultiChart and give the id to renderChart + $dataset = []; + $variables = json_decode($this->ReadPropertyString('EnergyVariables'), true); + $this->SendDebug('Variables', print_r($variables, true), 0); + $currentMediaChart = json_decode(base64_decode(IPS_GetMediaContent($this->GetIDForIdent('MediaChart'))), true); + $currentDataset = $currentMediaChart['datasets']; + foreach ($variables as $key => $variable) { + if (!in_array($variable, array_column($currentDataset, 'variableID'))) { + $dataset[] = [ + 'variableID' => $variable['CounterVariable'], + 'fillColor' => 'clear', + 'strokeColor' => '#' . dechex(rand(0, 255)) . dechex(rand(0, 255)) . dechex(rand(0, 255)), + 'timeOffset' => 0, + 'visible' => true, + 'side' => 'left', + ]; + } + } + $id = $this->GetIDForIdent('MediaChart'); + IPS_SetMediaContent($id, base64_encode(json_encode(['datasets' => $dataset]))); + } + + private function RegisterMediaDocument($Ident, $Name, $Extension, $Position = 0): void + { + $this->RegisterMedia(5, $Ident, $Name, $Extension, $Position); + } + + private function RegisterMedia($Type, $Ident, $Name, $Extension, $Position): void + { + $mediaId = @IPS_GetObjectIDByIdent($Ident, $this->InstanceID); + if ($mediaId === false) { + + $mediaId = IPS_CreateMedia($Type); + switch ($Type) { + case 5: // Document + IPS_SetMediaFile($mediaId, 'media/' . $mediaId . '.' . $Extension, false); + break; + case 4://Chart + IPS_SetMediaFile($mediaId, 'media/' . $mediaId . '.' . $Extension, false); + break; + default: + # code... + break; + } + IPS_SetParent($mediaId, $this->InstanceID); + IPS_SetIdent($mediaId, $Ident); + IPS_SetName($mediaId, $Name); + IPS_SetPosition($mediaId, $Position); + } + } + + private function GeneratePDF($author, $filename): string + { + $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); + $pdf->SetCreator(PDF_CREATOR); + $pdf->SetAuthor($author); + $pdf->SetTitle(''); + $pdf->SetSubject(''); + + $pdf->setPrintHeader(false); + + $pdf->setFooterFont([PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA]); + $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); + + $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP - 5, PDF_MARGIN_RIGHT); + $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); + + $pdf->SetAutoPageBreak(true, PDF_MARGIN_BOTTOM); + + $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); + $pdf->setPrintFooter(false); + + $pdf->SetFont('dejavusans'); + + $pdf->AddPage(); + + //PDF Content + //Header + $logo = $this->ReadPropertyString('LogoData'); + if (strpos(base64_decode($logo), 'ImageSVG('@' . $logo, $x = 150, $y = 0, $w = 50, $h = 50, $border = 1); + $logo = ''; + } elseif ($logo != '') { + $logo = ''; + } + + $pdf->writeHTML($this->GenerateHTMLHeader($logo), true, false, true, false, ''); + + //Text + $pdf->writeHTML($this->GenerateHTMLText(), true, false, true, false, ''); + + //Chart + //Charts + $svg = $this->GenerateChart(); + $this->SendDebug('XML', $svg, 0); + $pdf->ImageSVG('@' . $svg, $x = 10, $pdf->GetY(), $w = 180, $h = '', $link = '', $align = '', $palign = '', $border = 0, $fitonpage = true); + + //Save the pdf + return $pdf->Output($filename, 'S'); + } + + private function GenerateHTMLHeader($logo) + { + $title = strtoupper($this->Translate('Consumption')); + //Get Times + $startTime = $this->GetValue('Start'); + $endTime = $this->GetValue('End'); + if ($startTime > $endTime) { + $startTime = $this->GetValue('End'); + $endTime = $this->GetValue('Start'); + } + $timestamps = $this->Translate('From') . ' ' . date('d.m.Y', $startTime) . ' ' . $this->Translate('to') . ' ' . date('d.m.Y', $endTime); + + return << + + +


+

$title

+

$timestamps

+ +
$logo + + +
+
+ EOT; + } + + private function GenerateHTMLText(): string + { + $dataText = ''; + $data = $this->FetchData(json_decode($this->ReadPropertyString('EnergyVariables'), true)); + foreach ($data['Variables'] as $key => $variable) { + $name = $variable['Name']; + $consumption = $variable['Consumption']; + $percentage = $variable['Percentage']; + + //replace the decimal separator + $consumption = str_replace('.', $this->ReadPropertyString('DecimalSeparator'), strval($consumption)); + $percentage = str_replace('.', $this->ReadPropertyString('DecimalSeparator'), strval($percentage)); + $this->SendDebug('Consumption', $consumption, 0); + $this->SendDebug('percentage', $percentage, 0); + + $dataText .= << + EOT; + } + $totalConsumption = $data['Total']; + $totalConsumption = str_replace('.', $this->ReadPropertyString('DecimalSeparator'), strval($totalConsumption)); + $textCounter = $this->Translate('Counter'); + $textConsumption = $this->Translate('Consumption'); + $textPercentage = $this->Translate('Percentage'); + $textTotalConsumption = $this->Translate('Total Consumption'); + + return << +

$dataText

+

$textTotalConsumption: $totalConsumption kwh

+ EOT; + } + + private function GenerateChart() + { + + $archivID = IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}')[0]; + $this->SendDebug("end",date("d.m.y", strtotime("00:00:00", $this->GetValue('End'))), 0); + $this->SendDebug("Start", date("d.m.y",strtotime("00:00:00", $this->GetValue('Start')),), 0); + + $chart = '' . AC_RenderChart( + $archivID, + $this->GetIDForIdent('MediaChart'), + strtotime("00:00:00", $this->GetValue('Start')), + $this->ReadPropertyInteger('AggregationLevel'), + 0, + false, + false, + 800, + 500 + ) . ''; + $example = simplexml_load_string($chart); + $this->SendDebug('chart', $chart, 0); + + //add text-anchor + foreach ($example->svg->g as $object) { + if ($object['class'] == 'y axis') { + $object->g->addAttribute('text-anchor', 'end'); + } + } + + //fill the bars + $object = $example->svg; + if ($object['class'] == 'bar multi') { + $object = $example->svg->g[3]->g[1]; + $object->addAttribute('fill', 'yellowgreen'); + } else { + //svg -> graphs -> outline + $object = $example->svg->g[3]->g[1]->g; + $object->addAttribute('stroke', 'black'); + $object->addAttribute('fill', 'none'); + + // svg -> graphs -> background + $object = $example->svg->g[3]->g[0]->g; + $object->addAttribute('opacity', '0'); + } + + //transform the grid + $object = $example->svg->g[0]->line; + for ($i = 0; $i < count($object); $i++) { + $node = $object[$i]; + + //set the opacity of the vertical lines on 0 (trancparence) + //"remove" the vertical lines + if (!empty($node) && $node['class'] == 'gridLine y') { + $node->addAttribute('opacity', '0'); + } + if (!empty($node) && $node['class'] == 'gridLine y firstLine') { + $node->addAttribute('opacity', '0'); + } + + //set the horizontal lines grey + if (!empty($node) && $node['class'] == 'gridLine x' || $node['class'] == 'gridLine x firstLine') { + $node->addAttribute('opacity', '.2'); + } + } + + return $example->asXML(); + } + + private function FetchData(array $variables): array + { + $archiveID = IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}')[0]; + //Get Times + $startTime = $this->GetValue('Start'); + $endTime = $this->GetValue('End'); + if ($startTime > $endTime) { + $startTime = $this->GetValue('End'); + $endTime = $this->GetValue('Start'); + } + $data = []; + $totalConsumption = 0; + + //Get the consumption + foreach ($variables as $variable) { + $name = $variable["Name"] == "" ? IPS_GetName($variable['CounterVariable']) : $variable["Name"]; + $variable = $variable['CounterVariable']; + $aggregatedValues = AC_GetAggregatedValues($archiveID, $variable, $this->ReadPropertyInteger('AggregationLevel'), $startTime, $endTime, 0); + $this->SendDebug('Values of' . $variable, print_r($aggregatedValues, true), 0); + //ToDO look if the Values are 1000 and the Endtime match + + if (count($aggregatedValues) === 1000 && $startTime != $aggregatedValues[array_key_last($aggregatedValues)]['TimeStamp']) { + $this->SendDebug('Variable ' . $variable, 'Too many datasets, get higher aggregationLevel, to fetch all datasets for the period', 0); + } + $consumption = round(array_sum(array_column($aggregatedValues, 'Avg')), 2); + $totalConsumption += $consumption; + $data[] = [ + 'Name' => $name, + 'Consumption' => $consumption, + 'Percentage' => 0 + ]; + } + + $values['Total'] = $totalConsumption; + if ($totalConsumption == 0) { + $totalConsumption = 1; // To prevent the division by zero + } + //Calculate the percentage + foreach ($data as $key => $value) { + $data[$key]['Percentage'] = round(($value['Consumption'] / $totalConsumption) * 100, 2); + } + $values['Variables'] = $data; + + return $values; + } +} \ No newline at end of file From 263c181715beee4f0b0c8721bf7ea65f2ce34c30 Mon Sep 17 00:00:00 2001 From: Sunnyka <71286632+Sunnyka98@users.noreply.github.com> Date: Mon, 14 Apr 2025 16:06:34 +0200 Subject: [PATCH 2/9] fix locale --- PDFReportSingle/locale.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PDFReportSingle/locale.json b/PDFReportSingle/locale.json index 7437c97..a1e63fd 100644 --- a/PDFReportSingle/locale.json +++ b/PDFReportSingle/locale.json @@ -31,7 +31,7 @@ "Data Limit (Min)": "Toleranz (Min)", "Data Limit (Max)": "Toleranz (Max)", "Generate report now!": "Jetzt Report generieren!", - "Decimal Separator Comma": "Dezimaltrennzeichen Komma", + "Decimal Separator": "Dezimaltrennzeichen", "Done! Please open the media file beneath this instance!": "Fertig! Bitte öffnen Sie die Mediendatei unterhalb der Instanz!", "https://www.symcon.de/en/service/documentation/module-reference/symconreport/pdfreport-single/": "https://www.symcon.de/de/service/dokumentation/modulreferenz/symconreport/pdfreport-single/", "Dot": "Punkt", From 23c50d0d3187c656d67daf03042e715f72481f19 Mon Sep 17 00:00:00 2001 From: Sunnyka <71286632+Sunnyka98@users.noreply.github.com> Date: Mon, 14 Apr 2025 16:33:25 +0200 Subject: [PATCH 3/9] fix error of chart --- PDFReportLHG/module.php | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/PDFReportLHG/module.php b/PDFReportLHG/module.php index 857b679..e2dfdb1 100644 --- a/PDFReportLHG/module.php +++ b/PDFReportLHG/module.php @@ -12,7 +12,7 @@ public function Create() parent::Create(); //Properties - $this->RegisterPropertyString('LogoData', ""); + $this->RegisterPropertyString('LogoData', ''); $this->RegisterPropertyInteger('AggregationLevel', 1); $this->RegisterPropertyString('DecimalSeparator', ','); $this->RegisterPropertyString('EnergyVariables', '[]'); @@ -66,10 +66,9 @@ public function ApplyChanges() $dataset = []; $variables = json_decode($this->ReadPropertyString('EnergyVariables'), true); $this->SendDebug('Variables', print_r($variables, true), 0); - $currentMediaChart = json_decode(base64_decode(IPS_GetMediaContent($this->GetIDForIdent('MediaChart'))), true); - $currentDataset = $currentMediaChart['datasets']; - foreach ($variables as $key => $variable) { - if (!in_array($variable, array_column($currentDataset, 'variableID'))) { + if (@IPS_GetMediaContent($this->GetIDForIdent('MediaChart')) === false) { + foreach ($variables as $key => $variable) { + $dataset[] = [ 'variableID' => $variable['CounterVariable'], 'fillColor' => 'clear', @@ -78,6 +77,22 @@ public function ApplyChanges() 'visible' => true, 'side' => 'left', ]; + + } + }else { + $currentMediaChart = json_decode(base64_decode(IPS_GetMediaContent($this->GetIDForIdent('MediaChart'))), true); + $currentDataset = $currentMediaChart['datasets']; + foreach ($variables as $key => $variable) { + if (!in_array($variable, array_column($currentDataset, 'variableID'))) { + $dataset[] = [ + 'variableID' => $variable['CounterVariable'], + 'fillColor' => 'clear', + 'strokeColor' => '#' . dechex(rand(0, 255)) . dechex(rand(0, 255)) . dechex(rand(0, 255)), + 'timeOffset' => 0, + 'visible' => true, + 'side' => 'left', + ]; + } } } $id = $this->GetIDForIdent('MediaChart'); @@ -229,18 +244,18 @@ private function GenerateChart() { $archivID = IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}')[0]; - $this->SendDebug("end",date("d.m.y", strtotime("00:00:00", $this->GetValue('End'))), 0); - $this->SendDebug("Start", date("d.m.y",strtotime("00:00:00", $this->GetValue('Start')),), 0); + $this->SendDebug('end', date('d.m.y', strtotime('00:00:00', $this->GetValue('End'))), 0); + $this->SendDebug('Start', date('d.m.y', strtotime('00:00:00', $this->GetValue('Start'))), 0); $chart = '' . AC_RenderChart( $archivID, $this->GetIDForIdent('MediaChart'), - strtotime("00:00:00", $this->GetValue('Start')), + strtotime('00:00:00', $this->GetValue('Start')), $this->ReadPropertyInteger('AggregationLevel'), 0, false, false, - 800, + 800, 500 ) . ''; $example = simplexml_load_string($chart); @@ -307,7 +322,7 @@ private function FetchData(array $variables): array //Get the consumption foreach ($variables as $variable) { - $name = $variable["Name"] == "" ? IPS_GetName($variable['CounterVariable']) : $variable["Name"]; + $name = $variable['Name'] == '' ? IPS_GetName($variable['CounterVariable']) : $variable['Name']; $variable = $variable['CounterVariable']; $aggregatedValues = AC_GetAggregatedValues($archiveID, $variable, $this->ReadPropertyInteger('AggregationLevel'), $startTime, $endTime, 0); $this->SendDebug('Values of' . $variable, print_r($aggregatedValues, true), 0); From 5021cbca8f65720035e50fecafa3e141959d7122 Mon Sep 17 00:00:00 2001 From: Sunnyka <71286632+Sunnyka98@users.noreply.github.com> Date: Mon, 14 Apr 2025 17:08:52 +0200 Subject: [PATCH 4/9] set dyn true --- PDFReportLHG/module.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PDFReportLHG/module.php b/PDFReportLHG/module.php index e2dfdb1..8cceca4 100644 --- a/PDFReportLHG/module.php +++ b/PDFReportLHG/module.php @@ -254,7 +254,7 @@ private function GenerateChart() $this->ReadPropertyInteger('AggregationLevel'), 0, false, - false, + true, 800, 500 ) . ''; From b1e08df2e699964537ece0a077bb3a454d6e0d01 Mon Sep 17 00:00:00 2001 From: Sunnyka <71286632+Sunnyka98@users.noreply.github.com> Date: Wed, 16 Apr 2025 10:37:01 +0200 Subject: [PATCH 5/9] Add sendReport --- PDFReportLHG/form.json | 7 +++++++ PDFReportLHG/module.php | 41 ++++++++++++++++++++++++++++++++++++++--- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/PDFReportLHG/form.json b/PDFReportLHG/form.json index 2530086..9a3af90 100644 --- a/PDFReportLHG/form.json +++ b/PDFReportLHG/form.json @@ -59,6 +59,13 @@ "name": "SMTP", "caption": "E-Mail SMTP", "moduleID": "{375EAF21-35EF-4BC4-83B3-C780FD8BD88A}" + }, + { + "type": "SelectVariable", + "name": "DifferentReciever", + "caption": "DiffrentReciever", + "validVariableTypes": [3] + } ] }, diff --git a/PDFReportLHG/module.php b/PDFReportLHG/module.php index 8cceca4..fe159ba 100644 --- a/PDFReportLHG/module.php +++ b/PDFReportLHG/module.php @@ -16,6 +16,8 @@ public function Create() $this->RegisterPropertyInteger('AggregationLevel', 1); $this->RegisterPropertyString('DecimalSeparator', ','); $this->RegisterPropertyString('EnergyVariables', '[]'); + $this->RegisterPropertyInteger('SMTP', 0); + $this->RegisterPropertyInteger('DifferentReciever', 0); //Variables $this->RegisterVariableInteger('Start', $this->Translate('Start'), '~UnixTimestampDate', 1); @@ -29,13 +31,13 @@ public function Create() $this->SetValue('End', time()); } - $this->RegisterScript('Generate', 'Generate', "RegisterScript('Generate', 'Generate', "RegisterMedia(5, 'ReportPDF', $this->Translate('Report (PDF)'), 'pdf', 4); $this->RegisterMedia(4, 'MediaChart', $this->Translate('Chart'), 'chart', 5); } - public function GenerateMultiEnergyReport(): bool + public function GenerateReport(): bool { if (count(json_decode($this->ReadPropertyString('EnergyVariables'), true)) === 0) { echo $this->Translate('No Variables are selected.'); @@ -97,6 +99,40 @@ public function ApplyChanges() } $id = $this->GetIDForIdent('MediaChart'); IPS_SetMediaContent($id, base64_encode(json_encode(['datasets' => $dataset]))); + + $refs = $this->GetReferenceList(); + foreach ($refs as $ref) { + $this->UnregisterReference($ref); + } + // Register reference of the counter and the reciever and the instance + } + + public function SendReport(string $topic, string $body): bool + { + $smtp = $this->ReadPropertyInteger('SMTP'); + if (!IPS_InstanceExists($smtp)) { + $this->SendDebug('SMTP', "Don't exist", 0); + return false; + } + if ($this->GenerateReport()) { + $reciever = $this->ReadPropertyInteger('DifferentReciever'); + if (IPS_VariableExists($reciever)) { + $reciever = GetValue($reciever); + if (filter_var($reciever, FILTER_VALIDATE_EMAIL) === false) { + $reciever = false; + } + } + else { + $reciever = false; + } + if ($reciever) { + return SMTP_SendMailMediaEx($smtp, $reciever, $topic, $body, $this->GetIDForIdent('ReportPDF')); + } + else { + return SMTP_SendMailMedia($smtp, $topic, $body, $this->GetIDForIdent('ReportPDF')); + } + } + $this->SendDebug('SendReport', 'Something is wrong', 0); } private function RegisterMediaDocument($Ident, $Name, $Extension, $Position = 0): void @@ -172,7 +208,6 @@ private function GeneratePDF($author, $filename): string //Chart //Charts $svg = $this->GenerateChart(); - $this->SendDebug('XML', $svg, 0); $pdf->ImageSVG('@' . $svg, $x = 10, $pdf->GetY(), $w = 180, $h = '', $link = '', $align = '', $palign = '', $border = 0, $fitonpage = true); //Save the pdf From 44f5910d580d8f2eb304f44bb970d8cb5dcbeffb Mon Sep 17 00:00:00 2001 From: Niels Thole Date: Fri, 6 Nov 2026 14:05:58 +0100 Subject: [PATCH 6/9] Update report - Complete rebuild of generated chart, allowing more flexibility for start and end - Removed aggregation level, it's determined depending on start and end - Translate module, including configuration, variable names and report, removing property for decimal seperator in the process --- PDFReportLHG/form.json | 40 +---- PDFReportLHG/locale.json | 26 ++- PDFReportLHG/module.php | 335 ++++++++++++++++++++++++--------------- 3 files changed, 234 insertions(+), 167 deletions(-) diff --git a/PDFReportLHG/form.json b/PDFReportLHG/form.json index 9a3af90..6765e2f 100644 --- a/PDFReportLHG/form.json +++ b/PDFReportLHG/form.json @@ -16,44 +16,6 @@ "extensions": ".png, .svg", "name": "LogoData" }, - { - "type": "Select", - "caption": "Decimal Separator", - "name": "DecimalSeparator", - "options": [ - { - "caption": "Comma", - "value": "," - }, - { - "caption": "Dot", - "value": "." - } - ] - }, - { - "type": "Select", - "name": "AggregationLevel", - "caption": "Aggregation Level", - "options": [ - { - "caption": "Hourly", - "value": 0 - }, - { - "caption": "Daily", - "value": 1 - }, - { - "caption": "Weekly", - "value": 2 - }, - { - "caption": "Monthly", - "value": 3 - } - ] - }, { "type": "SelectModule", "name": "SMTP", @@ -63,7 +25,7 @@ { "type": "SelectVariable", "name": "DifferentReciever", - "caption": "DiffrentReciever", + "caption": "Different receiver (variable with e-mail address)", "validVariableTypes": [3] } diff --git a/PDFReportLHG/locale.json b/PDFReportLHG/locale.json index 3017800..2f3aba7 100644 --- a/PDFReportLHG/locale.json +++ b/PDFReportLHG/locale.json @@ -1,9 +1,27 @@ { "translations": { "de": { - "Decimal Separator Comma": "Dezimaltrennzeichen", - "Dot": "Punkt", - "Comma": "Komma" + "The Counter has no data for last month": "Der Zähler hat keine Daten für den letzten Monat", + "Logo": "Logo", + "E-Mail SMTP": "E-Mail SMTP", + "Different receiver (variable with e-mail address)": "Abweichender Empfänger (Variable mit E-Mail-Adresse)", + "Energy Counters": "Energiezähler", + "Name": "Name", + "Counter": "Zähler", + "Start": "Start", + "End": "Ende", + "Generate": "Generieren", + "Report (PDF)": "Bericht (PDF)", + "Chart": "Diagramm", + "No Variables are selected.": "Es sind keine Variablen ausgewählt.", + "Consumption": "Verbrauch", + "From": "Von", + "to": "bis", + "Total Consumption": "Gesamtverbrauch", + "m/d/Y": "d.m.Y", + "m/d": "d.m.", + "m/Y": "m.Y", + ".": "," } } -} \ No newline at end of file +} diff --git a/PDFReportLHG/module.php b/PDFReportLHG/module.php index fe159ba..8cdd304 100644 --- a/PDFReportLHG/module.php +++ b/PDFReportLHG/module.php @@ -6,6 +6,8 @@ class PDFReportLHG extends IPSModule { + private const COLORS = ['#9ACD32', '#4682B4', '#FF8C00', '#8B008B', '#20B2AA', '#DC143C', '#808000', '#1E90FF']; + public function Create() { // Diese Zeile nicht löschen. @@ -13,8 +15,6 @@ public function Create() //Properties $this->RegisterPropertyString('LogoData', ''); - $this->RegisterPropertyInteger('AggregationLevel', 1); - $this->RegisterPropertyString('DecimalSeparator', ','); $this->RegisterPropertyString('EnergyVariables', '[]'); $this->RegisterPropertyInteger('SMTP', 0); $this->RegisterPropertyInteger('DifferentReciever', 0); @@ -31,7 +31,7 @@ public function Create() $this->SetValue('End', time()); } - $this->RegisterScript('Generate', 'Generate', "RegisterScript('Generate', $this->Translate('Generate'), "RegisterMedia(5, 'ReportPDF', $this->Translate('Report (PDF)'), 'pdf', 4); $this->RegisterMedia(4, 'MediaChart', $this->Translate('Chart'), 'chart', 5); @@ -64,41 +64,35 @@ public function RequestAction($Ident, $Value): void public function ApplyChanges() { - // crate MultiChart and give the id to renderChart - $dataset = []; - $variables = json_decode($this->ReadPropertyString('EnergyVariables'), true); - $this->SendDebug('Variables', print_r($variables, true), 0); - if (@IPS_GetMediaContent($this->GetIDForIdent('MediaChart')) === false) { - foreach ($variables as $key => $variable) { - - $dataset[] = [ - 'variableID' => $variable['CounterVariable'], - 'fillColor' => 'clear', - 'strokeColor' => '#' . dechex(rand(0, 255)) . dechex(rand(0, 255)) . dechex(rand(0, 255)), + // The chart is not used for the PDF, but allows to view the counters in the visualization + // Keep the datasets of existing counters (e.g. changed colors) and add new counters with the colors of the PDF + $chartID = $this->GetIDForIdent('MediaChart'); + $currentDatasets = []; + $content = @IPS_GetMediaContent($chartID); + if ($content !== false && $content !== '') { + $currentChart = json_decode(base64_decode($content), true); + if (isset($currentChart['datasets'])) { + $currentDatasets = array_column($currentChart['datasets'], null, 'variableID'); + } + } + $datasets = []; + foreach (json_decode($this->ReadPropertyString('EnergyVariables'), true) as $index => $variable) { + $variableID = $variable['CounterVariable']; + if (isset($currentDatasets[$variableID])) { + $datasets[] = $currentDatasets[$variableID]; + } else { + $color = self::COLORS[$index % count(self::COLORS)]; + $datasets[] = [ + 'variableID' => $variableID, + 'fillColor' => $color, + 'strokeColor' => $color, 'timeOffset' => 0, 'visible' => true, 'side' => 'left', ]; - - } - }else { - $currentMediaChart = json_decode(base64_decode(IPS_GetMediaContent($this->GetIDForIdent('MediaChart'))), true); - $currentDataset = $currentMediaChart['datasets']; - foreach ($variables as $key => $variable) { - if (!in_array($variable, array_column($currentDataset, 'variableID'))) { - $dataset[] = [ - 'variableID' => $variable['CounterVariable'], - 'fillColor' => 'clear', - 'strokeColor' => '#' . dechex(rand(0, 255)) . dechex(rand(0, 255)) . dechex(rand(0, 255)), - 'timeOffset' => 0, - 'visible' => true, - 'side' => 'left', - ]; - } } } - $id = $this->GetIDForIdent('MediaChart'); - IPS_SetMediaContent($id, base64_encode(json_encode(['datasets' => $dataset]))); + IPS_SetMediaContent($chartID, base64_encode(json_encode(['datasets' => $datasets]))); $refs = $this->GetReferenceList(); foreach ($refs as $ref) { @@ -202,12 +196,14 @@ private function GeneratePDF($author, $filename): string $pdf->writeHTML($this->GenerateHTMLHeader($logo), true, false, true, false, ''); + //Text and chart are based on the same data to match each other + $data = $this->FetchData(json_decode($this->ReadPropertyString('EnergyVariables'), true)); + //Text - $pdf->writeHTML($this->GenerateHTMLText(), true, false, true, false, ''); + $pdf->writeHTML($this->GenerateHTMLText($data), true, false, true, false, ''); //Chart - //Charts - $svg = $this->GenerateChart(); + $svg = $this->GenerateChart($data); $pdf->ImageSVG('@' . $svg, $x = 10, $pdf->GetY(), $w = 180, $h = '', $link = '', $align = '', $palign = '', $border = 0, $fitonpage = true); //Save the pdf @@ -216,15 +212,11 @@ private function GeneratePDF($author, $filename): string private function GenerateHTMLHeader($logo) { - $title = strtoupper($this->Translate('Consumption')); + $title = mb_strtoupper($this->Translate('Consumption')); //Get Times - $startTime = $this->GetValue('Start'); - $endTime = $this->GetValue('End'); - if ($startTime > $endTime) { - $startTime = $this->GetValue('End'); - $endTime = $this->GetValue('Start'); - } - $timestamps = $this->Translate('From') . ' ' . date('d.m.Y', $startTime) . ' ' . $this->Translate('to') . ' ' . date('d.m.Y', $endTime); + [$startTime, $endTime] = $this->GetTimeRange(); + // The end is exclusive, so display the last day of the range + $timestamps = $this->Translate('From') . ' ' . date($this->Translate('m/d/Y'), $startTime) . ' ' . $this->Translate('to') . ' ' . date($this->Translate('m/d/Y'), $endTime - 1); return << @@ -242,116 +234,204 @@ private function GenerateHTMLHeader($logo) EOT; } - private function GenerateHTMLText(): string + private function GenerateHTMLText(array $data): string { $dataText = ''; - $data = $this->FetchData(json_decode($this->ReadPropertyString('EnergyVariables'), true)); foreach ($data['Variables'] as $key => $variable) { $name = $variable['Name']; - $consumption = $variable['Consumption']; - $percentage = $variable['Percentage']; - - //replace the decimal separator - $consumption = str_replace('.', $this->ReadPropertyString('DecimalSeparator'), strval($consumption)); - $percentage = str_replace('.', $this->ReadPropertyString('DecimalSeparator'), strval($percentage)); + $consumption = $this->FormatNumber($variable['Consumption'], 2); $this->SendDebug('Consumption', $consumption, 0); - $this->SendDebug('percentage', $percentage, 0); + $this->SendDebug('percentage', $variable['Percentage'], 0); $dataText .= << EOT; } - $totalConsumption = $data['Total']; - $totalConsumption = str_replace('.', $this->ReadPropertyString('DecimalSeparator'), strval($totalConsumption)); - $textCounter = $this->Translate('Counter'); - $textConsumption = $this->Translate('Consumption'); - $textPercentage = $this->Translate('Percentage'); + $totalConsumption = $this->FormatNumber($data['Total'], 2); $textTotalConsumption = $this->Translate('Total Consumption'); return <<

$dataText

-

$textTotalConsumption: $totalConsumption kwh

+

$textTotalConsumption: $totalConsumption kWh

EOT; } - private function GenerateChart() + private function GenerateChart(array $data): string { + $width = 800; + $height = 500; + $colors = self::COLORS; + $font = 'font-family="dejavusans"'; + $variables = $data['Variables']; + $labels = $data['Labels']; + + //Layout: the legend is placed below the chart with 3 entries per row + $legendRows = intval(ceil(count($variables) / 3)); + $plotLeft = 80; + $plotRight = $width - 20; + $plotTop = 30; + $plotBottom = $height - 50 - ($legendRows * 20); + + //Stack the values of all variables (positive values upwards, negative values downwards) + $maxValue = 0; + $minValue = 0; + foreach (array_keys($labels) as $key) { + $positive = 0; + $negative = 0; + foreach ($variables as $variable) { + if ($variable['Values'][$key] >= 0) { + $positive += $variable['Values'][$key]; + } else { + $negative += $variable['Values'][$key]; + } + } + $maxValue = max($maxValue, $positive); + $minValue = min($minValue, $negative); + } + if ($maxValue == $minValue) { + $maxValue = 1; + } - $archivID = IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}')[0]; - $this->SendDebug('end', date('d.m.y', strtotime('00:00:00', $this->GetValue('End'))), 0); - $this->SendDebug('Start', date('d.m.y', strtotime('00:00:00', $this->GetValue('Start'))), 0); - - $chart = '' . AC_RenderChart( - $archivID, - $this->GetIDForIdent('MediaChart'), - strtotime('00:00:00', $this->GetValue('Start')), - $this->ReadPropertyInteger('AggregationLevel'), - 0, - false, - true, - 800, - 500 - ) . ''; - $example = simplexml_load_string($chart); - $this->SendDebug('chart', $chart, 0); - - //add text-anchor - foreach ($example->svg->g as $object) { - if ($object['class'] == 'y axis') { - $object->g->addAttribute('text-anchor', 'end'); + //Calculate the y axis + $step = $this->GetAxisStep($maxValue - $minValue); + $decimals = $step < 1 ? intval(ceil(-log10($step))) : 0; + $axisMax = ceil($maxValue / $step) * $step; + $axisMin = floor($minValue / $step) * $step; + $getY = function ($value) use ($axisMin, $axisMax, $plotTop, $plotBottom) + { + return $plotBottom - (($value - $axisMin) / ($axisMax - $axisMin)) * ($plotBottom - $plotTop); + }; + + $svg = ''; + + //Grid and y axis labels + for ($value = $axisMin; $value <= $axisMax + ($step / 2); $value += $step) { + $y = round($getY($value), 2); + $svg .= ''; + $svg .= '' . $this->FormatNumber($value, $decimals) . ''; + } + $svg .= 'kWh'; + + //Bars + $slotWidth = ($plotRight - $plotLeft) / max(count($labels), 1); + $barWidth = round($slotWidth * 0.7, 2); + $labelStep = intval(ceil(count($labels) / 16)); + $index = 0; + foreach ($labels as $key => $label) { + $x = round($plotLeft + ($index * $slotWidth) + ($slotWidth * 0.15), 2); + $positive = 0; + $negative = 0; + foreach ($variables as $variableIndex => $variable) { + $value = $variable['Values'][$key]; + if ($value == 0) { + continue; + } + if ($value > 0) { + $top = $getY($positive + $value); + $bottom = $getY($positive); + $positive += $value; + } else { + $top = $getY($negative); + $bottom = $getY($negative + $value); + $negative += $value; + } + $svg .= ''; } + + //Reduce the labels if there are too many bars + if (($index % $labelStep) == 0) { + $svg .= '' . $label . ''; + } + $index++; } - //fill the bars - $object = $example->svg; - if ($object['class'] == 'bar multi') { - $object = $example->svg->g[3]->g[1]; - $object->addAttribute('fill', 'yellowgreen'); - } else { - //svg -> graphs -> outline - $object = $example->svg->g[3]->g[1]->g; - $object->addAttribute('stroke', 'black'); - $object->addAttribute('fill', 'none'); - - // svg -> graphs -> background - $object = $example->svg->g[3]->g[0]->g; - $object->addAttribute('opacity', '0'); + //Zero line + $y = round($getY(0), 2); + $svg .= ''; + + //Legend + foreach ($variables as $variableIndex => $variable) { + $x = $plotLeft + (($variableIndex % 3) * 230); + $y = $plotBottom + 45 + (intval(floor($variableIndex / 3)) * 20); + $svg .= ''; + $svg .= '' . htmlspecialchars($variable['Name'], ENT_XML1) . ''; } - //transform the grid - $object = $example->svg->g[0]->line; - for ($i = 0; $i < count($object); $i++) { - $node = $object[$i]; + return $svg . ''; + } - //set the opacity of the vertical lines on 0 (trancparence) - //"remove" the vertical lines - if (!empty($node) && $node['class'] == 'gridLine y') { - $node->addAttribute('opacity', '0'); - } - if (!empty($node) && $node['class'] == 'gridLine y firstLine') { - $node->addAttribute('opacity', '0'); - } + /** + * Formats the number with the decimal separator matching the language of the server + */ + private function FormatNumber(float $value, int $decimals): string + { + return number_format($value, $decimals, $this->Translate('.'), ''); + } - //set the horizontal lines grey - if (!empty($node) && $node['class'] == 'gridLine x' || $node['class'] == 'gridLine x firstLine') { - $node->addAttribute('opacity', '.2'); + /** + * Returns a step size of 1, 2 or 5 multiplied by a power of ten, which results in about 5 grid lines + */ + private function GetAxisStep(float $range): float + { + $roughStep = $range / 5; + $magnitude = pow(10, floor(log10($roughStep))); + foreach ([1, 2, 5] as $factor) { + if (($factor * $magnitude) >= $roughStep) { + return $factor * $magnitude; } } - - return $example->asXML(); + return 10 * $magnitude; } - private function FetchData(array $variables): array + /** + * Returns the selected time range [start, end) from 00:00:00 of the start day until 00:00:00 of the day after the end day + */ + private function GetTimeRange(): array { - $archiveID = IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}')[0]; - //Get Times $startTime = $this->GetValue('Start'); $endTime = $this->GetValue('End'); if ($startTime > $endTime) { - $startTime = $this->GetValue('End'); - $endTime = $this->GetValue('Start'); + [$startTime, $endTime] = [$endTime, $startTime]; + } + return [strtotime('00:00:00', $startTime), strtotime('+1 day', strtotime('00:00:00', $endTime))]; + } + + /** + * Returns how the values are grouped into the bars of the chart depending on the length of the time range + * Level: aggregation level for AC_GetAggregatedValues, Step: length of these periods, + * Key: date format to group the periods into bars, Label: date format of the bar labels + */ + private function GetBarInterval(int $startTime, int $endTime): array + { + $days = round(($endTime - $startTime) / (60 * 60 * 24)); + if ($days <= 1) { + return ['Level' => 0, 'Step' => '+1 hour', 'Key' => 'Y-m-d H', 'Label' => 'H:i']; + } elseif ($days <= 62) { + return ['Level' => 1, 'Step' => '+1 day', 'Key' => 'Y-m-d', 'Label' => $this->Translate('m/d')]; + } elseif ($days <= 731) { + return ['Level' => 1, 'Step' => '+1 day', 'Key' => 'Y-m', 'Label' => $this->Translate('m/Y')]; + } + return ['Level' => 1, 'Step' => '+1 day', 'Key' => 'Y', 'Label' => 'Y']; + } + + private function FetchData(array $variables): array + { + $archiveID = IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}')[0]; + [$startTime, $endTime] = $this->GetTimeRange(); + $this->SendDebug('Time range', date('d.m.Y H:i', $startTime) . ' - ' . date('d.m.Y H:i', $endTime), 0); + + //Create the bars of the chart + //Bars are grouped from whole hours/days, so they don't exceed the time range (e.g. the first month starts on the start day) + $interval = $this->GetBarInterval($startTime, $endTime); + $labels = []; + for ($time = $startTime; $time < $endTime; $time = strtotime($interval['Step'], $time)) { + $key = date($interval['Key'], $time); + if (!isset($labels[$key])) { + $labels[$key] = date($interval['Label'], $time); + } } + $data = []; $totalConsumption = 0; @@ -359,19 +439,25 @@ private function FetchData(array $variables): array foreach ($variables as $variable) { $name = $variable['Name'] == '' ? IPS_GetName($variable['CounterVariable']) : $variable['Name']; $variable = $variable['CounterVariable']; - $aggregatedValues = AC_GetAggregatedValues($archiveID, $variable, $this->ReadPropertyInteger('AggregationLevel'), $startTime, $endTime, 0); + //AC_GetAggregatedValues returns all periods starting within [start, end], so the period starting at the end has to be excluded + $aggregatedValues = AC_GetAggregatedValues($archiveID, $variable, $interval['Level'], $startTime, $endTime - 1, 0); $this->SendDebug('Values of' . $variable, print_r($aggregatedValues, true), 0); - //ToDO look if the Values are 1000 and the Endtime match - if (count($aggregatedValues) === 1000 && $startTime != $aggregatedValues[array_key_last($aggregatedValues)]['TimeStamp']) { - $this->SendDebug('Variable ' . $variable, 'Too many datasets, get higher aggregationLevel, to fetch all datasets for the period', 0); + $barValues = array_fill_keys(array_keys($labels), 0); + foreach ($aggregatedValues as $aggregatedValue) { + $key = date($interval['Key'], $aggregatedValue['TimeStamp']); + if (isset($barValues[$key])) { + $barValues[$key] += $aggregatedValue['Avg']; + } } - $consumption = round(array_sum(array_column($aggregatedValues, 'Avg')), 2); + + $consumption = round(array_sum($barValues), 2); $totalConsumption += $consumption; $data[] = [ 'Name' => $name, 'Consumption' => $consumption, - 'Percentage' => 0 + 'Percentage' => 0, + 'Values' => $barValues ]; } @@ -384,7 +470,8 @@ private function FetchData(array $variables): array $data[$key]['Percentage'] = round(($value['Consumption'] / $totalConsumption) * 100, 2); } $values['Variables'] = $data; + $values['Labels'] = $labels; return $values; } -} \ No newline at end of file +} From 88ab5298346be2fc141fff0e307986a04b9d2bba Mon Sep 17 00:00:00 2001 From: Niels Thole Date: Mon, 9 Nov 2026 13:24:34 +0100 Subject: [PATCH 7/9] Style fix --- PDFReportLHG/form.json | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/PDFReportLHG/form.json b/PDFReportLHG/form.json index 6765e2f..1351363 100644 --- a/PDFReportLHG/form.json +++ b/PDFReportLHG/form.json @@ -26,8 +26,9 @@ "type": "SelectVariable", "name": "DifferentReciever", "caption": "Different receiver (variable with e-mail address)", - "validVariableTypes": [3] - + "validVariableTypes": [ + 3 + ] } ] }, From a5c7e880389bc1b989cfc2ffa3ac4fe19110aa5c Mon Sep 17 00:00:00 2001 From: Niels Thole Date: Mon, 9 Nov 2026 14:04:00 +0100 Subject: [PATCH 8/9] Generalise module from LHG to Consumption in general. Also, support different units, taking the displayed one from the first variable on the list --- .../form.json | 2 +- .../locale.json | 5 ++-- .../module.json | 6 ++-- .../module.php | 29 ++++++++----------- 4 files changed, 18 insertions(+), 24 deletions(-) rename {PDFReportLHG => PDFReportConsumption}/form.json (97%) rename {PDFReportLHG => PDFReportConsumption}/locale.json (90%) rename {PDFReportLHG => PDFReportConsumption}/module.json (69%) rename {PDFReportLHG => PDFReportConsumption}/module.php (94%) diff --git a/PDFReportLHG/form.json b/PDFReportConsumption/form.json similarity index 97% rename from PDFReportLHG/form.json rename to PDFReportConsumption/form.json index 1351363..13b7985 100644 --- a/PDFReportLHG/form.json +++ b/PDFReportConsumption/form.json @@ -34,7 +34,7 @@ }, { "type": "List", - "caption": "Energy Counters", + "caption": "Counters", "name": "EnergyVariables", "columns": [ { diff --git a/PDFReportLHG/locale.json b/PDFReportConsumption/locale.json similarity index 90% rename from PDFReportLHG/locale.json rename to PDFReportConsumption/locale.json index 2f3aba7..99f4473 100644 --- a/PDFReportLHG/locale.json +++ b/PDFReportConsumption/locale.json @@ -5,7 +5,7 @@ "Logo": "Logo", "E-Mail SMTP": "E-Mail SMTP", "Different receiver (variable with e-mail address)": "Abweichender Empfänger (Variable mit E-Mail-Adresse)", - "Energy Counters": "Energiezähler", + "Counters": "Zähler", "Name": "Name", "Counter": "Zähler", "Start": "Start", @@ -20,8 +20,7 @@ "Total Consumption": "Gesamtverbrauch", "m/d/Y": "d.m.Y", "m/d": "d.m.", - "m/Y": "m.Y", - ".": "," + "m/Y": "m.Y" } } } diff --git a/PDFReportLHG/module.json b/PDFReportConsumption/module.json similarity index 69% rename from PDFReportLHG/module.json rename to PDFReportConsumption/module.json index 175fd50..a9f998d 100644 --- a/PDFReportLHG/module.json +++ b/PDFReportConsumption/module.json @@ -1,14 +1,14 @@ { "id": "{9DD58AF0-495C-2620-BF4A-2F2EF96C8927}", - "name": "PDF Report LHG", + "name": "PDF Report Consumption", "type": 3, "vendor": "", "aliases": [ - "Report (PDF, LHG)" + "Report (PDF, Consumption)" ], "parentRequirements": [], "childRequirements": [], "implemented": [], "prefix": "RAC", - "url": "https://www.symcon.de/en/service/documentation/module-reference/symconreport/pdfreport-lhg/" + "url": "https://www.symcon.de/en/service/documentation/module-reference/symconreport/pdfreport-consumption/" } \ No newline at end of file diff --git a/PDFReportLHG/module.php b/PDFReportConsumption/module.php similarity index 94% rename from PDFReportLHG/module.php rename to PDFReportConsumption/module.php index 8cdd304..b11666f 100644 --- a/PDFReportLHG/module.php +++ b/PDFReportConsumption/module.php @@ -4,7 +4,7 @@ include_once __DIR__ . '/../libs/vendor/autoload.php'; -class PDFReportLHG extends IPSModule +class PDFReportConsumption extends IPSModule { private const COLORS = ['#9ACD32', '#4682B4', '#FF8C00', '#8B008B', '#20B2AA', '#DC143C', '#808000', '#1E90FF']; @@ -238,22 +238,22 @@ private function GenerateHTMLText(array $data): string { $dataText = ''; foreach ($data['Variables'] as $key => $variable) { - $name = $variable['Name']; - $consumption = $this->FormatNumber($variable['Consumption'], 2); + $name = htmlspecialchars($variable['Name']); + $consumption = GetValueFormattedEx($data['FormatVariableID'], $variable['Consumption']); $this->SendDebug('Consumption', $consumption, 0); $this->SendDebug('percentage', $variable['Percentage'], 0); $dataText .= << + $name : $consumption
EOT; } - $totalConsumption = $this->FormatNumber($data['Total'], 2); + $totalConsumption = GetValueFormattedEx($data['FormatVariableID'], $data['Total']); $textTotalConsumption = $this->Translate('Total Consumption'); return <<

$dataText

-

$textTotalConsumption: $totalConsumption kWh

+

$textTotalConsumption: $totalConsumption

EOT; } @@ -268,7 +268,6 @@ private function GenerateChart(array $data): string //Layout: the legend is placed below the chart with 3 entries per row $legendRows = intval(ceil(count($variables) / 3)); - $plotLeft = 80; $plotRight = $width - 20; $plotTop = 30; $plotBottom = $height - 50 - ($legendRows * 20); @@ -298,6 +297,9 @@ private function GenerateChart(array $data): string $decimals = $step < 1 ? intval(ceil(-log10($step))) : 0; $axisMax = ceil($maxValue / $step) * $step; $axisMin = floor($minValue / $step) * $step; + $formatVariableID = $data['FormatVariableID']; + //The length of the formatted values depends on the variable, so the plot starts after the longest label + $plotLeft = max(80, 16 + (8 * max(mb_strlen(GetValueFormattedEx($formatVariableID, $axisMin)), mb_strlen(GetValueFormattedEx($formatVariableID, $axisMax))))); $getY = function ($value) use ($axisMin, $axisMax, $plotTop, $plotBottom) { return $plotBottom - (($value - $axisMin) / ($axisMax - $axisMin)) * ($plotBottom - $plotTop); @@ -309,9 +311,8 @@ private function GenerateChart(array $data): string for ($value = $axisMin; $value <= $axisMax + ($step / 2); $value += $step) { $y = round($getY($value), 2); $svg .= ''; - $svg .= '' . $this->FormatNumber($value, $decimals) . ''; + $svg .= '' . htmlspecialchars(GetValueFormattedEx($formatVariableID, round($value, $decimals)), ENT_XML1) . ''; } - $svg .= 'kWh'; //Bars $slotWidth = ($plotRight - $plotLeft) / max(count($labels), 1); @@ -361,14 +362,6 @@ private function GenerateChart(array $data): string return $svg . ''; } - /** - * Formats the number with the decimal separator matching the language of the server - */ - private function FormatNumber(float $value, int $decimals): string - { - return number_format($value, $decimals, $this->Translate('.'), ''); - } - /** * Returns a step size of 1, 2 or 5 multiplied by a power of ten, which results in about 5 grid lines */ @@ -471,6 +464,8 @@ private function FetchData(array $variables): array } $values['Variables'] = $data; $values['Labels'] = $labels; + //All values of the report are formatted based on the first counter + $values['FormatVariableID'] = $variables[0]['CounterVariable']; return $values; } From 30dadda2c0e90feb91666575669e7952cd06a57a Mon Sep 17 00:00:00 2001 From: DrNiels Date: Mon, 16 Nov 2026 15:19:54 +0100 Subject: [PATCH 9/9] Updates based on Copilot feedback - Call parent::ApplyChanges - Register references - Return false when generation fails - Preserve consumption precision until formatting Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- PDFReportConsumption/module.php | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/PDFReportConsumption/module.php b/PDFReportConsumption/module.php index b11666f..28c8c2e 100644 --- a/PDFReportConsumption/module.php +++ b/PDFReportConsumption/module.php @@ -63,7 +63,7 @@ public function RequestAction($Ident, $Value): void public function ApplyChanges() { - + parent::ApplyChanges(); // The chart is not used for the PDF, but allows to view the counters in the visualization // Keep the datasets of existing counters (e.g. changed colors) and add new counters with the colors of the PDF $chartID = $this->GetIDForIdent('MediaChart'); @@ -98,7 +98,19 @@ public function ApplyChanges() foreach ($refs as $ref) { $this->UnregisterReference($ref); } - // Register reference of the counter and the reciever and the instance + foreach (json_decode($this->ReadPropertyString('EnergyVariables'), true) as $variable) { + if (IPS_VariableExists($variable['CounterVariable'])) { + $this->RegisterReference($variable['CounterVariable']); + } + } + $receiverID = $this->ReadPropertyInteger('DifferentReciever'); + if (IPS_VariableExists($receiverID)) { + $this->RegisterReference($receiverID); + } + $smtpID = $this->ReadPropertyInteger('SMTP'); + if (IPS_InstanceExists($smtpID)) { + $this->RegisterReference($smtpID); + } } public function SendReport(string $topic, string $body): bool @@ -127,6 +139,7 @@ public function SendReport(string $topic, string $body): bool } } $this->SendDebug('SendReport', 'Something is wrong', 0); + return false; } private function RegisterMediaDocument($Ident, $Name, $Extension, $Position = 0): void @@ -444,7 +457,7 @@ private function FetchData(array $variables): array } } - $consumption = round(array_sum($barValues), 2); + $consumption = array_sum($barValues); $totalConsumption += $consumption; $data[] = [ 'Name' => $name,