add web server

This commit is contained in:
2026-01-24 15:25:08 +08:00
parent f8c9f6ff36
commit 8797010206
3 changed files with 48 additions and 90 deletions

View File

@@ -2,7 +2,7 @@ import machine, sys, time
import rom.app import rom.app
try: try:
app.start() rom.app.start()
except Exception as e: except Exception as e:
print("Fatal error in main:") print("Fatal error in main:")
sys.print_exception(e) sys.print_exception(e)

View File

@@ -5,91 +5,54 @@ import gc
import sys import sys
import time import time
import json
import machine import machine
# 使用全局的WiFiManager实例
from wifi_manager import wifi_manager from wifi_manager import wifi_manager
print("Trying to connect to saved WiFi network...")
if wifi_manager.connect(): def print_sysinfo():
# 连接成功 gc.collect()
ip = wifi_manager.get_ip() print(f'Memory Free: {gc.mem_free()}')
print(f"WiFi connected successfully, IP address: {ip}")
# 在这里可以添加主应用程序代码 def start():
# 例如:启动天气数据获取和显示 if not wifi_manager.connect():
print("Starting main application...") print("Failed to connect to WiFi, starting CaptivePortal for configuration")
from captive_portal import CaptivePortal
portal = CaptivePortal()
return portal.start()
# 示例:保持连接 # init web server
try: from rom.nanoweb import Nanoweb
while True: naw = Nanoweb()
# 检查连接状态 # website top directory
if not wifi_manager.is_connected(): naw.STATIC_DIR = '/rom/www'
print("WiFi connection lost")
break
# 每3秒报告一次状态 # /ping: pong
time.sleep(3) @naw.route('/ping')
gc.collect() async def ping(request):
print(f"Running normally, IP: {ip}, Free memory: {gc.mem_free()} bytes") await request.write("HTTP/1.1 200 OK\r\n")
await request.write("Content-Type: text\r\n\r\n")
await request.write("pong")
except KeyboardInterrupt: # /status
print("User interrupted") @naw.route('/status')
async def ping(request):
await request.write("HTTP/1.1 200 OK\r\n")
await request.write("Content-Type: application/json\r\n\r\n")
await request.write(json.dumps({
'time':'{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}'.format(*time.localtime()),
'uptime': str(f'{time.ticks_ms()//1000} sec'),
'memory': str(f'{gc.mem_free()//1000} KB'),
'platform': str(sys.platform),
'version': str(sys.version),
}))
finally: # create task
wifi_manager.disconnect() import uasyncio
print("Application ended") loop = uasyncio.get_event_loop()
loop.create_task(naw.run())
else: # run!
# 连接失败启动CaptivePortal进行WiFi配置 print_sysinfo()
print("Failed to connect to WiFi, starting CaptivePortal for configuration") loop.run_forever()
from captive_portal import CaptivePortal
# 启动CaptivePortal
portal = CaptivePortal()
try:
if portal.start():
# clear
del portal
sys.modules.pop("CaptivePortal", None)
sys.modules.pop("captive_dns", None)
sys.modules.pop("captive_http", None)
sys.modules.pop("server_base", None)
gc.collect()
# CaptivePortal成功配置并连接
print("WiFi configured successfully and connected")
# 在这里可以添加主应用程序代码
print("Starting main application...")
# 示例:保持连接
try:
while True:
# 检查连接状态
if not wifi_manager.is_connected():
print("WiFi connection lost")
break
# 每3秒报告一次状态
time.sleep(3)
gc.collect()
print(f"Running normally, Free memory: {gc.mem_free()} bytes")
except KeyboardInterrupt:
print("User interrupted")
finally:
wifi_manager.disconnect()
print("Application ended")
else:
print("CaptivePortal failed to establish connection")
except KeyboardInterrupt:
print("User interrupted")
finally:
time.sleep(3)
machine.reset()

View File

@@ -36,10 +36,10 @@ async def write(request, data):
async def error(request, code, reason): async def error(request, code, reason):
await request.write("HTTP/1.1 %s %s\r\n\r\n" % (code, reason)) await request.write("HTTP/1.1 %s %s\r\n\r\n" % (code, reason))
await request.write("<h1>%s</h1>" % (reason)) await request.write(str(reason))
async def send_file(request, filename, segment=64, binary=False): async def send_file(request, filename, segment=64, binary=True):
try: try:
with open(filename, 'rb' if binary else 'r') as f: with open(filename, 'rb' if binary else 'r') as f:
while True: while True:
@@ -59,7 +59,7 @@ class Nanoweb:
headers = {} headers = {}
routes = {} routes = {}
assets_extensions = ('html', 'css', 'js') assets_extensions = ('.html', '.css', '.js', '.jpg', '.png', '.gif')
callback_request = None callback_request = None
callback_error = staticmethod(error) callback_error = staticmethod(error)
@@ -166,18 +166,13 @@ class Nanoweb:
else: else:
# 3. Try to load index file # 3. Try to load index file
if request.url in ('', '/'): if request.url in ('', '/'):
await send_file(request, self.INDEX_FILE) await self.generate_output(request, self.INDEX_FILE)
else: else:
# 4. Current url have an assets extension ? # 4. Current url have an assets extension ?
for extension in self.assets_extensions: for extension in self.assets_extensions:
if request.url.endswith('.' + extension): if request.url.endswith(extension):
await send_file( await self.generate_output(
request, request, '%s%s' % (self.STATIC_DIR,request.url),
'%s%s' % (
self.STATIC_DIR,
request.url,
),
binary=True,
) )
break break
else: else: