forked from SkyRaVeR/FHEM_Powerrouter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path98_powerrouter.pm
374 lines (290 loc) · 13.4 KB
/
98_powerrouter.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
##############################################
# $Id: 98_powerrouter.pm by SkyRaVeR, rewrote by fbuescher $
#
# apt-get install libcurl4-openssl-dev cpanminus curl
# cpanm install WWW::Curl::Easy
# cpanm install JSON
# adjust the logging path in $POWERROUTER_TEMPFILE_FOLDER and ensure the directory exists! in this case it points to <yourfheminstallation/log/powerrouter>
#
# ToDo:
# - add current values
# - add detailed battery info
#
# Changelog:
# 14.09.2020 - changed curl part (basic_auth), changed parsing of battery, added parameter delay, added reading timedrift_minutes
# 01.11.2016 - added first version of battery state
# 16.06.2016 - fixed brainlag bug in sprintf
# 15.06.2016 - reworked lots of original code. increased readability and more error are caught; prepared battery stats
# 09.06.2016 - fixed missing variable and crash; added configure section for temporary json response from website
# 16.02.2016 - fixed an issue which lead to crash fhem due to missing exception handling...
# 15.02.2016 - adopted to new json response and fixed an exception which occured when no connectivity to mypowerrouter.com could be established
#
# Last change: 2020-09-14 16:14 UTC+1
# version 1.1.2
##############################################
package main;
use strict;
use warnings;
use WWW::Curl::Easy;
use Date::Parse;
use Time::Piece;
use Time::Seconds;
use DateTime qw( );
use JSON qw( decode_json );
##############################################
#
# configure section
#
##############################################
my $POWERROUTER_TEMPFILE_FOLDER = "log/powerrouter/";
# DO NOT TOUCH ANYTHING BELOW UNLESS YOU KNOW WHAT YOU DO !
my $POWERROUTER_URL_PRODUCTION = "https://www.mypowerrouter.com/aspects/history/production/1hour?scope=hour&aspect[perspective]=total&power_router[0]=%s&from_date=%s";
my $POWERROUTER_URL_CONSUMPTION = "https://www.mypowerrouter.com/aspects/history/consumption/1hour?scope=hour&aspect[perspective]=total&power_router[0]=%s&from_date=%s";
my $POWERROUTER_URL_BATTERY = "https://www.mypowerrouter.com/aspects/history/battery_state/60minute?scope=hour&power_router[0]=%s&from_date=%s";
# unit is [min] - if > 0 it will update battery data every x min
my $POWERROUTER_BATTERY_UPDATE_INTERVAL = 0;
sub ##########################################
powerrouter_Initialize($)
{
my ($hash) = @_;
$hash->{SetFn} = "powerrouter_Set";
$hash->{GetFn} = "powerrouter_Get";
$hash->{DefFn} = "powerrouter_Define";
$hash->{AttrList} = "setList login pass routerid battery_update_interval delay ". $readingFnAttributes;
}
sub ##########################################
powerrouter_Define($$)
{
my ($hash, $def) = @_;
my @a = split("[ \t][ \t]*", $def);
return "Wrong syntax: use define <name> powerrouter" if(int(@a) != 2);
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
# minutes of hour from 0 to 59
my $firstschedule = (60 - $min);
$firstschedule = ($firstschedule * 60) + 60 * AttrVal($hash->{NAME}, "delay", 0); # try to get data every "full hour" but since server time might slightly differ add x minutes
# start timer since we need to poll data from website...
Log3 $hash, 4, "powerrouter:first interval for powerrouter_GetUpdate:". scalar localtime(gettimeofday()+$firstschedule);
InternalTimer(gettimeofday()+$firstschedule, "powerrouter_GetUpdate", $hash, 0);
# until we perform any checks set ourself to active...
readingsSingleUpdate($hash,"STATE","active",1);
# dirty workaround
InternalTimer(gettimeofday()+1, "powerrouter_initphase2", $hash, 0);
$hash->{VERSION} = "1.1.2";
return undef;
}
###################################
sub
powerrouter_initphase2($) {
my ($hash) = @_;
# remove timer since it was just needed to leave the define and get called to set up our notification filter...
RemoveInternalTimer("powerrouter_initphase2");
$POWERROUTER_BATTERY_UPDATE_INTERVAL = AttrVal($hash->{NAME}, "battery_update_interval", 0);
if ($POWERROUTER_BATTERY_UPDATE_INTERVAL > 0) {
Log3 $hash, 4, "powerrouter:next interval for powerrouter_GetBatteryUpdate:" . scalar localtime(gettimeofday()+(60*$POWERROUTER_BATTERY_UPDATE_INTERVAL));
InternalTimer(gettimeofday()+(60*$POWERROUTER_BATTERY_UPDATE_INTERVAL), "powerrouter_GetBatteryUpdate", $hash, 1);
}
}
###################################
sub
powerrouter_Set($@)
{
return undef;
}
sub ##########################################
powerrouter_Get($@)
{
my ( $hash, @a ) = @_;
return "\"get X\" needs at least one argument" if ( @a < 2 );
return "no get value specified" if(int(@a) < 1);
my $setList = AttrVal($hash->{name}, "setList", " ");
return "Unknown argument ?, choose one of $setList" if($a[0] eq "?");
eval { powerrouter_GetPowerConsumption($hash); }; warn $@ if $@;
eval { powerrouter_GetPowerProduction($hash); }; warn $@ if $@;
# only retrieve data if a battery is present...
if ($POWERROUTER_BATTERY_UPDATE_INTERVAL > 0) {
eval { powerrouter_GetBatteyChargeState($hash); }; warn $@ if $@;
}
return $hash->{NAME};
}
sub ##########################################
powerrouter_GetUpdate($)
{
my ($hash) = @_;
my $name = $hash->{NAME};
eval { powerrouter_GetPowerConsumption($hash); }; warn $@ if $@;
eval { powerrouter_GetPowerProduction($hash); }; warn $@ if $@;
if ($POWERROUTER_BATTERY_UPDATE_INTERVAL > 0) {
eval { powerrouter_GetBatteyChargeState($hash); }; warn $@ if $@;
}
# re-schedule stuff for next reading
# next interval for powerrouter_GetUpdate:Wed Sep 16 11:01:00 2020
my $nextschedule=DateTime->now( time_zone => "local" )->truncate( to => 'hour' )->add(hours => 1)->add(minutes => 5)->strftime("%s");
readingsBeginUpdate($hash);
readingsBulkUpdate($hash, "_nextUpdate", scalar localtime($nextschedule) );
readingsEndUpdate($hash, 1);
Log3 $hash, 4, "powerrouter: next interval for powerrouter_GetUpdate:" . scalar localtime($nextschedule);
InternalTimer($nextschedule, "powerrouter_GetUpdate", $hash, 1);
# Log3 $hash, 4, "powerrouter: next interval for powerrouter_GetUpdate:" . scalar localtime(gettimeofday()+(60*60));
# InternalTimer(gettimeofday()+(60*60), "powerrouter_GetUpdate", $hash, 1);
}
sub ##########################################
powerrouter_GetBatteryUpdate($)
{
my ($hash) = @_;
my $name = $hash->{NAME};
if ($POWERROUTER_BATTERY_UPDATE_INTERVAL > 0) {
eval { powerrouter_GetBatteyChargeState($hash); }; warn $@ if $@;
readingsBeginUpdate($hash);
readingsBulkUpdate($hash, "_nextBatteryUpdate", scalar localtime(gettimeofday()+(60*$POWERROUTER_BATTERY_UPDATE_INTERVAL)) );
readingsEndUpdate($hash, 1);
Log3 $hash, 4, "powerrouter:next interval for powerrouter_GetBatteryUpdate:" . scalar localtime(gettimeofday()+(60*$POWERROUTER_BATTERY_UPDATE_INTERVAL));
# re-schedule stuff for next reading
InternalTimer(gettimeofday()+(60*$POWERROUTER_BATTERY_UPDATE_INTERVAL), "powerrouter_GetBatteryUpdate", $hash, 1);
}
}
sub ##########################################
powerrouter_GetPowerConsumption($)
{
my ($hash) = @_;
# time
my $now = localtime(time - 3600 );
my $nowstr = $now->strftime('%Y-%m-%dT%H:00:00Z');
# fill url with routerid and timestamp
my $url = sprintf("$POWERROUTER_URL_CONSUMPTION",AttrVal($hash->{NAME}, "routerid", ''),$nowstr);
# retrieve data from site
Log3 $hash, 3, "powerrouter_GetPowerConsumption::$url";
my $websiteresponse = powerrouter_retrieveData($hash,$url);
if (!defined $websiteresponse) {
return undef;
}
# parse response and update readings
powerrouter_parsejsonresponse($hash,$websiteresponse);
}
sub ##########################################
powerrouter_GetPowerProduction($)
{
my ($hash) = @_;
# time
my $now = localtime(time - 3600 );
my $nowstr = $now->strftime('%Y-%m-%dT%H:00:00Z');
# fill url with routerid and timestamp
my $url = sprintf("$POWERROUTER_URL_PRODUCTION",AttrVal($hash->{NAME}, "routerid", ''),$nowstr);
# retrieve data from site
Log3 $hash, 3, "powerrouter_GetPowerProduction::$url";
my $websiteresponse = powerrouter_retrieveData($hash,$url);
if (!defined $websiteresponse) {
return undef;
}
# parse response and update readings
powerrouter_parsejsonresponse($hash,$websiteresponse);
}
sub ##########################################
powerrouter_GetBatteyChargeState($)
{
my ($hash) = @_;
# time
my $now = localtime(time);
my $nowstr = $now->strftime('%Y-%m-%dT%H:00:00Z');
# fill url with routerid and timestamp
my $url = sprintf("$POWERROUTER_URL_BATTERY",AttrVal($hash->{NAME}, "routerid", ''),$nowstr);
# retrieve data from site
Log3 $hash, 3, "powerrouter_GetBatteyChargeState::$url";
my $websiteresponse = powerrouter_retrieveData($hash,$url);
if (!defined $websiteresponse) {
return undef;
}
# parse response and update readings
powerrouter_parsejsonresponse($hash,$websiteresponse);
}
sub powerrouter_retrieveData($$) {
my ($hash,$url) = @_;
my $curl = WWW::Curl::Easy->new;
my $response_body = '';
my $retcode;
$curl->setopt(CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/39.0.2171.65 Chrome/39.0.2171.65 Safari/537.36" );
$curl->setopt(CURLOPT_FOLLOWLOCATION, 1 );
$curl->setopt(CURLOPT_URL,$url);
$curl->setopt(CURLOPT_HTTPAUTH,CURLAUTH_ANY);
$curl->setopt(CURLOPT_USERPWD,AttrVal($hash->{NAME}, "login", '') . ":" . AttrVal($hash->{NAME}, "pass",''));
$curl->setopt(CURLOPT_WRITEDATA,\$response_body);
# Starts the actual request
$retcode = $curl->perform;
# Looking at the results...
if ($retcode == 0) {
} else {
# Error code, type of error, error message
print("An error happened: $retcode ".$curl->strerror($retcode)." ".$curl->errbuf."\n");
readingsSingleUpdate($hash,"STATE","axs denied",1);
Log3 $hash, 3, "powerrouter_retrieveData:: HTTP Basic: Access denied. Wrong credentials?";
$response_body = "HTTP Basic: Access denied.";
}
return $response_body;
}
sub powerrouter_parsejsonresponse($$) {
my ($hash, $json) = @_;
$json =~ s/^\s+//; #remove leading spaces
$json =~ s/\s+$//; #remove trailing spaces
if ($json eq 'HTTP Basic: Access denied.') {
$hash->{state} = "axs denied";
return undef;
}
# decode response...
my $decoded = decode_json($json);
# ready set go...
readingsBeginUpdate($hash);
my $item = $decoded->{'power_routers'}{AttrVal($hash->{NAME}, "routerid", '')}{'history'};
my $power_router_local_time = $decoded->{'power_routers'}{AttrVal($hash->{NAME}, "routerid", '')}{'power_router_local_time'};
# timeobjects in json are localtime, but suffixed with Z(ulu), this is wrong.
$power_router_local_time =~ s/Z$//;
$power_router_local_time = str2time("$power_router_local_time");
my $now = time;
# check for contents...
# $val contains the string like direct_use etc
foreach my $val (keys %{ $item } ) {
Log3 $hash, 5, "powerrouter_parsejsonresponse::iterate over keys, val=$val";
my @list_response;
eval { @list_response = @{$item->{$val}{'data'} }; };
# eval failed? skip to next val
next if ($@);
my $result="";
# loop over all samples to get the latest (see battery)
for (my $index=0; $index <= $#list_response; $index++) {
next unless defined $list_response[$index][1];
Log3 $hash, 5, "powerrouter_parsejsonresponse:: storing index $index with value " . $list_response[$index][1];
$result=$list_response[$index][1];
}
# update data in fhem...
Log3 $hash, 3, "powerrouter_parsejsonresponse::result for $val is $result";
readingsBulkUpdate($hash, $val, $result );
}
readingsBulkUpdate($hash, "timedrift_minutes", int(($now - $power_router_local_time)/60));
readingsBulkUpdate($hash, "STATE", "active");
readingsEndUpdate($hash, 1);
}
1;
=pod
=begin html
<a name="powerrouter"></a>
<h3>powerrouter</h3>
<ul>
Provides data from www.mypowerrouter.com in order to spice up some statistics :)
<br><br>
<a name="powerrouterdefine"></a>
<b>Define</b>
<ul>
<code>define <name> powerrouter</code>
<br><br>
Example:
<ul>
<code>define mypowerrouter powerrouter</code><br>
<code>attr mypowerrouter login <username></code><br>
<code>attr mypowerrouter pass <password></code><br>
<code>attr mypowerrouter routerid <id_of_router></code><br>
<code>attr mypowerrouter battery_update_interval <ival_in_min></code><br>
<code>attr mypowerrouter delay <delay_in_min></code><br>
</ul>
</ul>
<br>
</ul>
=end html
=cut