Proper usage of server.sleepfor

I am trying to write the most efficient code to a run a battery operated device. Here is the sequence of events:

  1. Agent retrieves sunset time from Weather Underground and performs a device.send(“sunset”, json.sunset) on device.onconnect
  2. Device wakes up from from previous server.sleepuntil(sunset.hour, sunset.minute)
  3. Device turns on a latching solenoid valve
  4. Device goes to sleep for 1 hour
  5. Device turns off a latching solenoid valve
  6. Device goes to server.sleepuntil(sunset.hour, sunset.minute) using the new sunset time from agent.on

The main issue is step 4. How do I code the second sleep for 1 hour (trying to avoid imp.sleep).
Also, should I be concerned about the timing of the device.send on device.onconnect from the agent when the device is in deep sleep?

Why are you trying to avoid imp.sleep?

imp.sleep is a busy wait; if you’re running off batteries and not needing any IO during that time, you should use server.sleepfor() to drop down to microamp level for that hour.

The device can’t get messages in deep sleep, but sending when the agent is told the device is online is a good strategy. You can then sleep immediately when you receive the message from the agent.

Thanks, Hugo! Just to clarify it, can I have a server.sleepfor() (step 4) followed by server.sleepuntil() (step 6)?

On waking from deep sleep, the imp restarts squirrel from the top (unlike imp.sleep). You can call hardware.wakereason() to check for WAKEREASON_TIMER, but you’ll probably also need to use the nv table to determine whether you’re waking to turn the solenoid on or off.

Thank you, you just confirmed my approach. I will also use agent.send to do a and retrieve it if not WAKEREASON_TIMER.

server.sleepfor() will enter sleep immediately, just as server.sleepuntil() does. You can’t follow one with another because, well, this is always the last thing it does :slight_smile: