<?php



	##############################################################
	# Swimming Pool Fill 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. 
	#
	############################################################
	#
	# 2016-05-06
	# V1.01
	#
	# Added blackout period for sprinkler system. Since my pool fills
	# using my irrigation line, I do not want the pool to fill while
	# my sprinklers are running. This would draw too much water
	# pressure from my system.
	#
	# Added a check to see if someone is manually filling the pool. I plan
	# on adding a button on the outside of my project box that will 
	# manually start and stop the filling process so I added the check
	# in here for that as well.
	##############################################################


/////////////////////////////////////////////////////////////////////////
// This is a simple bash script that will set your GPIO outputs the
// way you want them on boot of your Pi. In our case, when the Pi
// reboots it turns on our sprinkler valve for approx 1 minute until
// this script (pool_fill_control.php) runs and sets the pins correctly.
//
// You can create script with the below in it, then add that script to 
// the bottom of your /etc/rc.local file to be executed on boot. 

// #!/bin/sh

// ## Simple script to setup the mode on GPIO pin where
// ## you want it on boot. Put in /etc/rc.local to run
// ## on bootup.
//
//
//  /usr/local/bin/gpio -g write 17 1
//  /usr/local/bin/gpio -g mode 17 output
////////////////////////////////////////////////////////////////////////



// Provide your credentials to connect to MySQL.

$servername = "localhost";
$username = "pool_control"; // Your main MySQL admin username or username for your database.
$password = "My_Secret_Password"; // Your main MySQL admin password or password specific to your database.
$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;
$alertEmail = "your@email.here"; //Email address to include in log files. No email actually sent. 
$pushbilletAPI = "kjdsfkjdshkjdhfkjhsfdkjh"; // pushbullet API token (http://www.pushbullet.com)

// Set your timezone here. (http://php.net/manual/en/timezones.php)
date_default_timezone_set('America/Phoenix');


// Some stuff here to keep my pool from filling during the time my sprinkler system is running. 
// This will avoid too much draw on the sprinkler system. Could also be used to create a 
// 'blackout' period during which time you do not want your pool to fill (ie - when you are at work).

$current_time = date('Hi');
$SprinklerStart = 0400;
$SprinklerStop = 0900;

// 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'];
                }


// Cleanup - close the connection to the database.
$conn->close();







// I use this to keep the pool from filling while my sprinklers are running. You could also use this as a means of
// creating a 'blackout' period during which time you do not want your pool filled. 

	if ($current_time > $SprinklerStart && $current_time < $SprinklerStop) {
	echo "Sprinkler System Is Running, cannot fill the pool";
	}

	else {
// If someone has started to fill the pool manually, then we will bypass adding water as well as sending alerts.
// If you want to send alerts anyway, comment out the $PoolAlerting = false line below.

 	if(file_exists("/root/pool_control/manualFill.txt")) {
                // Someone is manually filling the pool, do nothing
		echo "Someone is manulay filling the pool already";
                $PoolAlerting = false;   // No need to send alerts if we are manually controlling the pool 	
        }

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

if ($PoolAlerting == true) {



        if($R == 0){ // check if pool  is filling and send alert when it starts and when it completes. 
                        // 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);
                                }
                        }
                }	

}


?>

