Page 1 of 1

Set RTC time on boot from timezonedb.com

Posted: Sun Oct 25, 2015 4:02 pm
by alanb
I hacked up a module that gets time from the timezonedb.com, then makes it easy to sync your WiPy's real-time clock (RTC) to it. This is not that accurate because it makes no attempt to account for network latencies, but +/- a few seconds is fine for many applications.

Note, this module has a horrible bare-bones HTTP GET implementation using bare sockets. It is probably brittle and would benefit from being replaced by urllib, requests or some proper library. Ideas appreciated ...

Usage is as such:
  1. Register for an API key at timezonedb.com, which is free for non-commercial use and <1 time request/sec.
  2. Download nettime.py to your WiPy. (Optionally, set the default APIKEY variable in nettime.py to your API key.)
    nettime.py.zip
    (1.37 KiB) Downloaded 324 times
  3. Add something like the following to your boot.py so that your WiPy sets its RTC on every POWER_ON or HARD_RESET reset:

    Code: Select all

    if network.WLAN().isconnected() and machine.reset_cause()<=machine.HARD_RESET:
        rtc = nettime.sync_rtc_to_network_time(key='myapikey')
    

Re: Set RTC time on boot from timezonedb.com

Posted: Sun Oct 25, 2015 4:21 pm
by andrew
Nice!

Andrew

Re: Set RTC time on boot from timezonedb.com

Posted: Sun Oct 25, 2015 8:17 pm
by danicampora
Add something like the following to your boot.py so that your WiPy sets its RTC on every full reset:
The RTC time is kept across power saving modes, so even after a DEEPSLEEP reset it will keep the correct time.

Re: Set RTC time on boot from timezonedb.com

Posted: Sun Oct 25, 2015 8:18 pm
by danicampora
Very nice alanb, thanks for sharing :-)

Re: Set RTC time on boot from timezonedb.com

Posted: Mon Oct 26, 2015 1:32 am
by alanb
danicampora wrote: The RTC time is kept across power saving modes, so even after a DEEPSLEEP reset it will keep the correct time.
Thanks for the tip. I updated my boot.py to only set the RTC if the reset reason was POWER_ON or HARD_RESET.