For loop or millis function?

My critical devices all have watchdog modules attached.

On other non-critical devices, I want to have a "watchdog" function to check MQTT messages have been published, if not published for say 5 times in a row then restart the ESP.

Current watchdog module code, only pats the watchdog if the MQTT message is published.

void setup()
{
timer.setInterval(5000L, heartbeat);
}


void heartbeat()  // function for heartbeat check and watchdog pat
{
  //publish freeram value first of all
  MQTTclient.publish((base_mqtt_topic + "/freeram").c_str(), String(ESP.getFreeHeap()).c_str(), true);

  //if mqtt message published successfully, pat the watchdog
  if (MQTTclient.publish((base_mqtt_topic + "/heartbeat").c_str(), String(WiFi.RSSI()).c_str(), true))
  {
   //Pat the HARDWARE watchdog
    digitalWrite(WATCHDOG, HIGH);
    delay(20);
    digitalWrite(WATCHDOG, LOW);
  }
}

Proposed code alternative to the hardware version, I am not sure what to do. I have two ideas:

  1. Use a 'for' loop - idea from this page
    Each time mqtt is published, set i=0, otherwise i++
    If i = 5 then "ESP.restart();"

I'm not sure if i has to be declared as int in the heartbeat function, or globally?

  1. Use a millis function-
    Heartbeat function is called every 5000ms, so 5 x 5000 = 25000ms to allow before resetting.
    Each time mqtt is published, set long unsigned variable "interval" = millis.
    Check if interval - millis > 25000, if so "ESP.restart();"
    .

Again I'm not sure if the variables should be declared globally or in the heartbeat function.

If there's any other comments or tips on approaching this please feel free.
Thanks

877:
Again I'm not sure if the variables should be declared globally or in the heartbeat function.

Do you need to access the variables from other parts of the program? If yes, global, if no, local.

The variable would only be used in the heartbeat function, so local then.

I wasn’t sure, as the variable gets incremented only one time for each call of the function. I assume the variable value is stored even when the program moves to another function?

Sorry if I’m using the wrong terminology.

If the function is called multiple times the variable has to be declared as static.
function call means. the function is called by its name running down each command inside the function
and then leaving the function.

If the variable should keep its value for mutliple function calls it has to defined as static.
Otherwise the the variable will be created new with every new function-call.

So as long as you choose an selfexplaining name with mutliple characters a global variable is a bit easier.

best regards Stefan

Thank you Stefan that makes sense now.