This Perl program runs continuously awaiting incoming packets from the Arduinos, placing them into a file where HCA can read them. The incoming packets are mostly formatted as HCA flags so no processing is required. The Arduino with the one-wire thermometers, however, sends in their one-wire addresses and this program changes those to an HCA-friendly format.
# major change – now interpret each record to see if it needs parsed
# use Time::Piece;
use IO::Socket::INET;
use Data::Dumper; # used for diag
# flush after every write
# $| = 1;
my ($socket,$received_data);
my ($peeraddress,$peerport);
my $outfile = “minutely.txt”; #picked up by hca
my $outln = “”;
my $logfile = “minutelog.txt”;
my $logln = “Minutely Start Up \n”;
my $infile = “ard-sensors.txt”; #contains sensor addr to hca element name
open LOGOUT, “>> $logfile” or die “Log file open error: $!”;
print LOGOUT $logln;
close LOGOUT;
$logln = “”;
# open file that contains addr/name translations
open INPUT, “$infile” or die “Input file open error: $!”;
# once file is open, create hash of addresses and names
my %taddr;
while (<INPUT>)
{
chomp;
my ($addrkey, $addrval) = split /=/;
$taddr{$addrkey} .= exists $taddr{$addrkey} ? “$addrval” : $addrval;
}
# print Dumper(\%taddr);
close INPUT;
# we call IO::Socket::INET->new() to create the UDP Socket and bound
# to specific port number mentioned in LocalPort and there is no need to provide
# LocalAddr explicitly as in TCPServer.
$socket = new IO::Socket::INET (
LocalPort => ‘5000’,
Proto => ‘udp’,
) or die “ERROR in Socket Creation : $!\n”;
$logln = “Starting infinite loop \n”;
open LOGOUT, “>> $logfile” or die “Log file open error: $!”;
print LOGOUT $logln;
close LOGOUT;
while(1)
{
# read operation on the socket
$socket->recv($received_data,1024);
my $datestring = localtime();
#get the peerhost and peerport at which the recent data received for the log
$peer_address = $socket->peerhost();
$peer_port = $socket->peerport();
if ($peer_port != “6000” && $peer_port != “5001” )
{
$logln = “Minutely Shutting Down \n”;
open LOGOUT, “>> $logfile” or die “Log file open error: $!”;
print LOGOUT $logln;
close LOGOUT;
$socket->close();
system (“start C:\\Users\\smarthome\\Documents\\HCA\\Logs\\minutelyrestart.bat”);
exit;
}
$logln = “$datestring,$peer_address,$peer_port,$received_data\n”;
# see if the record starts with a special word
if ($received_data =~ /taddr/)
{
# print “took branch 1 \n”;
my @fields = split /:/, $received_data;
my $addr1 = $fields[1];
if (exists $taddr{$addr1})
{
# print “took branch 2 \n”;
$addr2 = $taddr{$addr1};
$outln = $addr2 . “=” . $fields[2] . “\n”;
}
else
{
$outln = $fields[1] . “=” . $fields[2] . “\n”;
}
# print “$taddr{$addr1}”;
}
else
# if not, just use the record as is
{
$outln = $received_data . “\n”;
}
open OUTPUT, “>> $outfile” or die “Output file open error: $!”;
print OUTPUT $outln;
close OUTPUT;
open LOGOUT, “>> $logfile” or die “Log file open error: $!”;
print LOGOUT $logln;
close LOGOUT;
}
$socket->close();