httpsrv_start.lua 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. --[[
  2. @module httpsrv_start
  3. @summary HTTP服务器应用模块
  4. @version 1.0
  5. @date 2025.10.24
  6. @author 拓毅恒
  7. @usage
  8. 本文件为Air780EHM/Air780EHV/Air780EGH核心板+AirETH_1000配件板演示 HTTP 服务器功能的应用模块,核心业务逻辑为:
  9. 1. 初始化HTTP服务器
  10. 2. 配置HTTP服务器参数
  11. 3. 启动HTTP服务器服务
  12. 4. 处理HTTP请求和响应
  13. ]]
  14. local function handle_http_request(fd, method, uri, headers, body)
  15. log.info("httpsrv", method, uri, body or "")
  16. if uri == "/send/text" then
  17. log.info("Text Request", "Method:", method, "Body Length:", body and #body or 0)
  18. if method == "POST" and body and #body > 0 then
  19. -- 直接打印接收到的文本内容
  20. log.info("Received Text:", body)
  21. return 200, {}, "ok"
  22. end
  23. return 400, {}, "Invalid request"
  24. elseif uri == "/scan/go" then
  25. wlan.scan()
  26. return 200, {}, "ok"
  27. elseif uri == "/scan/list" then
  28. return 200, {["Content-Type"]="application/json"}, (json.encode({data=scan_result, ok=true}))
  29. elseif uri == "/connect" then
  30. if method == "POST" and body and #body > 2 then
  31. local jdata = json.decode(body)
  32. if jdata and jdata.ssid then
  33. sys.timerStart(wlan.connect, 500, jdata.ssid, jdata.passwd)
  34. return 200, {}, "ok"
  35. end
  36. end
  37. return 400, {}, "ok"
  38. elseif uri == "/connok" then
  39. log.info("connok", json.encode({ip=socket.localIP(2)}))
  40. return 200, {["Content-Type"]="application/json"}, json.encode({ip=socket.localIP(2)})
  41. end
  42. return 404, {}, "Not Found" .. uri
  43. end
  44. local function start_http_server()
  45. -- 等待网络就绪事件
  46. sys.waitUntil("CREATE_OK")
  47. local local_ip = socket.localIP(socket.LWIP_ETH)
  48. -- 启动HTTP服务器
  49. httpsrv.start(80, handle_http_request, socket.LWIP_ETH)
  50. log.info("HTTP", "文件服务器已启动,使用AirETH_1000-以太网模式")
  51. log.info("HTTP", "访问地址: http://" .. (local_ip or "192.168.4.1"))
  52. end
  53. local function scan_done_handle()
  54. local result = wlan.scanResult()
  55. scan_result = {}
  56. for k, v in pairs(result) do
  57. log.info("scan", (v["ssid"] and #v["ssid"] > 0) and v["ssid"] or "[隐藏SSID]", v["rssi"], (v["bssid"]:toHex()))
  58. if v["ssid"] and #v["ssid"] > 0 then
  59. table.insert(scan_result, {
  60. ssid = v["ssid"],
  61. rssi = v["rssi"]
  62. })
  63. end
  64. end
  65. log.info("scan", "aplist count:", #scan_result)
  66. end
  67. -- 订阅WiFi扫描完成事件
  68. sys.subscribe("WLAN_SCAN_DONE", scan_done_handle)
  69. sys.taskInit(start_http_server)