Skip to content

Instantly share code, notes, and snippets.

@electricimp
Last active December 18, 2015 15:58
Show Gist options
  • Save electricimp/5807689 to your computer and use it in GitHub Desktop.
Save electricimp/5807689 to your computer and use it in GitHub Desktop.
Sample code for demonstrating device/agent communication with an Electric Imp (and round trip latency).
function startTime(time)
{
// Send the device a 'pong' message immediately
device.send("pong", time);
}
// When we get a 'ping' message from the device, call start_time()
device.on("ping", startTime);
function ping()
{
// Send a 'ping' message to the server with the current millis counter
agent.send("ping", hardware.millis());
}
function returnFromImp(startMillis)
{
// Handle a 'pong' message from the server
// Get the current time
local endMillis = hardware.millis();
// Calculate how long the round trip took
local diff = endMillis - startMillis;
// Log it
server.log("Round trip took: " + diff + "ms");
// Wake up in 5 seconds and ping again
imp.wakeup(5.0, ping);
}
// When we get a 'pong' message from the agent, call returnFromImp()
agent.on("pong", returnFromImp);
// Start the ping-pong
ping();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment