#!/usr/bin/perl

# RootBear @ IrcNet
# oh3nwq @ ham radio

# listening to UDP port to read 4 temperature sensors
# and store the data to rrd
# each sensor data comes in a separate message

# Flushing to STDOUT after each write
$| = 1;

use warnings;
use strict;
use IO::Socket;

# Server side information
my $listen_port     = 1000;
my $protocal        = 'udp';
my $received_data   = undef;
my $update;
my $sensor;
my $data;
my $s1="U";
my $s2="U";
my $s3="U";
my $s4="U";

# Creating UDP socket for server
# remember to change the local listening port if needed
my $server = IO::Socket::INET->new (
    LocalPort   => $listen_port,
    Proto       => $protocal,
    Type        => SOCK_DGRAM
) or die "Socket could not be created, failed with error $!\n";

while($server->recv($received_data, 64)) {
    my $peer_address = $server->peerhost();
    my $peer_port    = $server->peerport();
#    print "\nMessage was received from: $peer_address, $peer_port\n";
#    print "$received_data\n";

    $sensor = substr($received_data, 2-1, 1);
    $data = substr($received_data, 5-1, 6);

   if ($sensor == 1) {
        $s1 = $data;
        }
   if ($sensor == 2) {
        $s2 = $data;
        }
   if ($sensor == 3) {
        $s3 = $data;
        }
   if ($sensor == 4) {
        $s4 = $data;
        }

#    print "Sensor $sensor Data: $data\n";

#   remember to change the path and name of rrd
    $update=`/usr/bin/nice /usr/bin/rrdtool update /home/username/path_to_rrd/name_of_rrd.rrd N:$s1:$s2:$s3:$s4`;

# it might be a good idea to change the read sensor data back to "U" after a while
# but as this is just a test code, I did not bother
}

print "\nClosing socket...\n";
$server->close();
