Created
January 9, 2017 21:31
-
-
Save lchoate/29f821d06c046f17e045e2ee7bb11943 to your computer and use it in GitHub Desktop.
Trying to automate something and understand globals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$worked = false; | |
$GLOBALS['from'] = "My devices <devices@myhouse.com>"; | |
$GLOBALS['toEmail'] = "me <me@address.com>"; | |
$GLOBALS['subject'] = "Home Automation Message"; | |
$validDeviceIPs = ['192.168.0.110','192.168.1.109']; | |
/** | |
* @param $device | |
* @param string $action | |
* @param string $additionalMessage | |
* @return bool | |
*/ | |
function doAction($device, $action = "OFF" ,$additionalMessage ="") | |
{ | |
$ok = false; //set a default response that assumes we couldn't command a device. | |
switch(strtolower($action)){ | |
case "on": | |
// ... whatever routine does that work. Assume it returns a bool $ok | |
break; | |
case "off": | |
// ... turn it off, return bool $ok; | |
break; | |
default: | |
$ok = false; // do nothing, retain the false and move on. | |
break; | |
} | |
if($ok) { | |
// appliance did whatever we asked, returned ok. | |
// setup success email. | |
$fullMessage = "Hi, \r\n I asked $device to turn $action and it did. Make sure the house isn't on fire. | |
\r\n Also, we were told to tell you $additionalMessage"; | |
} else { | |
//error email | |
error_log($device." failed to turn ".$action ); | |
$fullMessage = "YO!\r\n I asked $device to turn $action and it didn't or so we are told... You know how electronics are. | |
\r\n You may want to check it.\r\n Also, we were told to tell you $additionalMessage"; | |
} | |
$mail = mail($GLOBALS['toEmail'], $GLOBALS['subject'].$message ,$fullMessage); | |
if($mail){ | |
return true; | |
} else { | |
error_log("Failed to send a mail message about the $device turning $action"); | |
return false; | |
} | |
// failing all of that... | |
return false; | |
} | |
if(isset($_POST['thing']) && isset($_POST['action']) && in_array($_POST['device'],$validDeviceIPs,true)){ | |
if("ON" == $_POST['action'] || "OFF" ==$_POST['action'] ){ | |
$worked = doAction($_POST['device'],$_POST['action'],"You can add an additional message in this paramater. It will be appended to the email"); | |
if($worked){ | |
$message = "Ok, I did the thing you wanted"; | |
} else { | |
$message = "Something broke"; | |
} | |
} | |
echo $message; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment