Skip to content

Instantly share code, notes, and snippets.

@ElectricImpSampleCode
Last active September 10, 2018 10:31
Show Gist options
  • Save ElectricImpSampleCode/666c0f23d9088df7ce6f to your computer and use it in GitHub Desktop.
Save ElectricImpSampleCode/666c0f23d9088df7ce6f to your computer and use it in GitHub Desktop.
This example shows device-agent and agent-device messaging in action.
function startTime(time) {
// Send the device a 'pong' message immediately
device.send("pong", time);
}
// When we get a 'ping' message from the device, call startTime()
device.on("ping", startTime);
function ping() {
// Send a 'ping' message to the server with the
// current millisecond counter value
agent.send("ping", hardware.millis());
}
function returnFromAgent(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 returnFromAgent()
agent.on("pong", returnFromAgent);
// Start the ping-pong
ping();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment