| 1 | #!/usr/bin/env perl | ||
| 2 | |||
| 3 | # $Id: Discover.pm,v 1.3 2013-12-31 03:29:22 ericblue76 Exp $ | ||
| 4 | # | ||
| 5 | # Author: Eric Blue - ericblue76@gmail.com | ||
| 6 | # Project: Belkin Wemo API | ||
| 7 | # Url: http://eric-blue.com/belkin-wemo-api/ | ||
| 8 | # | ||
| 9 | |||
| 10 | # ABSTRACT: Uses UPNP to control Belkin Wemo Switches | ||
| 11 | |||
| 12 | package WebService::Belkin::WeMo::Discover; | ||
| 13 | { | ||
| 14 | $WebService::Belkin::WeMo::Discover::VERSION = '1.0'; | ||
| 15 | } | ||
| 16 | |||
| 17 | use Storable; | ||
| 18 | use Data::Dumper; | ||
| 19 | use Net::UPnP::ControlPoint; | ||
| 20 | use Carp; | ||
| 21 | |||
| 22 | use strict; | ||
| 23 | |||
| 24 | sub new { | ||
| 25 | |||
| 26 | my $class = shift; | ||
| 27 | my $self = {}; | ||
| 28 | my %params = @_; | ||
| 29 | |||
| 30 | bless $self, $class; | ||
| 31 | |||
| 32 | $self->{_discovered} = {}; | ||
| 33 | |||
| 34 | $self; | ||
| 35 | |||
| 36 | } | ||
| 37 | |||
| 38 | sub search { | ||
| 39 | |||
| 40 | my $self = shift; | ||
| 41 | |||
| 42 | my $upnp = Net::UPnP::ControlPoint->new(); | ||
| 43 | my @devices = $upnp->search( st => 'upnp:rootdevice', mx => 3 ); | ||
| 44 | |||
| 45 | my $discovered; | ||
| 46 | |||
| 47 | foreach my $device (@devices) { | ||
| 48 | my $device_type = $device->getdevicetype(); | ||
| 49 | |||
| 50 | if ( $device_type =~ /urn:Belkin:device/ ) { | ||
| 51 | |||
| 52 | my $type; | ||
| 53 | if ($device_type =~/controllee/) { | ||
| 54 | $type = "switch"; | ||
| 55 | } elsif ($device_type =~/sensor/) { | ||
| 56 | $type = "sensor"; | ||
| 57 | } else { | ||
| 58 | $type = "unknown"; | ||
| 59 | } | ||
| 60 | |||
| 61 | my ( $ip, $port ) = | ||
| 62 | $device->getssdp() =~ /LOCATION: http:\/\/(.*):(.*)\/setup.xml/; | ||
| 63 | $discovered->{$ip} = { | ||
| 64 | ip => $ip, | ||
| 65 | port => $port, | ||
| 66 | type => $type, | ||
| 67 | name => $device->getfriendlyname(), | ||
| 68 | device => $device | ||
| 69 | }; | ||
| 70 | |||
| 71 | } | ||
| 72 | } | ||
| 73 | $self->{_discovered} = $discovered; | ||
| 74 | |||
| 75 | return $discovered; | ||
| 76 | |||
| 77 | } | ||
| 78 | |||
| 79 | sub save { | ||
| 80 | |||
| 81 | my $self = shift; | ||
| 82 | my ($filename) = @_; | ||
| 83 | |||
| 84 | store( $self->{_discovered}, $filename ); | ||
| 85 | |||
| 86 | } | ||
| 87 | |||
| 88 | sub load { | ||
| 89 | |||
| 90 | my $self = shift; | ||
| 91 | my ($filename) = @_; | ||
| 92 | |||
| 93 | if ( ! -e $filename ) { | ||
| 94 | croak "Can't load device data $filename!\n"; | ||
| 95 | } | ||
| 96 | |||
| 97 | my $loaded = retrieve($filename); | ||
| 98 | return $loaded; | ||
| 99 | |||
| 100 | } | ||
| 101 | |||
| 102 | 1; | ||
| 103 | |||
| 104 | __END__ |