#!/usr/bin/perl # David Brenner # ADC value 1023 = 60 Watts # ADC value 375 = 0 Watts use DBD::mysql; my $rotations; my $inst_current; my $scaling_factor = 60/648; # this is the value to multiply by the ADC value to get the actual current my $power; my $rpm; # connect to database my $dbh = DBI->connect("DBI:mysql:database=windturbine;host=localhost", "user", "password", {'RaiseError' => 1}); # 60 second timeout my $timeout = 60; my $tmp_count = 0; use IO::Socket; open(FILE,">/home/user/log.txt"); while(1){ $tmp_count = 0; eval{ local $SIG{ALRM} = sub { die "Timed Out"; }; alarm $timeout; my $sock = new IO::Socket::INET ( LocalHost => 'localhost', LocalPort => '9099', Proto => 'tcp', Listen => 1, Reuse => 1 ); die "Could not create socket: $!\n" unless $sock; my $new_sock = $sock->accept(); while(<$new_sock>){ alarm 0; $_ =~ /sensor: (\d+)/; my $sensor = $1; print FILE "sensor: $sensor cur value\n"; $sensor = ($sensor > 1024) ? 1023 : $sensor; $sensor = ($sensor < 375) ? 375 : $sensor; $power = ($sensor - 375) * $scaling_factor; $power = sprintf("%.3f", $power); my $date = `date +'%Y-%m-%d-%H:%M:%S'`; chomp $date; print FILE "power: $power watts\n"; if($tmp_count++ == 100){ close FILE; open(FILE,">/home/user/log.txt"); } $rpm = 0; $dbh->do("INSERT INTO windturbine (power, rpm) VALUES(?, ?)", undef, $power, $rpm); alarm $timeout; } close($sock); }; if($tmp_count++ == 1000){ close FILE; open(FILE,">/home/user/log.txt"); } my $date = `date +'%Y-%m-%d-%H:%M:%S'`; chomp $date; print FILE "$date Error: timeout.\n" if ( $@ && $@ =~ /Timed Out/ ); } close FILE;