#!/usr/bin/php -qc/etc
# -q for quiet and -c for where the config is b/c php.ini is in /etc

<?php
#-----------------------------------------------------------------------#
#									#
# Script originally written by David McDowell and John Mitchell.	#
# Thanks also to fellow TriLUG (http://www.trilug.org) members.		#
# Maintained and updated by David McDowell.				#
#                                                                       #
# Ported to a single PHP script by Kevin Otte (kjotte@nivex.net)        #
#									#
# You may use this script freely providing you give due credit; please	#
# keep this information block for use and distribution. This script is	#
# provided WITHOUT ANY WARRANTY. Check					#
# http://www.turnpike420.net/linux/iTHX-M/ for the latest version.	#
#									#
# Version 1.4 - 2005-10-11						#
# 									#
#-----------------------------------------------------------------------#

# This script gets temperature/humidity data from a Newport Electronics, Inc.
# iServer MicroServer model iTHX-M: http://www.newportus.com
#
# Set this script up as a cron job to run every n minutes you will get
# a daily text log with mask: yyyy-mm-dd_iTHX-M.txt
#
# This PHP script outputs data as comma delimited text which is appended to
# the daily text log. It also puts the data into a MSSQL database; you may
# of course choose your own database logging method.

# Start by capturing date ($datenow) and time ($timenow) from your computer
# if you don't want date and time from the iTHX-M. The iTHX-M does not
# appear to have a way to keep time in sync using NTP or similar methods.
# use date('Y-m-d') for yyyy-mm-dd
# use date('H:i:s') for hr:mn:se

$datenow=date('Y-m-d');
$timenow=date('H:i:s');

# Declare deviceIP and port
$deviceIP = "10.1.1.1";
$port = 1000;

# Open socket connection to device
$socket = fsockopen($deviceIP,$port)
     or die("Could not connect to $deviceIP:$port (getting temp)\n");
     
# This gets one temperature ($temperature) reading.
# We cut the date/time from the return string of the iTHX-M.
# The iTHX-M returns with this mask: 000.00 mm/dd/yyyy hr:mn:se
# We only want the temperature: 000.00

fwrite($socket,"*SRT\r")
     or die("Could not send request to socket (getting temp)");

$temperature = substr(fgets($socket),0,6)
     or die("Could not read temperature from device");

# Done with first query, close socket connection
fclose($socket);

# Wait one second for the iTHX-M to recover
sleep(1);

# Open another socket connection to device
$socket = fsockopen($deviceIP,$port)
     or die("Could not connect to $deviceIP:$port (getting humidity)\n");
 
# This gets one humidity ($humidity) reading.
# We cut the date/time from the return string of the iTHX-M.
# The iTHX-M returns with this mask: 000.00 mm/dd/yyyy hr:mn:se
# We only want the humidity: 000.00

fwrite($socket,"*SRH\r")
     or die("Could not send request to socket (getting humidity)");

$humidity = substr(fgets($socket),0,6)
     or die("Could not read humidity from device");

# Done with second query, close socket connection
fclose($socket);

# Output as comma delimited text to daily text log.
# Added "T_" in front of the temperature.
# Added "H_" in front of the humidity.
$filename = sprintf("%s_iTHX-M.txt",$datenow);
$outfile = fopen($filename,"a")
     or die("Could not open $filename for writing");

$outstr = sprintf("%s,%s,T_%s,H_%s\n",$datenow,$timenow,$temperature,$humidity);

fwrite($outfile,$outstr)
     or die("Could not append data to $filename");

# Output to daily text log looks like this:
# 2004-09-25,15:50:01,T_067.80,H_056.50

# Output data to a database
# Define MSSQL 8.0 Server Parameters
$hostname = '10.1.1.2';
$username = 'myuser';
$password = 'mypwd';
$dbname = 'MYDB';

# Connect to MSSQL 8.0 Database
$conn = mssql_connect($hostname,$username,$password) or die ('Could not connect');
mssql_select_db($dbname) or die ('Could not select database.');

# Convert values to float
$temperature = floatval($temperature);
$humidity = floatval($humidity);

# Insert values into the database
$query1 = "INSERT INTO ITHXData (Temperature, Humidity) VALUES ($temperature, $humidity)";
mssql_query($query1) or die ('Temperature and Humidity update query failed.');

# ALERT NOTIFICATION SYSTEM
#
# Our default values in the database:
# TLowerAlarm = 74
# TUpperAlarm = 78
# HLowerAlarm = 82
# HUpperAlarm = 88
# Currently we haven't considered temperatures that would be too cold, nor
# have we considered extremely low humidities in our Alert system due to the
# moderate climate where we are located.

$query2 = "SELECT * FROM ITHXOptions";
$result2 = mssql_query($query2) or die ('Gathering upper values failed.');

while ($row2 = mssql_fetch_array($result2)){
	$TLowerAlarm = $row2['TLowerAlarm'];
	$TUpperAlarm = $row2['TUpperAlarm'];
	$HLowerAlarm = $row2['HLowerAlarm'];
	$HUpperAlarm = $row2['HUpperAlarm'];
	$TLASent = $row2['TLASent'];
	$TUASent = $row2['TUASent'];
	$HLASent = $row2['HLASent'];
	$HUASent = $row2['HUASent'];
	$TLACount = $row2['TLACount'];
	$TUACount = $row2['TUACount'];
	$HLACount = $row2['HLACount'];
	$HUACount = $row2['HUACount'];
	$CountLimit = $row2['CountLimit'];
	$recipient = $row2['SendTo'];
}

$email = "myiTHX-Mdevice@example.com";
$headers = "From: $email\n";
$headers .= "X-Sender: <$email>\n";
$headers .= "Return-Path: <$email>\n";
$TUASubject = "THERMAL ALERT";
$TLASubject = "THERMAL EVENT";
$HUASubject = "HUMIDITY ALERT";
$HLASubject = "HUMIDITY EVENT";
$message = "T = $temperature\n";
$message .= "H = $humidity\n";

if ($temperature >= $TUpperAlarm){
	if ($TUASent == 1){
		if ($TUACount >= $CountLimit){
			# send text alarm for Temperature Upper Alert
			mail($recipient, $TUASubject, $message, $headers,"-f <$email>");
			mssql_query("UPDATE ITHXOptions SET TUACount = 0");
		} else {
			$TUACount++;
			mssql_query("UPDATE ITHXOptions SET TUACount = $TUACount");
		}
	} else {
		# send text alarm for Temperature Upper Alert
		mail($recipient, $TUASubject, $message, $headers,"-f <$email>");
		$TUACount++;
		mssql_query("UPDATE ITHXOptions SET TUASent = 1, TUACount = $TUACount");
	}
} elseif ($temperature >= $TLowerAlarm){
	if ($TLASent == 1){
		if ($TLACount >= $CountLimit){
			# send text alarm for Temperature Lower Alert
			mail($recipient, $TLASubject, $message, $headers,"-f <$email>");
			mssql_query("UPDATE ITHXOptions SET TLACount = 0, TUACount = 0, TUASent = 0");
		} else {
			$TLACount++;
			mssql_query("UPDATE ITHXOptions SET TLACount = $TLACount, TUACount = 0, TUASent = 0");
		}
	} else {
		# send text alarm for Temperature Lower Alert
		mail($recipient, $TLASubject, $message, $headers,"-f <$email>");
		$TLACount++;
		mssql_query("UPDATE ITHXOptions SET TLASent = 1, TLACount = $TLACount, TUACount = 0, TUASent = 0");
       	}
} else {
	if (($TUACount > 0) or ($TUASent == 1)){

		mssql_query("UPDATE ITHXOptions SET TUACount = 0, TUASent = 0");
	}
	if (($TLACount > 0) or ($TLASent == 1)){
		mssql_query("UPDATE ITHXOptions SET TLACount = 0, TLASent = 0");
	}
}

if ($humidity >= $HUpperAlarm){
	if ($HUASent == 1){
		if ($HUACount >= $CountLimit){
			# send text alarm for Humidity Upper Alert
			mail($recipient, $HUASubject, $message, $headers,"-f <$email>");
			mssql_query("UPDATE ITHXOptions SET HUACount = 0");
		} else {
			$HUACount++;
			mssql_query("UPDATE ITHXOptions SET HUACount = $HUACount");
		}
	} else {
		# send text alarm for Humidity Upper Alert
		mail($recipient, $HUASubject, $message, $headers,"-f <$email>");
		$HUACount++;
		mssql_query("UPDATE ITHXOptions SET HUASent = 1, HUACount = $HUACount");
	}
} elseif ($humidity >= $HLowerAlarm){
	if ($HLASent == 1){
		if ($HLACount >= $CountLimit){
			# send text alarm for Humidity Lower Alert
			mail($recipient, $HLASubject, $message, $headers,"-f <$email>");
			mssql_query("UPDATE ITHXOptions SET HLACount = 0, HUACount = 0, HUASent = 0");
		} else {
			$HLACount++;
			mssql_query("UPDATE ITHXOptions SET HLACount = $HLACount, HUACount = 0, HUASent = 0");
		}
	} else {
		# send text alarm for Humidity Lower Alert
		mail($recipient, $HLASubject, $message, $headers,"-f <$email>");
		$HLACount++;
		mssql_query("UPDATE ITHXOptions SET HLASent = 1, HLACount = $HLACount, HUACount = 0, HUASent = 0");
       	}
} else {
	if (($HUACount > 0) or ($HUASent == 1)){
		mssql_query("UPDATE ITHXOptions SET HUACount = 0, HUASent = 0");
	}
	if (($HLACount > 0) or ($HLASent == 1)){
		mssql_query("UPDATE ITHXOptions SET HLACount = 0, HLASent = 0");
	}
}

mssql_close($conn);

?>
