#!/usr/bin/perl
use LWP::Simple;
use DBI;
#use strict;

my $DBHOST = "localhost";
my $DBNAME = "temperature";

my $URL = "http://192.168.1.51/";
my $PASSWORD = "ando1937";

my $solin = "[34:62:77:68:32:33:32:41]";
my $solut = "[34:65:59:76:32:33:32:44]";
my $ack   = "[34:77:67:76:32:33:32:68]";


# CREATE TABLE nattsjo_solin (id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, 
#	time TIMESTAMP, temp SMALLINT, PRIMARY KEY(id));

#CREATE TABLE nattsjo_solut (id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, 
#	time TIMESTAMP, temp SMALLINT, PRIMARY KEY(id));

#CREATE TABLE nattsjo_ack1 (id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, 
#	time TIMESTAMP, temp SMALLINT, PRIMARY KEY(id));

# yum install perl-libwww-perl 
#

my $content = get($URL); #Get web page in content
if (!defined $content) {
    die "get failde!";
}

if ($content =~ /error/) {
    print $content . "\n";
    die "Sensor error!";
}

if ($content =~ /no sensor/) {
    print $content . "\n";
    die "No Sensor!";
}


@w2 = split(/\n/, $content);

@s1 = split(/\s+/, $w2[2]);
@s2 = split(/\s+/, $w2[3]);
@s3 = split(/\s+/, $w2[4]);

$t1 = substr($s1[4],0,length($t1)-2);
$t2 = substr($s2[4],0,length($t2)-2);
$t3 = substr($s3[4],0,length($t3)-2);

$a1 = $s1[3]; $a2 = $s2[3]; $a3 = $s3[3];
$t1 = $t1*10; $t2 = $t2*10; $t3 = $t3*10;

$sql1 = "INSERT INTO nattsjo_solarin VALUES (null, now(), $t1)";
$sql2 = "INSERT INTO nattsjo_ack1 VALUES (null, now(), $t2)";
$sql3 = "INSERT INTO nattsjo_solarout VALUES (null, now(), $t3)";

$webreport1 = "http://www.rotary.nu/temp/nattsjo_solarin/report.php";
$webreport2 = "http://www.rotary.nu/temp/nattsjo_ack1/report.php";
$webreport3 = "http://www.rotary.nu/temp/nattsjo_solarout/report.php";


	if (exists($ARGV[0])) {
	    print $content . "\n\n";
	    print $a1 . " " . $a2 . " " . $a3 . "\n";
	    print $t1 . " " . $t2 . " " . $t3 . "\n\n";
	    print $sql1 . "\n";
	    print $sql2 . "\n";
	    print $sql3 . "\n";
	} else {	
		my $db = DBI->connect("DBI:mysql:$DBNAME:$DBHOST", $DBUSER, $DBPASS);
		if ($t1) {
		    $DBI::result = $db->prepare($sql1);
		    $DBI::result->execute();
		}
		if ($t2) {
		    $DBI::result = $db->prepare($sql2);
		    $DBI::result->execute();
		}
		if ($t3) {
		    $DBI::result = $db->prepare($sql3);
		    $DBI::result->execute();
		}
		undef $db;

                if ($webreport1 && $t1) {
		    get("$webreport1?pw=$PASSWORD&temp=$t1");
                }
                if ($webreport2 && $t2) {
		    get("$webreport2?pw=$PASSWORD&temp=$t2");
                }
		if ($webreport3 && $t3) {
		    get("$webreport3?pw=$PASSWORD&temp=$t3");
                }
}