glenn20 / micropython-espnow-utils

Some utilities for use with espnow and wifi on micropython
MIT License
22 stars 7 forks source link

NTP improvement: Retry until year > 2000 #4

Open BetterAutomations opened 5 months ago

BetterAutomations commented 5 months ago

Here's a little improvement you can do on the NTP script that I do on mine. Occasionally, the first ntptime.settime() call fails, so I retry until the year is no longer 2000.

import time
from micropython import const

NTP_MAX_RETRIES = const(10)

def get_year():
    tm = time.gmtime()
    return int(tm[0])

def is_synched():
    # Epoch is 2000. If year is still epoch it must not yet be synched.
    return get_year() > 2000

def sync():
    ntptime.host = host

    tries = 0
    while tries < NTP_MAX_RETRIES:
        tries += 1
        ntptime.settime()

        if is_synched():
            break
    else:
        raise Exception('NTP max retries exceeded')