<?php

	##############################################################
	# Swimming Pool Control Script for a Raspberry Pi 3
	# 
	# V1.0 (2016-05-06)
	# Richard J. Sears
	# richard@sears.net
	##############################################################
	#
	# This script is part of a smart pool level monitoring system 
	# comprised of a moneino (moteino.com) connected to an eTape
	# water level sensor. The Motenio runs a sketch that monitors
	# the water level in the pool every 10 minutes and if it gets
	# below a certain point, it writes a low water level bit to a 
	# mysql database. 
	#
	# This script reads that bit and then makes a decision what to
	# based on the water level in the pool.
	#
	# If the water is low, then the script causes GPIO pin 17 (0) 
	# to go HIGH powering a relay that opens a sprinkler control
	# valve attached to the pool. It also send a pushbullet 
	# notification so that you know that your pool is being filled.
	#
	# Once the pool level has reached the desired level, the script
	# shuts off the sprinkler valve by forcing the GPIO pin LOW
	# which shuts off the valve. It then sends another pushbullet
	# notification letting you know is has completed filling the
	# pool. 
	#
	############################################################
       



// Provide your credentials to connect to MySQL.

$servername = "your.server.name";
$username = "pool_control"; // Your main MySQL admin username or username that is the exact same for both databases
$password = "SuperSecretPassword"; // Your main MySQL admin password or password that is exact same for both databases
$emoncms_db = "emoncms"; // The name of your emoncms (or other) database.

// Set up some alerting so we know when the pool is getting filled up and when it is done.
$PoolAlerting = true; // Alert Logging
$alertActive = true; // send pushbutton alert when pool filling? - set to false to disable alerting
$alertEmail = "bob@microsoft.com"; //Email address to include in log files. No email actually sent. 
$pushbilletAPI = "klsdjfghkldsjgfhkdjshkfjdshgkj"; // pushbullet API token (http://www.pushbullet.com)

// Set local timezone
date_default_timezone_set('America/Phoenix');

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}


// Get current Pool Level status from database
                $sql = mysqli_query($conn,"SELECT data FROM ".$emoncms_db.".feed_222 ORDER by time DESC LIMIT 1");
                        while ($row = mysqli_fetch_array($sql)){
                                $R = $row['data'];
                }


if ($R == 0) {
echo "Pool Level is LOW";
 exec('gpio mode 0 out');
 exec('gpio write 0 1');
}
else
{
echo "Pool Level is OK";
exec('gpio mode 0 out');
exec('gpio write 0 0');
} 


if ($PoolAlerting == true) {



        if($R == 0){ // check if station is reporting and send alert if activated
                if($alertActive){
                        // check if alert was sent already
                        if(file_exists("/root/pool_control/alertSent.txt")){
                                // alert was sent already, do nothing
                        }
                        else{

                                // Send a pushbullet notification
                                exec("
                                curl --header 'Access-Token: ".$pushbilletAPI."' \
                                --header 'Content-Type: application/json' \
                                --data-binary '{\"body\":\"Your swimming pool water level is low and is being refilled.\",\"title\":\"Swimming Pool is Refilling\",\"type\":\"note\"}' \
                                --request POST \
                                https://api.pushbullet.com/v2/pushes
                                ");
                                $alertFile = fopen("/root/pool_control/alertSent.txt", "w") or die("Unable to open file!");
                                $txt = "Alert sent";
                                fwrite($alertFile, $txt);
                                fclose($alertFile);

                                // now make a note in the error log that mail was sent
                                if(file_exists("/root/pool_control/AlertLog.txt")){
                                     //   $lastReport = date("Y-m-d H:i",$lastMeteoUpdate);
                                        $message = "Swimming Pool is Refilling";
                                        $errorContent = file_get_contents("/root/pool_control/AlertLog.txt");
                                        $errorContent = $errorContent."\n\n".date("Ymd H:i",time())."\n".$message."\nSending PushBullet to ".$alertEmail.".";
                                        file_put_contents("/root/pool_control/AlertLog.txt", $errorContent);
                                }
                                else{
                                        $errorFile = fopen("/root/pool_control/AlertLog.txt", "w") or die("Unable to open file!");
                                        $errorText = date("Ymd H:i",time())."\n".$message."\nSending email to ".$alertEmail.".";
                                        fwrite($errorFile, $errorText);
                                        fclose($errorFile);
                                }
                        }
                }
        }

	if($R ==1){
	 if(file_exists("/root/pool_control/alertSent.txt")){
				// Send a pushbullet notification
                                exec("
                                curl --header 'Access-Token: ".$pushbilletAPI."' \
                                --header 'Content-Type: application/json' \
                                --data-binary '{\"body\":\"Swimming pool water level back to normal. Refilling Complete.\",\"title\":\"Swimming Pool Level OK\",\"type\":\"note\"}' \
                                --request POST \
                                https://api.pushbullet.com/v2/pushes
                                ");                        
				unlink('/root/pool_control/alertSent.txt');

			       // now make a note in the error log that mail was sent
			       if(file_exists("/root/pool_control/AlertLog.txt")){
                                        $message = "Swimming Pool is Done Refilling";
                                        $errorContent = file_get_contents("/root/pool_control/AlertLog.txt");
                                        $errorContent = $errorContent."\n\n".date("Ymd H:i",time())."\n".$message."\nSending PushBullet to ".$alertEmail.".";
                                        file_put_contents("/root/pool_control/AlertLog.txt", $errorContent);
                                }
                                else{
                                        $errorFile = fopen("/root/pool_control/AlertLog.txt", "w") or die("Unable to open file!");
                                        $errorText = date("Ymd H:i",time())."\n".$message."\nSending email to ".$alertEmail.".";
                                        fwrite($errorFile, $errorText);
                                        fclose($errorFile);
                                }
                        }
                }	

}





// Cleanup
$conn->close();

?>

