add web server
This commit is contained in:
@@ -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)
|
||||||
|
|||||||
109
src/rom/app.py
109
src/rom/app.py
@@ -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():
|
||||||
# 连接成功
|
|
||||||
ip = wifi_manager.get_ip()
|
|
||||||
print(f"WiFi connected successfully, IP address: {ip}")
|
|
||||||
|
|
||||||
# 在这里可以添加主应用程序代码
|
|
||||||
# 例如:启动天气数据获取和显示
|
|
||||||
print("Starting main application...")
|
|
||||||
|
|
||||||
# 示例:保持连接
|
|
||||||
try:
|
|
||||||
while True:
|
|
||||||
# 检查连接状态
|
|
||||||
if not wifi_manager.is_connected():
|
|
||||||
print("WiFi connection lost")
|
|
||||||
break
|
|
||||||
|
|
||||||
# 每3秒报告一次状态
|
|
||||||
time.sleep(3)
|
|
||||||
gc.collect()
|
gc.collect()
|
||||||
print(f"Running normally, IP: {ip}, Free memory: {gc.mem_free()} bytes")
|
print(f'Memory Free: {gc.mem_free()}')
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
def start():
|
||||||
print("User interrupted")
|
if not wifi_manager.connect():
|
||||||
|
|
||||||
finally:
|
|
||||||
wifi_manager.disconnect()
|
|
||||||
print("Application ended")
|
|
||||||
|
|
||||||
else:
|
|
||||||
# 连接失败,启动CaptivePortal进行WiFi配置
|
|
||||||
print("Failed to connect to WiFi, starting CaptivePortal for configuration")
|
print("Failed to connect to WiFi, starting CaptivePortal for configuration")
|
||||||
|
|
||||||
from captive_portal import CaptivePortal
|
from captive_portal import CaptivePortal
|
||||||
|
|
||||||
# 启动CaptivePortal
|
|
||||||
portal = CaptivePortal()
|
portal = CaptivePortal()
|
||||||
|
return portal.start()
|
||||||
|
|
||||||
try:
|
# init web server
|
||||||
if portal.start():
|
from rom.nanoweb import Nanoweb
|
||||||
# clear
|
naw = Nanoweb()
|
||||||
del portal
|
# website top directory
|
||||||
sys.modules.pop("CaptivePortal", None)
|
naw.STATIC_DIR = '/rom/www'
|
||||||
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")
|
|
||||||
|
|
||||||
# 在这里可以添加主应用程序代码
|
# /ping: pong
|
||||||
print("Starting main application...")
|
@naw.route('/ping')
|
||||||
|
async def ping(request):
|
||||||
|
await request.write("HTTP/1.1 200 OK\r\n")
|
||||||
|
await request.write("Content-Type: text\r\n\r\n")
|
||||||
|
await request.write("pong")
|
||||||
|
|
||||||
# 示例:保持连接
|
# /status
|
||||||
try:
|
@naw.route('/status')
|
||||||
while True:
|
async def ping(request):
|
||||||
# 检查连接状态
|
await request.write("HTTP/1.1 200 OK\r\n")
|
||||||
if not wifi_manager.is_connected():
|
await request.write("Content-Type: application/json\r\n\r\n")
|
||||||
print("WiFi connection lost")
|
await request.write(json.dumps({
|
||||||
break
|
'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),
|
||||||
|
}))
|
||||||
|
|
||||||
# 每3秒报告一次状态
|
# create task
|
||||||
time.sleep(3)
|
import uasyncio
|
||||||
gc.collect()
|
loop = uasyncio.get_event_loop()
|
||||||
print(f"Running normally, Free memory: {gc.mem_free()} bytes")
|
loop.create_task(naw.run())
|
||||||
|
|
||||||
except KeyboardInterrupt:
|
# run!
|
||||||
print("User interrupted")
|
print_sysinfo()
|
||||||
|
loop.run_forever()
|
||||||
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()
|
|
||||||
|
|||||||
@@ -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:
|
||||||
|
|||||||
Reference in New Issue
Block a user