wifi_sta.lua 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. --[[
  2. @module wifi_sta
  3. @summary wifi_sta模块
  4. @version 1.0
  5. @date 2025.10.20
  6. @author 魏健强
  7. @usage 本文为wifi_sta功能模块,核心逻辑为
  8. 1、模块连接wifi;
  9. 2、发送http请求,测试网络;
  10. 本文件没有对外接口,直接在其他功能模块中require "wifi_sta"就可以加载运行;
  11. ]]
  12. -- wifi的STA相关事件
  13. sys.subscribe("WLAN_STA_INC", function(evt, data)
  14. -- evt 可能的值有: "CONNECTED", "DISCONNECTED"
  15. -- 当evt=CONNECTED, data是连接的AP的ssid, 字符串类型
  16. -- 当evt=DISCONNECTED, data断开的原因, 整数类型
  17. log.info("收到STA事件", evt, data)
  18. end)
  19. function test_sta()
  20. log.info("执行STA连接操作")
  21. wlan.connect("test", "HZ88888888")
  22. -- 等待wifi_sta网络连接成功
  23. while not socket.adapter(socket.LWIP_STA) do
  24. -- 在此处阻塞等待wifi连接成功的消息"IP_READY"
  25. -- 或者等待1秒超时退出阻塞等待状态;
  26. -- 注意:此处的1000毫秒超时不要修改的更长;
  27. sys.waitUntil("IP_READY", 1000)
  28. end
  29. while true do
  30. local code, headers, body = http.request("GET", "https://httpbin.air32.cn/bytes/2048", nil, nil, {adapter=socket.LWIP_STA,timeout=5000,debug=false}).wait()
  31. log.info("http执行结果", code, headers, body and #body)
  32. sys.wait(2000)
  33. end
  34. end
  35. function ip_ready_handle(ip, adapter)
  36. log.info("ip_ready_handle",ip, adapter)
  37. if adapter == socket.LWIP_STA then
  38. log.info("wifi sta 链接成功")
  39. end
  40. end
  41. sys.taskInit(test_sta)
  42. sys.subscribe("IP_READY", ip_ready_handle)