web_server.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from _thread import stack_size
  2. import uasyncio
  3. import gc
  4. import micropython
  5. from mywifi import wifi_do_work, my_wifi
  6. from MicroWebSrv.microWebSrv import MicroWebSrv
  7. from http_handler import routeHandlers
  8. '''
  9. ` 实例化web服务器对象
  10. ` bindIP='192.168.31.123' 必填。在WiFi已经连接路由器的情况下,填写esp32的ip地址
  11. ` 这个脚本同时支持 Python3.10 代码,测试时填上电脑本机IP地址即可
  12. ` routeHandlers 这是web网页的路由表
  13. - 当浏览器访问 192.168.31.123/test 时,会调用 _httpHandlerTestGet 函数
  14. - 当浏览器点击 summit 时,
  15. - 如 _httpHandlerTestGet 函数中 content 的 html 内容 method="post" 所显示的那样:<form action="/test" method="post" accept-charset="ISO-8859-1">
  16. - 该语句会以 POST 方式请求服务器
  17. - 再经过 routeHandlers 路由到 _httpHandlerTestPost 回调函数,输出函数内 content 的结果返回给浏览器
  18. ` 浏览器直接输入: 192.168.43.67 会出现 index.html 页面(前提是 webPath='MicroWebSrv/www/' 路径设置正常)
  19. - index.html 文件在哪路由?
  20. - 在 MicroWebSrv\microWebSrv.py 文件中,初始化提到:_indexPages,函数 _physPathFromURLPath 调用相关页面
  21. - 理论上这是作者源文件里面的东西,我们可以不用管它,也无法从外部修改,直接使用 WriteResponseFile 函数返回网页文件即可
  22. - `httpResponse.WriteResponseFile(filepath= '/my-html.html',contentType = "text/html",headers = None)`
  23. '''
  24. class MyWebSrv():
  25. _instance = None
  26. def __new__(cls, *args, **kwargs):
  27. if cls._instance is None:
  28. cls._instance = super().__new__(cls)
  29. return cls._instance # 返回的是内存地址
  30. def __init__(self, ip='', webp = '/MicroWebSrv/view') -> None:
  31. self.ip = ip
  32. self.web_path = webp
  33. self.srv = None
  34. def start_server(self, threaded=True):
  35. # import sys
  36. # if sys.platform == 'win32':
  37. # ip_addr = '192.168.43.240'
  38. # web_path = 'MicroWebSrv\web_files'
  39. # else:
  40. # from mywifi import my_wifi
  41. # while not my_wifi.wlan.isconnected():
  42. # pass
  43. # ip_addr = my_wifi.get_wifi_addr()
  44. # web_path = '/MicroWebSrv/web_files'
  45. # print(self.web_path)
  46. # stack_size 必须设置大小,如果不设置当访问网页程序会抛出超出堆栈的异常
  47. stack_size(32768)
  48. self.srv = MicroWebSrv(routeHandlers=routeHandlers, bindIP=self.ip, webPath=self.web_path)
  49. self.srv.Start(threaded=True)
  50. print("start:", self.ip)
  51. web_srv = MyWebSrv()
  52. async def start_server():
  53. uasyncio.create_task(wifi_do_work())
  54. while not my_wifi.wlan.isconnected():
  55. await uasyncio.sleep_ms(100)
  56. # print('wait to wifi connect...')
  57. web_srv.ip = my_wifi.get_wifi_addr()
  58. web_srv.start_server()
  59. while True:
  60. gc.collect()
  61. # print(micropython.mem_info())
  62. await uasyncio.sleep_ms(10000)
  63. if __name__ == '__main__':
  64. uasyncio.run(start_server())
  65. # WebSrv()
  66. # ----------------------------------------------------------------------------