Skip to content

Instantly share code, notes, and snippets.

@blindman2k
Last active December 24, 2015 00:59
Show Gist options
  • Save blindman2k/6720979 to your computer and use it in GitHub Desktop.
Save blindman2k/6720979 to your computer and use it in GitHub Desktop.
The device pings the agent every second. If it misses a pong response it turns on the light for at least 10 seconds.
device.on("ping", function(ping) {
device.send("pong", ping);
})
server.log("Agent started")
const TOLERANCE = 1000;
const LOST = 3000;
const WAKEUP = 1000;
const DELAY = 5000;
//------------------------------------------------------------------------------
imp.configure("Agent ping", [], []);
server.log("Device started")
//------------------------------------------------------------------------------
turnoff <- time();
pings <- {};
//------------------------------------------------------------------------------
led <- hardware.pin9;
led.configure(DIGITAL_OUT);
led.write(0);
//------------------------------------------------------------------------------
function alert(message) {
server.log(message)
led.write(1);
turnoff = time() + 10;
}
//------------------------------------------------------------------------------
agent.on("pong", function(pong) {
local dur = math.abs(hardware.millis() - pong);
if (pong in pings) {
delete pings[pong];
if (dur > TOLERANCE) {
alert(format("ALERT: %0.02f seconds", dur/1000.0));
} else {
// server.log(format("PONG: %0.02f seconds", dur/1000.0));
}
} else {
server.log(format("FOUND: %0.02f seconds", dur/1000.0));
}
})
//------------------------------------------------------------------------------
function ping() {
// Check for lost pings
local lost = [];
foreach (ping,dummy in pings) {
local dur = math.abs(hardware.millis() - ping);
if (dur > LOST) {
lost.push(ping);
}
}
if (lost.len() > 0) {
foreach (ping in lost) {
delete pings[ping];
}
alert(format("LOST: %d pings", lost.len()));
}
// Send the next ping
local last_ping = hardware.millis();
pings[last_ping] <- true;
agent.send("ping", last_ping)
if (time() >= turnoff) {
led.write(0);
}
imp.wakeup(WAKEUP/1000.0, ping);
}
imp.wakeup(DELAY/1000.0, ping);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment