Deep sleep, preferences and software download

Hi,

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 <- {};
prefs.itv <- 1;
prefs.sid <- “Hello”;
prefs.pas <- “World”;

// TBD: server.save() 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(){
prefs.itv = time() % 60;
server.log("Pref change itv: " + prefs.itv);
imp.wakeup(12,simulatingPrefChanges);
}

server.log(“Agent started”);
device.onconnect(sendPrefs);
simulatingPrefChanges();
`

Device nut:

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

function sleep(unused){
server.flush(15);
if(server.isconnected()) server.expectonlinein(20);
imp.deepsleepfor(20);
}

function awake(unsused){
server.log(“Awake, doing this”);
imp.onidle(sleep(true));
}

server.setsendtimeoutpolicy(RETURN_ON_ERROR, WAIT_TIL_SENT, 15);
server.onunexpecteddisconnect(function(reason) {sleep();});
imp.setpowersave(true);
imp.enableblinkup(false);

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

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

imp.onidle(sleep(true));

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); });

Peter

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 = prefs.itv, sid = prefs.sid, pas = prefs.pas};