I had a bug where IoTaWatt was always failing the call to rtc.initialize() in Setup.cpp and also taking a very long time to obtain the current time via NTP.
The first problem is that my RTC started in a disabled state (Control_3 had a value of 0xE0). IoTaWatt would never reset the RTC into an enabled state (Typically I assume you want to use 0 for the top 3 bits of the Control_3 register of RTC to enable both “Standard Battery Switchover” and “Low Battery Detection”).
I see in timeServices.cpp the syncRtc state has a comment indicating that rtc.adjust() also changes the mode enabling both “Standard Battery Switchover” and “Low Battery Detection”. However, rtc.adjust() was never called.
You can reproduce this problem by changing the code to set Control_3 register to 0xE0 in setup. After doing this once, the state was retained by my RTC and the problem showed up again every time I rebooted I needed a successful NTP query before anything would start working.
I dont know how my RTC got into this disabled state in the first place (I think it just started off that way from the beginning). I think IoTaWatt firmware should probably be made to be resilient against this problem.
My solution was to update the conditional for the rtc.adjust() call from:
if(timeDiff < -1 || timeDiff > 1)
// Read Control_3
uint8_t Control_3 = Wire.read();
if(timeDiff < -1 || timeDiff > 1 || ((Control_3 & 0xE0) != 0))
This forces the adjust call to run if the current state is not what we expect, which sets the RTC into the desired state (Standard Switchover and Low Detection), but only after getting a correct time from NTP.
The other problem I was having was with older firmware, where an NTP query would always timeout. I have a large ping. The increase in the timeout helps somewhat, but an improvement for me was changing to using the NTP pool servers instead of the NIST ones. The NIST ones apparently work well in USA but not so well outside.
I.e. I changed the NTP host from “time.nist.gov1”, to using: “pool.ntp.org”. Changing this greatly reduced the time required to synchronize with the NTP servers for me.
A more complete change would be to add this option to the config file. But that may be overkill.
Would you be willing to accept pull requests for these two changes?