| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- from _thread import stack_size
- import uasyncio
- import gc
- import micropython
- from mywifi import wifi_do_work, my_wifi
- from MicroWebSrv.microWebSrv import MicroWebSrv
- from MicroWebSrv.urls import routeHandlers,_acceptWebSocketCallback
- '''
- ` 实例化web服务器对象
- ` bindIP='192.168.31.123' 必填。在WiFi已经连接路由器的情况下,填写esp32的ip地址
- ` 这个脚本同时支持 Python3.10 代码,测试时填上电脑本机IP地址即可
- ` routeHandlers 这是web网页的路由表
- - 当浏览器访问 192.168.31.123/test 时,会调用 _httpHandlerTestGet 函数
- - 当浏览器点击 summit 时,
- - 如 _httpHandlerTestGet 函数中 content 的 html 内容 method="post" 所显示的那样:<form action="/test" method="post" accept-charset="ISO-8859-1">
- - 该语句会以 POST 方式请求服务器
- - 再经过 routeHandlers 路由到 _httpHandlerTestPost 回调函数,输出函数内 content 的结果返回给浏览器
- ` 浏览器直接输入: 192.168.43.67 会出现 index.html 页面(前提是 webPath='MicroWebSrv/www/' 路径设置正常)
- - index.html 文件在哪路由?
- - 在 MicroWebSrv\microWebSrv.py 文件中,初始化提到:_indexPages,函数 _physPathFromURLPath 调用相关页面
- - 理论上这是作者源文件里面的东西,我们可以不用管它,也无法从外部修改,直接使用 WriteResponseFile 函数返回网页文件即可
- - `httpResponse.WriteResponseFile(filepath= '/my-html.html',contentType = "text/html",headers = None)`
- '''
- class MyWebSrv():
- _instance = None
- def __new__(cls, *args, **kwargs):
- if cls._instance is None:
- cls._instance = super().__new__(cls)
- return cls._instance # 返回的是内存地址
- def __init__(self, ip='', webp = '') -> None:
- self.ip = ip
- self.web_path = webp
- self.srv = None
- def start_server(self, threaded=True):
- # import sys
- # if sys.platform == 'win32':
- # ip_addr = '192.168.43.240'
- # web_path = 'MicroWebSrv\web_files'
- # else:
- # from mywifi import my_wifi
- # while not my_wifi.wlan.isconnected():
- # pass
- # ip_addr = my_wifi.get_wifi_addr()
- # web_path = '/MicroWebSrv/web_files'
- # print(self.web_path)
- # stack_size 必须设置大小,如果不设置当访问网页程序会抛出超出堆栈的异常
- stack_size(32768)
- self.srv = MicroWebSrv(routeHandlers=routeHandlers, bindIP=self.ip, webPath=self.web_path)
- self.srv.Start(threaded=True)
- print("start:", self.ip)
- web_srv = MyWebSrv()
- async def start_server():
- uasyncio.create_task(wifi_do_work())
- while not my_wifi.wlan.isconnected():
- await uasyncio.sleep_ms(100)
- # print('wait to wifi connect...')
- web_srv.ip = my_wifi.get_wifi_addr()
- web_srv.web_path = '/MicroWebSrv/web_files'
- web_srv.start_server()
-
- while True:
- gc.collect()
- # print(micropython.mem_info())
- await uasyncio.sleep_ms(10000)
- if __name__ == '__main__':
- uasyncio.run(start_server())
- # WebSrv()
- # ----------------------------------------------------------------------------
|