How to receive MQTT messages after deep sleep?

Maxyct
Posts: 1
Joined: Sun May 26, 2019 4:44 pm

How to receive MQTT messages after deep sleep?

Postby Maxyct » Mon Jun 10, 2019 11:28 pm

Hi guys,

is it possible to subscribe to a MQTT topic and collect messages every time the ESP32 wakes up from deep sleep mode?

I'm using Arduino IDE and loop function is not used in deep sleep mode and cannot understand where I should insert the client.loop() call: in the setup?
I'm using this library: https://pubsubclient.knolleary.net/api.html

Thanks,
Max

danwat
Posts: 1
Joined: Sat Jun 15, 2019 5:27 am

Re: How to receive MQTT messages after deep sleep?

Postby danwat » Sat Jun 15, 2019 5:57 am

Hi Max,

The thing to remember is, when using the arduino framework and deep sleeping, your sketch only runs the setup() section and never runs the loop() part.

So, one (pseudocode) option would look something like this

Code: Select all

bool readyToSleep=false;

void setup() {
  // I'm awake from sleep
  esp_sleep_enable_timer_wakeup(100000000);

  setup_networking();
  subscribe_topics();
  while(!readyToSleep){
     do_cool_things();
     client.loop();  //Ensure we've sent & received everything
  }
  esp_deep_sleep_start();
}

void loop(){
  // Usually won't get here
}
at some point in do_cool_things() you'd have to decide you'd been awake long enough (maybe a counter) , and set readyToSleep=true;
the code will call client.loop() one last time and then go back to sleep.

cheers,
Dan

Who is online

Users browsing this forum: Google [Bot] and 26 guests