Updates for async

This commit is contained in:
iosullivan committed 2026-10-10 19:28:04 +10:00
1 parent 6f2a926a27
commit 1b781e93bf
3 files changed
+1640 -65

No files matched your search

@@ -0,0 +1,4 @@
from microdot.microdot import Microdot, Request, Response, abort, redirect, \
send_file, URLPattern, AsyncBytesIO, iscoroutine # noqa: F401
__version__ = '2.7.0'
+40 -65
View File
@@ -1,5 +1,8 @@
from time import time, gmtime, mktime,sleep from time import time, gmtime, mktime,sleep
import network, machine, ntptime, socket, json, requests,neopixel import network, machine, ntptime, socket, json, requests,neopixel, asyncio
from microdot import Microdot
app = Microdot()
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('-')]
@@ -51,76 +54,48 @@ def save_config(data):
print("Configuration saved:", config) print("Configuration saved:", config)
def start_http_server(): @app.post('/save')
addr = socket.getaddrinfo("0.0.0.0", 80)[0][-1] async def save(request):
s = socket.socket() # Handle form submission
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) body = request.split("\r\n\r\n", 1)[1]
s.bind(addr) form_data = parse_form_data(body)
s.listen(1) save_config(form_data)
print("HTTP server listening on port 80") response_body = """<!DOCTYPE html>
while True:
try:
conn, addr = s.accept()
request = conn.recv(2048).decode()
if request.startswith("POST /save"):
# Handle form submission
body = request.split("\r\n\r\n", 1)[1]
form_data = parse_form_data(body)
save_config(form_data)
response_body = """<!DOCTYPE html>
<html> <html>
<head> <head>
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Setup Complete</title> <title>Setup Complete</title>
<style> <style>
body { font-family: sans-serif; padding: 16px; text-align: center; } body { font-family: sans-serif; padding: 16px; text-align: center; }
h2 { color: #28a745; } h2 { color: #28a745; }
</style> </style>
</head> </head>
<body> <body>
<h2>Configuration saved</h2> <h2>Configuration saved</h2>
<p>Device will reboot and connect to Wi-Fi.</p> <p>Device will reboot and connect to Wi-Fi.</p>
<p><small>You can close this window.</small></p> <p><small>You can close this window.</small></p>
</body> </body>
</html>""" </html>"""
else:
# Serve the setup page for any other request
try:
with open("portal.html") as f:
response_body = f.read()
except:
response_body = "<h1>Setup Page Not Found</h1><p>Please upload portal.html</p>"
response = ( return response_body
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"Connection: close\r\n\r\n"
+ response_body
)
conn.send(response.encode()) @app.get('/')
async def index(request):
try:
with open("portal.html") as f:
response_body = f.read()
except:
response_body = "<h1>Setup Page Not Found</h1><p>Please upload portal.html</p>"
except Exception as e: response = (
print("HTTP error:", e) "HTTP/1.1 200 OK\r\n"
try: "Content-Type: text/html\r\n"
error = f"<h2>Error</h2><p>{e}</p>" "Connection: close\r\n\r\n"
conn.send( + response_body
"HTTP/1.1 500 Internal Server Error\r\n" )
"Content-Type: text/html\r\n"
"Connection: close\r\n\r\n" return response
.encode() + error.encode()
)
except:
pass
finally:
try:
conn.close()
except:
pass
def reconnect_wifi(): def reconnect_wifi():
while not wlan.isconnected(): while not wlan.isconnected():
@@ -132,7 +107,7 @@ def reconnect_wifi():
break break
max_wait -= 1 max_wait -= 1
print('Waiting for connection...') print('Waiting for connection...')
sleep(1) asyncio.wait(1)
if wlan.isconnected(): if wlan.isconnected():
print('Connected to Wi-Fi') print('Connected to Wi-Fi')
print('Network config:', wlan.ifconfig()) print('Network config:', wlan.ifconfig())
@@ -140,7 +115,7 @@ def reconnect_wifi():
except Exception as e: except Exception as e:
print('Connection error:', e) print('Connection error:', e)
print('Retrying connection...') print('Retrying connection...')
sleep(2) asyncio.wait(2)
# 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
@@ -182,7 +157,7 @@ except:
# Halt waiting for config # Halt waiting for config
while(True): while(True):
sleep(5) asyncio.wait(5)
while(True): while(True):
# Synchronise NTP time if hasn't been done in 1 hour # Synchronise NTP time if hasn't been done in 1 hour
@@ -236,4 +211,4 @@ while(True):
# Once all LEDs updated # Once all LEDs updated
wled.write() wled.write()
sleep(1) asyncio.wait(1)
File diff suppressed because it is too large. Load diff