1
+ <#
2
+ . SYNOPSIS
3
+ Get power reading from smart power meter using the HAN / H1 / P1 port
4
+ . DESCRIPTION
5
+ Call from /var/prtg/scriptsxml/get-P1power.sh that just load the powershell script from bash. Uses PRTG 'SSH Script Advanced' sensor
6
+ . NOTES
7
+ 2022-12-04 Version 1 [email protected]
8
+ .NET new-Object System.IO.Ports.SerialPort does not get data, use command 'cu' instead.
9
+ . LINK
10
+ https://hanporten.se/
11
+ . EXAMPLE
12
+ cu -l /dev/ttyUSB0 -s 115200 -E% > pwr.log
13
+ #>
14
+ function get-P1data {
15
+ param (
16
+ $SerialPort = ' /dev/ttyUSB0' ,
17
+ $BaudRate = 115200 ,
18
+ $Parity = 0 , # 'None'
19
+ $StopBits = 1 , # 'One'
20
+ $DataBits = 8 ,
21
+ $ByteSize = 8 ,
22
+ $XonXoff = $false ,
23
+ $TimeOut = 120
24
+ )
25
+ $Templog = New-TemporaryFile | Select-Object - ExpandProperty FullName
26
+ $Starttime = get-date
27
+ do {
28
+
29
+ $CUCommand = [Scriptblock ]::Create((" cu -l {0} -s {1} -E% > {2}" -f $SerialPort , $BaudRate , $Templog ))
30
+
31
+ $JobGetData = Start-Job - ScriptBlock $CUCommand
32
+ while ($JobGetData.State -ne ' Completed' ) {
33
+ Start-Sleep - Milliseconds 100
34
+ Write-Verbose " Waiting to complete"
35
+ }
36
+ $JobGetData | Remove-Job
37
+ $ResultJob = Get-Content $Templog
38
+ $CurrentTime = Get-Date
39
+ if (($CurrentTime - $Starttime ).totalseconds -ge $TimeOut ) {
40
+ throw " Timout, could not get a correct reading in $TimeOut seconds"
41
+ }
42
+ } while ($ResultJob.length -le 10 ) # data is written from power meeter every 10 seconds, sometime the data returned is not complete.
43
+ Remove-Item - Path $Templog - Force
44
+
45
+ # Date,0-0:1.0.0
46
+ $Map =
47
+ " metric,register,value,suffix
48
+ Measure,1-0:1.8.0
49
+ Effekt,1-0:1.7.0
50
+ L1,1-0:21.7.0
51
+ L2,1-0:41.7.0
52
+ L3,1-0:61.7.0
53
+ L1A,1-0:31.7.0
54
+ L2A,1-0:51.7.0
55
+ L3A,1-0:71.7.0
56
+ " | ConvertFrom-Csv
57
+
58
+
59
+
60
+ foreach ($Register in $Map ) {
61
+ $Match = $ResultJob | Where-Object {$PSitem -match $Register.register } | Select-Object - Last 1
62
+ if ($Match ) {
63
+ $Value , $Suffix = $Match.Replace ($Register.register , ' ' ).Split(' *' ).trim(' (' , ' )' )
64
+ $Register.value = $Value
65
+ $Register.suffix = $Suffix
66
+ }
67
+
68
+ }
69
+ Write-Output $Map
70
+ }
71
+
72
+ # Main code
73
+ try {
74
+ $Measurements = get-P1data
75
+ $Output = [PSCustomObject ]@ {
76
+ prtg = [PSCustomObject ]@ {
77
+ result =
78
+ $Measurements | ForEach-Object {
79
+ [PSCustomObject ]@ {
80
+ Channel = $PSitem.metric
81
+ Float = 1
82
+ Value = $PSitem.value
83
+ CustomUnit = $PSitem.suffix
84
+
85
+ }
86
+ }
87
+ }
88
+ }
89
+
90
+ } Catch {
91
+ $error
92
+ $Output = [PSCustomObject ]@ {
93
+ prtg = [PSCustomObject ]@ {
94
+ error = 1
95
+ text = $error [0 ].Exception.Message
96
+ }
97
+ }
98
+ }
99
+ Write-Output ($Output | ConvertTo-Json - depth 5 | ForEach-Object { [System.Text.RegularExpressions.Regex ]::Unescape($PSItem ) })
0 commit comments