Deep sleep, preferences and software download


I am Coding for a battery driven device (imp002) that deep sleeps and periodically wakes up and do measurements. The following example based on documentation has two problems. 1. Agent preference changes never reach the device 2. software updates are not received by the device after first power on.

In the example the device just do a server.log(“Awake, doing this”) instead of meassurements.

Suggestions for improvement?

Agent nut:

`// Default preferences
prefs <- {}; <- 1;
prefs.sid <- “Hello”;
prefs.pas <- “World”;

// TBD: and server.load() to keep prefs across updates

function sendPrefs(){
local data = {itv = 2, sid = prefs.sid, pas = prefs.pas};
device.send(“prefs”, data);
server.log("->Device: " + http.jsonencode(data));

function simulatingPrefChanges(){ = time() % 60;
server.log("Pref change itv: " +;

server.log(“Agent started”);

Device nut:

function updatePrefs(dat){ =;
nv.sid = dat.sid;
nv.pas = dat.pas;
server.log(“Prefs updated …”);

function sleep(unused){
if(server.isconnected()) server.expectonlinein(20);

function awake(unsused){
server.log(“Awake, doing this”);

server.setsendtimeoutpolicy(RETURN_ON_ERROR, WAIT_TIL_SENT, 15);
server.onunexpecteddisconnect(function(reason) {sleep();});

if ( !(“nv” in getroottable()) ) nv <- {itv = 3, sid = null, pas = null};
agent.on(“prefs”, updatePrefs);

server.isconnected() ? awake(true) : server.connect(awake, 15);


This line is wrong: it calls onidle not with the function sleep, but with the result of calling the function sleep(true). The result of the function isn’t valid as a parameter to onidle, but that error is never produced because sleep(true) never returns! What you meant is probably:

imp.onidle(function() { sleep(true); });


Yes Peter, that’s what I meant to do, thanks!

And then changing from “itv = 2” to the following in sendPrefs() in the agent, let’s the simulated itv changes transfer:

local data = {itv =, sid = prefs.sid, pas = prefs.pas};