I noticed a weird behavior of my application on an ESP32. After some "debugging" I think the issue is due to this function:
bool getLocalTime(struct tm * info, uint32_t ms)
{
uint32_t start = millis();
time_t now;
while((millis()-start) <= ms) {
time(&now);
localtime_r(&now, info);
if(info->tm_year > (2016 - 1900)){
return true;
}
delay(10);
}
return false;
}
By the way, ms
defaults to 5000.
In my code I use getLocalTime
in a finite-state-machine in order to execute actions at specific time, i.e.:
void Irrigation::fsm()
{
time_t now = timing.getTimestamp();
switch (state)
{
case Running:
if (now - lastExecution)
{
// do something
}
break;
}
}
where:
time_t Timing::getTimestamp()
{
struct tm tm;
getLocalTime(&tm);
return mktime(&tm);
}
It seemed to me the application hangs (the fsm
is called every second).
Actually, looking at the getLocalTime
implementation I don't understand what it does. Why it needs a while cycle and a delay of 10 ms every cycle, just to retrieve the current time?
I'm looking for the epoch time in second. Is my approach wrong?