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/PDFReportConsumption/form.json b/PDFReportConsumption/form.json new file mode 100644 index 0000000..13b7985 --- /dev/null +++ b/PDFReportConsumption/form.json @@ -0,0 +1,68 @@ +{ + "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": "SelectModule", + "name": "SMTP", + "caption": "E-Mail SMTP", + "moduleID": "{375EAF21-35EF-4BC4-83B3-C780FD8BD88A}" + }, + { + "type": "SelectVariable", + "name": "DifferentReciever", + "caption": "Different receiver (variable with e-mail address)", + "validVariableTypes": [ + 3 + ] + } + ] + }, + { + "type": "List", + "caption": "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/PDFReportConsumption/locale.json b/PDFReportConsumption/locale.json new file mode 100644 index 0000000..99f4473 --- /dev/null +++ b/PDFReportConsumption/locale.json @@ -0,0 +1,26 @@ +{ + "translations": { + "de": { + "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)", + "Counters": "Zä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" + } + } +} diff --git a/PDFReportConsumption/module.json b/PDFReportConsumption/module.json new file mode 100644 index 0000000..a9f998d --- /dev/null +++ b/PDFReportConsumption/module.json @@ -0,0 +1,14 @@ +{ + "id": "{9DD58AF0-495C-2620-BF4A-2F2EF96C8927}", + "name": "PDF Report Consumption", + "type": 3, + "vendor": "", + "aliases": [ + "Report (PDF, Consumption)" + ], + "parentRequirements": [], + "childRequirements": [], + "implemented": [], + "prefix": "RAC", + "url": "https://www.symcon.de/en/service/documentation/module-reference/symconreport/pdfreport-consumption/" +} \ No newline at end of file diff --git a/PDFReportConsumption/module.php b/PDFReportConsumption/module.php new file mode 100644 index 0000000..28c8c2e --- /dev/null +++ b/PDFReportConsumption/module.php @@ -0,0 +1,485 @@ +RegisterPropertyString('LogoData', ''); + $this->RegisterPropertyString('EnergyVariables', '[]'); + $this->RegisterPropertyInteger('SMTP', 0); + $this->RegisterPropertyInteger('DifferentReciever', 0); + + //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', $this->Translate('Generate'), "RegisterMedia(5, 'ReportPDF', $this->Translate('Report (PDF)'), 'pdf', 4); + $this->RegisterMedia(4, 'MediaChart', $this->Translate('Chart'), 'chart', 5); + + } + + public function GenerateReport(): 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() + { + 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'); + $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', + ]; + } + } + IPS_SetMediaContent($chartID, base64_encode(json_encode(['datasets' => $datasets]))); + + $refs = $this->GetReferenceList(); + foreach ($refs as $ref) { + $this->UnregisterReference($ref); + } + 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 + { + $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); + return false; + } + + 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 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($data), true, false, true, false, ''); + + //Chart + $svg = $this->GenerateChart($data); + $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 = mb_strtoupper($this->Translate('Consumption')); + //Get Times + [$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 << + + +


+

$title

+

$timestamps

+ +
$logo + + +
+
+ EOT; + } + + private function GenerateHTMLText(array $data): string + { + $dataText = ''; + foreach ($data['Variables'] as $key => $variable) { + $name = htmlspecialchars($variable['Name']); + $consumption = GetValueFormattedEx($data['FormatVariableID'], $variable['Consumption']); + $this->SendDebug('Consumption', $consumption, 0); + $this->SendDebug('percentage', $variable['Percentage'], 0); + + $dataText .= << + EOT; + } + $totalConsumption = GetValueFormattedEx($data['FormatVariableID'], $data['Total']); + $textTotalConsumption = $this->Translate('Total Consumption'); + + return << +

$dataText

+

$textTotalConsumption: $totalConsumption

+ EOT; + } + + 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)); + $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; + } + + //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; + $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); + }; + + $svg = ''; + + //Grid and y axis labels + for ($value = $axisMin; $value <= $axisMax + ($step / 2); $value += $step) { + $y = round($getY($value), 2); + $svg .= ''; + $svg .= '' . htmlspecialchars(GetValueFormattedEx($formatVariableID, round($value, $decimals)), ENT_XML1) . ''; + } + + //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++; + } + + //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) . ''; + } + + return $svg . ''; + } + + /** + * 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 10 * $magnitude; + } + + /** + * 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 + { + $startTime = $this->GetValue('Start'); + $endTime = $this->GetValue('End'); + if ($startTime > $endTime) { + [$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; + + //Get the consumption + foreach ($variables as $variable) { + $name = $variable['Name'] == '' ? IPS_GetName($variable['CounterVariable']) : $variable['Name']; + $variable = $variable['CounterVariable']; + //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); + + $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 = array_sum($barValues); + $totalConsumption += $consumption; + $data[] = [ + 'Name' => $name, + 'Consumption' => $consumption, + 'Percentage' => 0, + 'Values' => $barValues + ]; + } + + $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; + $values['Labels'] = $labels; + //All values of the report are formatted based on the first counter + $values['FormatVariableID'] = $variables[0]['CounterVariable']; + + return $values; + } +} 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",