Created
February 14, 2014 15:56
-
-
Save cprerovsky/9003536 to your computer and use it in GitHub Desktop.
Ninjablock PHP presence script
This file contains hidden or 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 | |
| /** | |
| * php ninjablock presence driver | |
| * usage: | |
| * | |
| * nohup php -f ninja-presence.php 2>&1 & | |
| */ | |
| include 'nbapi.php'; | |
| date_default_timezone_set('CET'); | |
| $IPS = ['IP1', 'IP2', '...']; | |
| define( 'ACCESS_TOKEN', 'YOUR ACCESS TOKEN' ); | |
| define( 'DEVICE_GUID', 'YOUR STATE DEVICE GUID' ); | |
| define( 'CHECK_INTERVAL', 15 ); // seconds | |
| define( 'MISS_THRESHOLD', 3 ); // seconds | |
| $ninja = new Device(ACCESS_TOKEN); | |
| /** | |
| * check if ip address answers to ping | |
| * @param $ip ip address to be pinged | |
| * @return true if ping was successful, false otherwise | |
| */ | |
| function ping($ip) { | |
| $res = shell_exec("ping -c1 $ip"); | |
| if (strpos($res, '1 received') !== false) { | |
| return true; // ping successful | |
| } | |
| return false; | |
| } | |
| $lastState = $state = false; | |
| $missed = 0; | |
| while (true) { | |
| $LAST_SEEN = []; | |
| foreach ($IPS as $ip) { | |
| if (ping($ip)) { | |
| $LAST_SEEN[] = $ip; | |
| } | |
| } | |
| // now update status | |
| $lastState = $state; | |
| if (count($IPS) === count($LAST_SEEN)) { | |
| $state = "EverybodyHome"; | |
| $missed = 0; | |
| } else if (count($LAST_SEEN) > 0) { | |
| $state = "SomebodyHome"; | |
| $missed = 0; | |
| } else { | |
| $missed++; | |
| if ($missed >= MISS_THRESHOLD) { | |
| $state = "NobodyHome"; | |
| } else { | |
| echo "ping missed for $missed times\n"; | |
| } | |
| } | |
| if ($state != $lastState) { | |
| $ninja->actuate(DEVICE_GUID, array('DA' => $state)); | |
| echo 'presence ' . date('Y-m-d H:i:s') . ': ' . $state . "\n"; | |
| } | |
| sleep(CHECK_INTERVAL); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment