iperf_server.lua 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. --[[
  2. @module iperf_server
  3. @summary iperf服务器模式测试模块
  4. @version 1.0
  5. @date 2025.10.29
  6. @author 拓毅恒
  7. @usage
  8. 本模块演示如何初始化CH390以太网并启动iperf服务器模式进行测试。
  9. 适用于路由器连接场景,设备通过DHCP从路由器获取IP地址。
  10. 使用步骤:
  11. 1、初始化SPI接口连接CH390
  12. 2、设置CH390驱动和网络参数
  13. 3、配置从路由器获取IP地址
  14. 4、启动iperf服务器并处理测试结果
  15. 本文件没有对外接口,直接在 main.lua 中 require "iperf_server" 即可加载运行。
  16. ]]
  17. -- 引入必要的模块
  18. local exnetif = require "exnetif"
  19. -- 记录服务器IP
  20. local server_ip = "0.0.0.0"
  21. -- iperf测试报告处理函数
  22. local function iperf_report_handler(bytes, ms_duration, bandwidth)
  23. -- 转换为Mbps显示
  24. local bandwidth_mbps = bandwidth / 1024 / 1024 * 8
  25. log.info("iperf报告", string.format("数据量: %d bytes, 持续时间: %d ms, 带宽: %.2f Mbps", bytes, ms_duration, bandwidth_mbps))
  26. end
  27. -- iperf服务器任务
  28. local function iperf_server_task()
  29. log.info("iperf测试", "开始初始化网络...")
  30. -- 使用exnetif配置SPI外接以太网芯片CH390H
  31. exnetif.set_priority_order({
  32. {
  33. ETHERNET = {
  34. pwrpin = 20,
  35. tp = netdrv.CH390,
  36. opts = {spi = 0, cs = 8}
  37. }
  38. }
  39. })
  40. -- 等待IP地址获取成功
  41. log.info("iperf测试", "等待获取IP地址...")
  42. local ip_wait_count = 60
  43. while true do
  44. local ipv4 = socket.localIP(socket.LWIP_ETH)
  45. if ipv4 and ipv4 ~= "0.0.0.0" then
  46. log.info("iperf测试", "IP获取成功:", ipv4)
  47. server_ip = ipv4
  48. break
  49. end
  50. -- 超时检查
  51. if ip_wait_count <= 0 then
  52. log.error("iperf测试", "获取IP地址超时")
  53. return
  54. end
  55. ip_wait_count = ip_wait_count - 1
  56. sys.wait(1000)
  57. end
  58. -- 等待以太网连接
  59. while not socket.adapter(socket.LWIP_ETH) do
  60. sys.wait(100)
  61. end
  62. log.info("iperf测试", "以太网连接状态: 已连接")
  63. -- 连接到路由器场景,不需要配置DHCP服务器
  64. log.info("iperf测试", "网络配置完成")
  65. -- 订阅iperf测试报告事件
  66. sys.subscribe("IPERF_REPORT", iperf_report_handler)
  67. -- 启动iperf服务器
  68. log.info("iperf测试", "启动服务器模式")
  69. log.info("iperf测试", "服务器IP地址:", server_ip, "端口: 5001")
  70. iperf.server(socket.LWIP_ETH)
  71. sys.wait(2000)
  72. log.info("iperf测试", "服务器已启动,等待客户端连接")
  73. log.info("iperf测试", "请在客户端设备上设置服务器IP地址为:", server_ip)
  74. end
  75. -- 执行iperf服务器模式测试
  76. sys.taskInit(iperf_server_task)