Skip to content

Instantly share code, notes, and snippets.

@ElectricImpSampleCode
Last active September 12, 2018 10:18
Show Gist options
  • Save ElectricImpSampleCode/fb40795297445d19834b75464f59f39a to your computer and use it in GitHub Desktop.
Save ElectricImpSampleCode/fb40795297445d19834b75464f59f39a to your computer and use it in GitHub Desktop.
Electric Imp imp API imp.setpowersave() demo code
// Just respond to 'ping' messages by immmediately
// sending back a 'pong' message to the device
device.on("ping", function(dummy) {
device.send("pong", true);
});
// Set the number of messages from which the average rount-trip
// time will be taken at the end of every run (float for better
// accuracy when we come to calculate the average duration)
const TRIP_COUNT = 100.0;
local runCount = 0;
local total = 0;
local pingTime = 0;
// Send a 'ping' message to the server
function ping() {
// Record the time of the ping transmission
pingTime = hardware.millis();
agent.send("ping", true);
}
// Handle the incoming 'pong' reply from the server
agent.on("pong", function(dummy) {
// How long did the message round trip take?
local roundTrip = hardware.millis() - pingTime;
// Add it to the total so we can average later
total = total + roundTrip;
runCount++;
if (runCount == TRIP_COUNT) {
// We've done the first batch of runs in Standard Mode
// Report the data and switch to power save
server.log(format("Standard WiFi Mode Avg. Round Trip Time: %.2fms", total / TRIP_COUNT));
server.log("Starting Run #2 - Power-save WiFi Mode...");
imp.setpowersave(true);
total = 0;
} else if (runCount >= TRIP_COUNT * 2) {
// End of final run, so report the power save time
server.log(format("Power-save WiFi Mode Avg. Round Trip Time: %.2fms", total / TRIP_COUNT));
return;
}
// Send the next message
ping();
});
// Start of runtime
server.log("Starting Run #1 - Standard WiFi Mode...");
ping();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment