#!/usr/bin/perl

use ControlX10::CM17;
use Device::SerialPort;

#need to sleep a bit because the temp grabber needs a chance to write the file
sleep 20;

open(THERMOSTAT, "< /gdata/data/thermostat")
                or die "Thermostat not set! \n";

my $desired_temperature=<THERMOSTAT>;
chomp $desired_temperature;
close(THERMOSTAT);

if ( "$desired_temperature" !~ /[0-9]/ )
{
	print ("no desired temp\n");
	exit;
}

open(TEMPERATURE, "< /gdata/data/temperature")
                or die "Temperature not found! \n";

my @current_temps=<TEMPERATURE>;
close(TEMPERATURE);

my $current_temp = 'hey';

foreach $temp_temp (@current_temps)
{
	if ( "$temp_temp" =~ /Sensor\ 1/ )
	{
		$temp_temp =~ s/.*F: //;
		chomp $temp_temp;
		$current_temp=$temp_temp;
	}
}

if ( "$current_temp" !~ /[0-9]/ )
{
	print ("no current temp\n");
	exit;
}


my $serial_port = Device::SerialPort->new('/dev/ttyS0',1);
die "Can't open serial port $serial_port: $^E\n" unless ($serial_port);

$serial_port->error_msg(1); # use built-in error messages
$serial_port->user_msg(0);
$serial_port->databits(8);
$serial_port->baudrate(4800);
$serial_port->parity("none");
$serial_port->stopbits(1);
$serial_port->dtr_active(1);
$serial_port->handshake("none");
$serial_port->write_settings || die "Could not set up port\n";

my $wiggle_room = 0.5;

if ( $current_temp < ($desired_temperature - $wiggle_room)) {
	&ControlX10::CM17::send($serial_port, 'A9J');
	print ("turning on\n");
	print ("current_temp $current_temp\n");
	print ("desired_temp $desired_temperature\n");
	exit;
}

if ( $current_temp > ($desired_temperature + $wiggle_room)) {
	&ControlX10::CM17::send($serial_port, 'A9K');
	print ("turning off\n");
	print ("current_temp $current_temp\n");
	print ("desired_temp $desired_temperature\n");
	exit;
}

print ("no action taken\n");
print ("current_temp $current_temp\n");
print ("desired_temp $desired_temperature\n");
