Updates for reliable NTP

This commit is contained in:
iosullivan committed 2026-07-19 08:09:36 +08:00
1 parent 6c202faac5
commit 536b076f39
1 file changed
+24 -12
+24 -12
View File
@@ -22,7 +22,9 @@ def connect_wifi():
wlan.active(True) wlan.active(True)
wlan.connect(SSID, PASS) wlan.connect(SSID, PASS)
# Wait for the connection (esp32 can take some time) while not wlan.isconnected():
try:
wlan.connect(ssid, password)
max_wait = 10 max_wait = 10
while max_wait > 0: while max_wait > 0:
if wlan.isconnected(): if wlan.isconnected():
@@ -30,6 +32,14 @@ def connect_wifi():
max_wait -= 1 max_wait -= 1
print('Waiting for connection...') print('Waiting for connection...')
sleep(1) 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(): def init_LEDs():
# Sets up LEDs and their ports. # Sets up LEDs and their ports.
@@ -40,13 +50,8 @@ def init_LEDs():
connect_wifi() connect_wifi()
# Synchronize time of RTC with NTP # Synchronize time of RTC with NTP
try: last_ntp_sync = -3700 # Init as more than an hour ago
ntptime.settime() last_api_query = mktime([2000,1,1,0,0,0,0,0]) # Set last query default (will run on first run)
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)
query_period = 120 # Query the API at most every 2 minutes query_period = 120 # Query the API at most every 2 minutes
distance_on = 10 # Time from station before turning on LED distance_on = 10 # Time from station before turning on LED
@@ -202,8 +207,17 @@ init_LEDs()
while(True): 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? # 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 # Query updated API
trains = (requests.get("https://lapi.transitchicago.com/api/1.0/ttpositions.aspx?key="+APIKEY+"&rt=Blue&outputType=JSON")).json()['ctatt'] 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) stations[nextStation]['eta'].append(eta_time)
last_query = time() # uptime polling window last_api_query = time() # uptime polling window
print(gmtime(last_query))
# Process the ETA for each station # Process the ETA for each station