web_server.py 3.2 KB

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