#!/usr/local/bin/perl use strict; use warnings; use POE qw( Component::Server::HTTP ); use lib qw( lib ); use CGI; use HTTP::Request::AsCGI; use Device::Gainer; use JSON::Syck; my $ALLOW_METHODS = { map {$_=>1} qw( turn_on_led turn_off_led peek_digital_input digital_output set_high set_low peek_analog_input analog_output )}; my $base = ( $0 =~ m#^(.*)/[^/]*$# )[0] || "."; my $html = "$base/default.html"; my $gainer = Device::Gainer->new( host => '192.168.1.33' ); my $conf = {}; $conf->{Port} = 10080; $conf->{ContentHandler} = { '/' => \&handler }; my $aliases = POE::Component::Server::HTTP->new( %$conf ); POE::Kernel->run(); sub handler { my ($req, $res) = @_; my $ascgi = HTTP::Request::AsCGI->new($req)->setup; my $cgi = CGI->new(); my $mode = $cgi->param('m') || "default"; if ( $mode eq "send" ) { $res->content_type('text/plain'); my $cmd = $cgi->param('c'); $cmd .= '*' unless ( $cmd =~ /\*$/ ); $gainer->send( $cmd ); $gainer->wait(); my $ret = $gainer->recv(); my $data = { res => $ret }; my $json = JSON::Syck::Dump( $data ); $res->content($json); } elsif ( $ALLOW_METHODS->{$mode} ) { $res->content_type('text/plain'); my $keys = [ sort grep {/^a/} $cgi->param() ]; my $args = []; foreach my $key ( @$keys ) { my $val = $cgi->param( $key ); push( @$args, $val ); } my @ret = $gainer->$mode( @$args ); my $ret = ( scalar @ret > 1 ) ? \@ret : $ret[0]; my $data = { res => $ret }; my $json = JSON::Syck::Dump( $data ); $res->content($json); } elsif( $mode eq "default" ) { $res->content_type('text/html; charset=UTF-8'); open( HTML, $html ) or die "$! - $html\n"; local $/ = undef; my $body = ; close( HTML ); $res->content($body); } else { $res->code(HTTP::Status::RC_FORBIDDEN); return HTTP::Status::RC_FORBIDDEN; } $res->code(RC_OK); return RC_OK; }