Updates for WLED

This commit is contained in:
Isaac OSullivan committed 2026-10-07 19:26:50 +10:00
1 parent bc488d444f
commit 07f5be6fe7
1 file changed
+40 -33
+40 -33
View File
@@ -1,5 +1,5 @@
from time import time, gmtime, mktime,sleep from time import time, gmtime, mktime,sleep
import network, machine, ntptime, sockets, json, requests import network, machine, ntptime, socket, json, requests,neopixel
def time_from_iso(datetime_str): def time_from_iso(datetime_str):
[yyyy, mm, dd] = [int(i) for i in datetime_str.split('T')[0].split('-')] [yyyy, mm, dd] = [int(i) for i in datetime_str.split('T')[0].split('-')]
@@ -10,7 +10,7 @@ def time_from_iso(datetime_str):
def start_ap(): def start_ap():
# Sets up initial captive portal for configuring wifi and basic options # Sets up initial captive portal for configuring wifi and basic options
ap = network.WLAN(network.AP_IF) ap = network.WLAN(network.AP_IF)
ap.active(true) ap.active(True)
ap.config( ap.config(
essid="CTA-Setup", essid="CTA-Setup",
@@ -41,7 +41,9 @@ def save_config(data):
config = { config = {
"SSID": data.get("SSID"), "SSID": data.get("SSID"),
"PASS": data.get("PASS", ""), "PASS": data.get("PASS", ""),
"APIKEY": data.get("APIKEY", "") "APIKEY": data.get("APIKEY", ""),
"LStation": data.get("LStation", ""),
"RStation": data.get("RStation", "")
} }
with open("config.json", "w") as f: with open("config.json", "w") as f:
@@ -140,36 +142,38 @@ def reconnect_wifi():
print('Retrying connection...') print('Retrying connection...')
sleep(2) sleep(2)
def set_LEDs(stations):
# Sets up LEDs and their ports.
for station in stations:
led = machine.Pin(station['led_index'], machine.Pin.OUT)
led.value(station['state'])
# Synchronize time of RTC with NTP # Synchronize time of RTC with NTP
last_ntp_sync = -3700 # Init as more than an hour ago 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) 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 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
distance_half = 30 # Time from station before going 'half' on
stations = {} stations = {}
# Setup Neopixel
p = machine.Pin(20) # connected on pin 20
wled = neopixel.NeoPixel(p,2)
wled[0] = (0,0,0)
wled[1] = (0,0,0)
wled.write()
# Check if already configured and load config for Wifi, API Key etc. # Check if already configured and load config for Wifi, API Key etc.
try: try:
with open("config.json", "r") as f: with open("config.json", "r") as f:
config = json.load(f) config = json.load(f)
APIKEY = config.APIKEY APIKEY = config["APIKEY"]
SSID = config.SSID SSID = config["SSID"]
PASS = config.PASS PASS = config["PASS"]
# Won't scale well for infinite LEDs # Allocate first and second station in demo only
stations["L"] = { 'id':config.LStation, 'eta':[], 'led_index':15, 'state':0 } stations[0] = { 'id':config["LStation"], 'eta':[] }
stations["R"] = { 'id':config.RStation, 'eta':[], 'led_index':16, 'state':0 } stations[1] = { 'id':config["RStation"], 'eta':[] }
# Function sets up LEDs.
set_LEDs()
wlan = network.WLAN(network.STA_IF) wlan = network.WLAN(network.STA_IF)
wlan.active(True) wlan.active(True)
reconnect_wifi() reconnect_wifi()
start_http_server() # Still launch server to allow changing SSID and config
# need to make below multithreaded....
#start_http_server() # Still launch server to allow changing SSID and config
demo = False demo = False
except: except:
# Failed to open file, launch AP mode # Failed to open file, launch AP mode
@@ -196,8 +200,8 @@ while(True):
# 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']
# Query all stations # Query all stations
for station,dict in stations.item(): for station,dict in stations.items():
trains_s = (requests.get(f"https://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key={APIKEY}&mapid={dict['id']}outputType=JSON")).json()['ctatt'] trains_s = (requests.get(f"https://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key={APIKEY}&mapid={dict['id']}&outputType=JSON")).json()['ctatt']
# Timestamps are served in local Chicago time, convert to GMT for simplicity on this side. # Timestamps are served in local Chicago time, convert to GMT for simplicity on this side.
#print(f"Time of poll is: "+str(gmtime(time_from_iso(trains_s['tmst'])+(5*60*60)))) #print(f"Time of poll is: "+str(gmtime(time_from_iso(trains_s['tmst'])+(5*60*60))))
@@ -213,20 +217,23 @@ while(True):
last_api_query = time() # uptime polling window last_api_query = time() # uptime polling window
# Process the ETA for each station # Process the ETA for each station
for station, dict in stations.items(): # loop through all stations for station, value in stations.items(): # loop through all stations
# Set LED state tracker to 0, if no trains, it'll stay 0. for index, eta in enumerate(value['eta']): # multiple trains. Find old trains
stations[station]['state'] = 0 if (eta - time()) < -distance_on: # Remove old trains
for index, eta in enumerate(dict['eta']): # multiple trains. Enumerate is used so we have the index to update the dict itself.
time_from_now = eta - time()
print('Train will arrive at'+dict['name']+' in '+ str(time_from_now) + ' seconds')
if time_from_now < distance_on:
stations[station]['state'] = 1
if time_from_now < -distance_on: # Remove old trains
stations[station]['eta'].pop(index) stations[station]['eta'].pop(index)
# Set Station LED state # Set LED state tracker to 0, if no trains, it'll stay 0.
set_LEDs() eta = min(value['eta'])
time_from_now = eta - time()
print(f"Next train will arrive at {value['id']} in {str(time_from_now)} seconds")
if time_from_now < distance_on:
wled[station] = (255,0,0)
elif time_from_now < distance_half:
wled[station] = (255,100,0)
else:
wled[station] = (0,0,0)
# Once all LEDs updated
wled.write()
sleep(1) sleep(1)