blib/lib/AHA.pm untested

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