#!/usr/bin/perl -w
#	check_watchptTemp_linux.pl
# 	Copyright 2010,2011 Julius Schlosburg
#
#	This script gets the temperature from a Digi Watchport Temperature Sensor.
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
	

use strict;
use Device::SerialPort;
use Getopt::Long;
my $argw;
my $argc;
my $argp;
my $argh = 0;

#get limited options set
GetOptions(
	"w=i" => \$argw,
	"c=i" => \$argc,
	"p=s" => \$argp,
	"h|help" => \$argh
);
my $exitcode = 3;
my $warning = $argw;
my $critical = $argc;
my $port = $argp;
if ($port eq ""){
	$port = "/dev/ttyUSB0";
}
if ($warning == "" || $critical == "" || $argh){
	print "Usage: \n /usr/bin/perl check_watchptTemp_linux.pl -w <warning temp> -c <critical temp> [-p <port(default /dev/ttyUSB0)>]\n\n";
	exit;
}

my $state = 2;

#get temp
my $temp = getTemp();

if ($temp > $warning){
	$state++;
}
elsif ($temp < $warning){
	$state--;
}
if ($temp > $critical){
	$state++;
}
elsif ($temp < $critical){
	$state--;
}

if ($state eq 0){
	print "OK: Temp is good at $temp";
	$exitcode = '0';
}
elsif ($state  < 3){
	print "WARNING: Temp is at $temp";
	$exitcode = '1';
}
elsif ($state eq 4){
	print "CRITICAL: Temp is at $temp";
	$exitcode = '2';
}

#Performance data:
print "|temp=$temp;$warning;$critical;0;100\n";
exit $exitcode;
	
#######################SUBS################################################

sub getTemp{
	#Create Serial port object
	my $ob = Device::SerialPort->new ($port) or die "CRITICAL, can't open serial port! $!";
	$ob->baudrate(9600);
	$ob->parity('none');
	$ob->databits(8);
	$ob->stopbits(1);
	$ob->handshake('none');
	$ob->stty_inlcr;
	$ob->write_settings || undef $ob;
	# Send TF command to watchport... tells device to return temp in F
	$ob->write("TF\r");
	$ob->read_char_time(5);
	my ($count, $tempRead) = $ob->read(255);
	if ($tempRead =~ /.*?([\d]+.[\d]+)/){
		$tempRead = $1;
	}
	$ob->close;
	undef $ob;
	return $tempRead;
}
