iperf_client.lua 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. --[[
  2. @module iperf_client
  3. @summary iperf客户端模式测试模块
  4. @version 1.0
  5. @date 2025.10.29
  6. @author 拓毅恒
  7. @usage
  8. 本模块演示如何初始化CH390以太网并启动iperf客户端模式进行测试。
  9. 适用于路由器连接场景,设备通过DHCP从路由器获取IP地址。
  10. 1、初始化SPI接口连接CH390
  11. 2、设置CH390驱动和网络参数
  12. 3、配置从路由器获取IP地址
  13. 4、连接到指定的iperf服务器并进行测试
  14. 本文件没有对外接口,直接在 main.lua 中 require "iperf_client" 即可加载运行。
  15. ]]
  16. -- 引入必要的模块
  17. local exnetif = require "exnetif"
  18. -- 配置服务器IP地址(需要根据实际服务器IP进行修改)
  19. local SERVER_IP = "192.168.1.3" -- 这里需要修改为实际的服务器IP地址
  20. -- iperf测试报告处理函数
  21. local function iperf_report_handler(bytes, ms_duration, bandwidth)
  22. -- 转换为Mbps显示
  23. local bandwidth_mbps = bandwidth / 1024 / 1024 * 8
  24. log.info("iperf报告", string.format("数据量: %d bytes, 持续时间: %d ms, 带宽: %.2f Mbps", bytes, ms_duration, bandwidth_mbps))
  25. end
  26. -- iperf客户端任务
  27. local function iperf_client_task()
  28. log.info("iperf测试", "开始初始化网络...")
  29. -- 使用exnetif配置SPI外接以太网芯片CH390H
  30. exnetif.set_priority_order({
  31. {
  32. ETHERNET = {
  33. pwrpin = 140,
  34. tp = netdrv.CH390,
  35. opts = {spi = 1, cs = 12}
  36. }
  37. }
  38. })
  39. -- 等待IP地址获取成功
  40. log.info("iperf测试", "等待获取IP地址...")
  41. -- 设置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. break
  48. end
  49. -- 超时检查
  50. if ip_wait_count <= 0 then
  51. log.error("iperf测试", "获取IP地址超时")
  52. return
  53. end
  54. ip_wait_count = ip_wait_count - 1
  55. sys.wait(1000)
  56. end
  57. -- 等待以太网连接
  58. while not socket.adapter(socket.LWIP_ETH) do
  59. sys.wait(100)
  60. end
  61. log.info("iperf测试", "以太网连接状态: 已连接")
  62. -- 启动客户端模式,连接到指定服务器
  63. log.info("iperf测试", "启动客户端模式")
  64. log.info("iperf测试", "连接到服务器IP:", SERVER_IP, "端口: 5001")
  65. -- 连接服务器
  66. iperf.client(socket.LWIP_ETH, SERVER_IP, 5001)
  67. -- 订阅iperf测试报告事件
  68. sys.subscribe("IPERF_REPORT", iperf_report_handler)
  69. log.info("iperf测试", "测试开始")
  70. -- 设置测试循环次数,共测试2分钟
  71. local test_count = 24
  72. while test_count > 0 do
  73. -- 等待IPERF_REPORT事件,超时时间5秒
  74. local report_received = sys.waitUntil("IPERF_REPORT", 5000)
  75. if report_received then
  76. -- 如果收到报告事件,退出循环
  77. log.info("iperf测试", "收到报告,结束测试")
  78. break
  79. else
  80. -- 如果超时,继续测试
  81. test_count = test_count - 1
  82. log.info("iperf测试", "测试进行中...")
  83. end
  84. end
  85. -- 测试结束
  86. log.info("iperf测试", "测试结束,关闭客户端")
  87. iperf.abort()
  88. end
  89. -- 执行iperf客户端模式测试
  90. sys.taskInit(iperf_client_task)