From 536b076f390492d1b90e68825a536a2723d36790 Mon Sep 17 00:00:00 2001 From: iosullivan Date: Sun, 19 Jul 2026 08:09:36 +0800 Subject: [PATCH] Updates for reliable NTP --- examples/src/micropython/main.py | 50 ++++++++++++++++++++------------ 1 file changed, 31 insertions(+), 19 deletions(-) diff --git a/examples/src/micropython/main.py b/examples/src/micropython/main.py index 633ea0f..ab965f0 100644 --- a/examples/src/micropython/main.py +++ b/examples/src/micropython/main.py @@ -22,14 +22,24 @@ def connect_wifi(): wlan.active(True) wlan.connect(SSID, PASS) - # Wait for the connection (esp32 can take some time) - max_wait = 10 - while max_wait > 0: - if wlan.isconnected(): - break - max_wait -= 1 - print('Waiting for connection...') - sleep(1) + while not wlan.isconnected(): + try: + wlan.connect(ssid, password) + max_wait = 10 + while max_wait > 0: + if wlan.isconnected(): + break + max_wait -= 1 + print('Waiting for connection...') + sleep(1) + if wlan.isconnected(): + print('Connected to Wi-Fi') + print('Network config:', wlan.ifconfig()) + break + except Exception as e: + print('Connection error:', e) + print('Retrying connection...') + sleep(2) def init_LEDs(): # Sets up LEDs and their ports. @@ -40,13 +50,8 @@ def init_LEDs(): connect_wifi() # Synchronize time of RTC with NTP -try: - ntptime.settime() - print("Time synchronized successfully") -except Exception as e: - print("Error synchronizing time:", e) - -last_query = mktime([2000,1,1,0,0,0,0,0]) # Set last query default (will run on first run) +last_ntp_sync = -3700 # Init as more than an hour ago +last_api_query = mktime([2000,1,1,0,0,0,0,0]) # Set last query default (will run on first run) query_period = 120 # Query the API at most every 2 minutes distance_on = 10 # Time from station before turning on LED @@ -202,8 +207,17 @@ init_LEDs() while(True): + # Synchronise NTP time if hasn't been done in 1 hour + if (time() - last_ntp_sync) > 3600: + try: + ntptime.settime() + print("Time synchronized successfully") + last_ntp_sync = time() + except Exception as e: + print("Error synchronizing time:", e) + # Have we queried API in the query_period seconds? - if (time() - last_query) > query_period: + if (time() - last_api_query) > query_period: # Query updated API trains = (requests.get("https://lapi.transitchicago.com/api/1.0/ttpositions.aspx?key="+APIKEY+"&rt=Blue&outputType=JSON")).json()['ctatt'] @@ -219,9 +233,7 @@ while(True): stations[nextStation]['eta'].append(eta_time) - last_query = time() # uptime polling window - print(gmtime(last_query)) - + last_api_query = time() # uptime polling window # Process the ETA for each station