Sleep without loop blocks connection


#1

Not a big deal now that I know about it but I’ve found that if you sleep without looping, Bluz will stay in a blinking green state. Why? Is there another method I could call within the loop (ie Particle.Process()) to allow it to connect?

For example this code will prevent a connection for 120sec.

void setup() {
}

void loop() {
    unsigned long startTime = millis();
    while(millis() - startTime < 120000) //120sec
        System.sleep(SLEEP_MODE_CPU);
}

I had a function that needs a delay so it seemed like a sensible thing to put the cpu to sleep while it waited. I found if I wait for Particle.connected before sleeping then I don’t have a problem. Perhaps worth mentioning on http://docs.bluz.io/reference/system/


#2

Yes, blocking the main thread will cause delays in connection and cloud events. Bluz works on a single thread, the user app is called in-line with all the other code that is used to manage the connection to the cloud or receive events. By blocking it as you did, you have effectively blocked the entire system.

We do mention this a bit on the main page of the docs, but we can try to be more explicit about it. The sleep call has nothing to do with it, you have effectively done a delay(120000).


#3

Ok, I see there’s already an issue for adding processing during delays: https://github.com/bluzDK/bluzDK-firmware/issues/18

Is there something I can call in the meantime to allow the background processing, like Particle.process() for the Photon/Core before they made it part of delay()?


#4

Yes, that is on the list to fix.

At the moment, no. The best way to do this for now is to set a time and only move on when it is passed. So something like this:

long nextTime;
long timeBetween = 120000;

void setup() {
  nextTime = millis();
}

void loop() {
  if (millis() > nextTime) {
    //do whatever every two minutes
    nextTime = millis()+timeBetween;
  }
  System.sleep(SLEEP_MODE_CPU);
}

That will let you run your code every two minutes without blocking the system at all. We will update delay() in a future release to basically do the CPU sleeping and cloud processing when you call it, so it would take care of all this for you.


#5

Ok, good to know. For now I’ve just added a publish queue. That was the reason for waiting, to keep trying to re-sending my Particle.publish until it succeeded. The publish queue is a better option anyway as it won’t block the rest of my code.