Skip to content

Instantly share code, notes, and snippets.

@mwegner
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwegner/4f55b22e4e06bcfb1cad to your computer and use it in GitHub Desktop.
Save mwegner/4f55b22e4e06bcfb1cad to your computer and use it in GitHub Desktop.
Ping-Based Device Presence (with Slack webhook)
<?php
// timeout in minutes for phone being considered away
// (iphones only check in sporadically to wifi when running on battery)
// can probably lower this and still avoid false positives...
$minutesAway = 21;
date_default_timezone_set("America/Phoenix");
// store everything in an associative array (hacky and simple)
// static DHCP assigned on router for device
$track = array();
$track['ip'] = '192.168.XX.YY';
$track['name'] = 'Matthew';
$track['gone'] = false;
$track['last'] = 0;
$track['timeArrived'] = time();
$track['timeLeft'] = time();
$all[] = $track;
// would put other devices here...
// initial settings when script starts
foreach($all as &$track)
{
$testNow = Ping($track['ip']);
$track['gone'] = !$testNow;
}
while(true)
{
foreach($all as &$track)
{
// current status
$testNow = Ping($track['ip']);
// debug
//print "Ping on $track[name]: " . ($testNow ? "YES" : "NO") . "\n";
// if we've been offline for awhile
$testGone = !$testNow && time() - $track['last'] > 60 * $minutesAway;
// did we just leave?
if($testGone && !$track['gone'])
{
print "$track[name] just left\n";
Send("$track[name] has left the office", "bad");
$track['timeLeft'] = time();
}
// did we just arrive?
if(!$testGone && $track['gone'])
{
print "$track[name] just arrived\n";
Send("$track[name] has arrived at the office", "good");
$track['timeArrived'] = time();
}
if($testNow)
$track['last'] = time();
$track['gone'] = $testGone;
sleep(1);
}
}
// this is for OSX!
function Ping($ip)
{
$str = exec("ping -c 1 -W 1 $ip 2>&1", $input, $result);
if($result == 0)
return true;
else
return false;
}
function Send($text, $color)
{
// you can specify channel (will use default for webhook otherwise)
$payload = array(
//'channel' => '#debug'
'username' => 'office presence'
,'icon_emoji' => ":runner:"
,'attachments' => array(
array(
'fallback' => $text
,'color' => $color
,'text' => $text
)
)
);
// your slack webhook goes here!
$url = 'https://hooks.slack.com/services/YOUR_WEBHOOK_INFO';
$fields = array(
'payload' => json_encode($payload)
);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields);
$result = curl_exec($ch);
curl_close($ch);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment