Skip to content

Instantly share code, notes, and snippets.

@walkure
Created October 11, 2012 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walkure/3872704 to your computer and use it in GitHub Desktop.
Save walkure/3872704 to your computer and use it in GitHub Desktop.
UPS Monitor
#!/usr/bin/env perl
use strict;
use Device::SerialPort;
use IO::Socket;
use IO::Pipe;
use IO::Select;
my $pipe = IO::Pipe->new();
my $pid = fork();
if($pid != 0){
simple_server();
wait;
}
elsif(defined $pid){
ups_monitor();
exit:
}
sub ups_monitor
{
#monitoring
my $port = new Device::SerialPort('/dev/ttyUSB0');
$port->baudrate(2400);
$port->databits(8);
$port->parity("none");
$port->stopbits(1);
#become writer
$pipe->writer();
$pipe->autoflush(1);
while(1){
$port->write("Q1\x0d");
my ($count_in, $string_in) = $port->read(100);
unless($count_in == 47){
sleep(1);
next;
}
my @line = split(/[\(| ]/,$string_in);
$line[4] += 0;
my($vin,$vout,$load,$freq,$vbat) = ($line[1],$line[3],$line[4],$line[5],$line[6]);
print $pipe "$vin,$vout,$load,$freq,$vbat\n";
sleep(1);
}
}
sub simple_server
{
#become reader
$pipe->reader();
my $listener = new IO::Socket::INET(Listen => 1, LocalPort => 13255, ReuseAddr => 1);
my $selector = new IO::Select($pipe, $listener);
my($vin,$vout,$load,$freq,$vbat);
while(my @ready = $selector->can_read) {
foreach my $fh (@ready) {
if($fh == $listener) {
my $new = $listener->accept;
$selector->add($new);
}
elsif($fh == $pipe){
my $upslog = <$pipe>;
if(defined $upslog){
chomp $upslog;
my @dat = split(/,/,$upslog);
($vin,$vout,$load,$freq,$vbat) = @dat;
}
}
else {
print $fh <<"_HTTP_";
Content-Type: text/plain
$vin,$vout,$load,$freq,$vbat
_HTTP_
$selector->remove($fh);
$fh->close;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment