blib/lib/AHA.pm untested

filter: Statementstmt 0.0% 0 / 123 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 12 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 214 CC 20 SCAR 26.7
CC
20
Cov
0%
new
30.0
_execute_cmd
30.0
_sid
30.0
CRAP 14.5
1 =head1 NAME
2  
3 AHA - Simple access to the AHA interface for AVM based home automation
4  
5 =head1 SYNOPSIS
6  
7 my $aha = AHA->new( { host => "fritz.box", password => "s!cr!t" } );
8  
9 # Get all switches as array ref of AHA::Switch objects
10 my $switches = $aha->list();
11  
12 # For all switches found
13 for my $switch (@$switches) {
14 say "Name: ",$switch->name();
15 say "State: ",$switch->is_on();
16 say "Present: ",$switch->is_present();
17 say "Energy: ",$switch->energy();
18 say "Power: ",$switch->power();
19 say "Temp.°C: ",$switch->temperature() / 10;
20  
21 # If switch is on, switch if off and vice versa
22 $switch->is_on() ? $switch->off() : $switch->on();
23 }
24  
25 # Access switch directly via name as configured
26 $aha->energy("Lava lamp");
27  
28 # ... or by AIN
29 $aha->energy("087610077197");
30  
31 # Logout
32 $aha->logout();
33  
34 =head1 DESCRIPTION
35  
36 This module allows programatic access to AVM's Home Automation (AHA) system as
37 it is specified in L<AVM AHA HTTP Protocol
38 specification|http://www.avm.de/de/Extern/files/session_id/AHA-HTTP-Interface.pdf>.
39  
40 Please note that this module is not connected to AVM in any way. It's a hobby
41 project, without any warranty and no guaranteed support.
42  
43 Typical it is used to manage and monitor L<AHA::Switch>es. The following
44 operations are supported:
45  
46 =over 4
47  
48 =item *
49  
50 Switching on and off a certain actor (switch)
51  
52 =item *
53  
54 Get the current state of an actor
55  
56 =item *
57  
58 Get the current power consumption and consumed energy of an actor (if
59 it is a plug like the Dect!200)
60  
61 =back
62  
63 =head1 METHODS
64  
65 Many methods of this class take an 8-digit AIN (actor id) or a symbolic name as
66 argument. This symbolic name can be configured in the admin UI of the Fritz
67 Box.
68  
69 If the argument (name or AIN) is not known, an error is raised (die). The same
70 is true, if authorization fails.
71  
72 =over
73  
74 =cut
75  
76 package AHA;
77  
78 use strict;
79 use LWP::UserAgent;
80 use AHA::Switch;
81 use Encode;
82 use Digest::MD5;
83 use Data::Dumper;
84 use vars qw($VERSION);
85  
86 $VERSION = "0.6";
87  
88 # Set to one if some debugging should be printed
89 my $DEBUG = 0;
90  
91 =item $aha = new AHA({host => "fritz.box", password => "s!cr!t", user => "admin"})
92  
93 =item $aha = new AHA("fritz.box","s!cr!t","admin")
94  
95 Create a new AHA object for accessing a Fritz Box via the HTTP interface. The
96 parameters can be given as a hashref (for named parameters) or in a simple form
97 with host, password and user (optional) as unnamed arguments.
98  
99 The named arguments which can be used:
100  
101 =over
102  
103 =item host
104  
105 Name or IP of the Fritz box to access
106  
107 =item port
108  
109 Port to connect to. It's 80 by default
110  
111 =item password
112  
113 Password for connecting to the Fritz Box
114  
115 =item user
116  
117 User role for login. Only required if a role based login is configured for the
118 Fritz box
119  
120 =back
121  
122 If used without an hashref as argument, the first argument must be the host,
123 the second the password and the third optionally the user.
124  
125 =cut
126  
127 sub new {
128 my $class = shift;
129 my $self = {};
130 my $arg1 = shift;
131 if (ref($arg1) ne "HASH") {
132 $self->{host} = $arg1;
133 $self->{password} = shift;
134 $self->{user} = shift;
135 } else {
136 map { $self->{$_} = $arg1->{$_} } qw(host password user port);
137 }
138 die "No host given" unless $self->{host};
139 die "No password given" unless $self->{password};
140  
141 my $base = $self->{port} ? $self->{host} . ":" . $self->{port} : $self->{host};
142  
143 $self->{ua} = LWP::UserAgent->new;
144 $self->{login_url} = "http://" . $base . "/login_sid.lua";
145 $self->{ws_url} = "http://" . $base . "/webservices/homeautoswitch.lua";
146 $self->{ain_map} = {};
147 return bless $self,$class;
148 }
149  
150 =item $switches = $aha->list()
151  
152 List all switches know to AHA. An arrayref with L<AHA::Switch> objects is
153 returned, one for each device. When no switch is registered an empty arrayref
154 is returned.
155  
156 =cut
157  
158 sub list {
159 my $self = shift;
160 return [ map { new AHA::Switch($self,$_) } (split /\s*,\s*/,$self->_execute_cmd("getswitchlist")) ];
161 }
162  
163 =item $aha->is_on($ain)
164  
165 Check, whether the switch C<$ain> is in state "on", in which case this methods
166 returns 1. If it is "off", 0 is returned. If the switch is not connected,
167 C<undef> is returned.
168  
169 =cut
170  
171 sub is_on {
172 my $self = shift;
173 return &_inval_check($self->_execute_cmd("getswitchstate",$self->_ain(shift)));
174 }
175  
176 =item $aha->on($ain)
177  
178 Switch on the switch with the name or AIN C<$ain>.
179  
180 =cut
181  
182 sub on {
183 my $self = shift;
184 my $ain = $self->_ain(shift);
185 return $self->_execute_cmd("setswitchon",$ain);
186 }
187  
188 =item $aha->off($ain)
189  
190 Switch off the switch with the name or AIN C<$ain>.
191  
192 =cut
193  
194 sub off {
195 my $self = shift;
196 return $self->_execute_cmd("setswitchoff",$self->_ain(shift));
197 }
198  
199 =item $is_present = $aha->is_present($ain)
200  
201 Check whether the switch C<$ain> is present. This means, whether it is
202 registered at the Fritz Box at all in which case 1 is returned. If the switch
203 is not connected, 0 is returned.
204  
205 =cut
206  
207 sub is_present {
208 my $self = shift;
209 return $self->_execute_cmd("getswitchpresent",$self->_ain(shift));
210 }
211  
212 =item $energy = $aha->energy($ain)
213  
214 Get the amount of energy which has been consumed by the switch C<$ain> since
215 ever or since the reset of the energy statistics via the admin UI. The amount
216 is measured in Wh.
217  
218 =cut
219  
220 sub energy {
221 my $self = shift;
222 return $self->_execute_cmd("getswitchenergy",$self->_ain(shift));
223 }
224  
225 =item $power = $aha->power($ain)
226  
227 Get the current power consumption of the switch C<$ain> in mW.
228 If the switch is not connected, C<undef> is returned.
229  
230 =cut
231  
232 sub power {
233 my $self = shift;
234 return &_inval_check($self->_execute_cmd("getswitchpower",$self->_ain(shift)));
235 }
236  
237 =item $temperature = $aha->temperature($ain)
238  
239 Get the current temperature of the switch C<$ain> in 0,1 °C.
240 If the switch is not connected, C<undef> is returned.
241  
242 =cut
243  
244 sub temperature {
245 my $self = shift;
246 return &_inval_check($self->_execute_cmd("gettemperature",$self->_ain(shift)));
247 }
248  
249 =item $name = $aha->name($ain)
250  
251 Get the symbolic name for the AIN given. In this case C<$ain> must be an real
252 AIN.
253  
254 =cut
255  
256 sub name {
257 my $self = shift;
258 my $ain = shift || die "No AIN given for which to fetch the name";
259 return $self->_execute_cmd("getswitchname",$ain);
260 }
261  
262 =item $ain = $aha->ain_by_name($name)
263  
264 This is the inverse method to C<name()>. It takes a symbolic name C<$name> as
265 argument and returns the AIN. If no such name is registered, an error is
266 raised.
267  
268 =cut
269  
270 sub ain_by_name {
271 my $self = shift;
272 my $name = shift;
273 my $map = $self->{ain_map};
274 return $map->{$name} if $map->{$name};
275 $self->_init_ain_map();
276 my $ain = $self->{ain_map}->{$name};
277 die "No AIN for '$name' found" unless $ain;
278 return $ain;
279 }
280  
281 =item $aha->logout()
282  
283 Logout from the connected fritz.box in order to free up any resources. You
284 can still use any other method on this object, in which case it is
285 logs in again (which eats up some performance, of course)
286  
287 =cut
288  
289 sub logout {
290 my $self = shift;
291 return unless $self->{sid};
292  
293 # Send a post request as defined in
294 # http://www.avm.de/de/Extern/files/session_id/AVM_Technical_Note_-_Session_ID.pdf
295 my $req = HTTP::Request->new(POST => $self->{login_url});
296 $req->content_type("application/x-www-form-urlencoded");
297 my $login = "sid=".$self->{sid}."&security:command/logout=fcn";
298 $req->content($login);
299 my $resp = $self->{ua}->request($req);
300 die "Cannot logout SID ",$self->{sid},": ",$resp->status_line unless $resp->is_success;
301 print "--- Logout ",$self->{sid} if $DEBUG;
302 delete $self->{sid};
303 }
304  
305 =back
306  
307  
308  
309 =cut
310  
311 # ======================================================================
312 # Private methods
313  
314 # Decide whether an AIN or a name is given
315 sub _ain {
316 my $self = shift;
317 my $ain = shift || die "No AIN or name given";
318 return $ain =~ /^\d{12}$/ ? $ain : $self->ain_by_name($ain);
319 }
320  
321 # Execute a command as defined in
322 # http://www.avm.de/de/Extern/files/session_id/AHA-HTTP-Interface.pdf
323 sub _execute_cmd {
324 my $self = shift;
325 my $cmd = shift || die "No command given";
326 my $ain = shift;
327 my $url = $self->{ws_url} . "?sid=" . $self->_sid() . "&switchcmd=" . $cmd;
328 $url .= "&ain=" . $ain if $ain;
329 my $resp = $self->{ua}->get($url);
330 print ">>> $url\n" if $DEBUG;
331 die "Cannot execute ",$cmd,": ",$resp->status_line unless $resp->is_success;
332 my $c = $resp->content;
333 chomp $c;
334 print "<<< $c\n" if $DEBUG;
335 return $c;
336 }
337  
338 # Return the cached SID or perform the login as described in
339 # http://www.avm.de/de/Extern/files/session_id/AVM_Technical_Note_-_Session_ID.pdf
340 sub _sid {
341 my $self = shift;
342
343 return $self->{sid} if $self->{sid};
344
345 # Get the challenge
346 my $resp = $self->{ua}->get($self->{login_url});
347 my $content = $resp->content();
348  
349 my $challenge = ($content =~ /<Challenge>(.*?)<\/Challenge>/ && $1);
350 my $input = $challenge . '-' . $self->{password};
351 Encode::from_to($input, 'ascii', 'utf16le');
352 my $challengeresponse = $challenge . '-' . lc(Digest::MD5::md5_hex($input));
353  
354 # Send the challenge back with encoded password
355 my $req = HTTP::Request->new(POST => $self->{login_url});
356 $req->content_type("application/x-www-form-urlencoded");
357 my $login = "response=$challengeresponse";
358 if ($self->{user}) {
359 $login .= "&username=" . $self->{user};
360 }
361 $req->content($login);
362 $resp = $self->{ua}->request($req);
363 if (! $resp->is_success()) {
364 die "Cannot login to ", $self->{host}, ": ",$resp->status_line();
365 }
366 $content = $resp->content();
367 $self->{sid} = ($content =~ /<SID>(.*?)<\/SID>/ && $1);
368 print "-- Login, received SID ",$self->{sid} if $DEBUG;
369 return $self->{sid};
370 }
371  
372 # Initialize the reverse name -> AIN map
373 sub _init_ain_map {
374 my $self = shift;
375 my $devs = $self->list();
376 $self->{ain_map} = {};
377 for my $dev (@$devs) {
378 $self->{ain_map}->{$self->name($dev->ain())} = $dev->ain();
379 }
380 }
381  
382 # Convert "inval" to undef
383 sub _inval_check {
384 my $ret = shift;
385 return $ret eq "inval" ? undef : $ret;
386 }
387  
388 =head1 LICENSE
389  
390 AHA is free software: you can redistribute it and/or modify
391 it under the terms of the GNU General Public License as published by
392 the Free Software Foundation, either version 2 of the License, or
393 (at your option) any later version.
394  
395 AHA is distributed in the hope that it will be useful,
396 but WITHOUT ANY WARRANTY; without even the implied warranty of
397 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
398 GNU General Public License for more details.
399  
400 You should have received a copy of the GNU General Public License
401 along with AHA. If not, see <http://www.gnu.org/licenses/>.
402  
403 =head1 AUTHOR
404  
405 roland@cpan.org
406  
407 =cut
408  
409 1;