socket_demo.lua 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. local libnet = require "libnet"
  2. -- 下面演示用阻塞方式做串口透传远程服务器,简单的串口DTU
  3. local d1Online = false
  4. local com_buff = zbuff.create(4096)
  5. local d1Name = "D1_TASK"
  6. local function netCB(msg)
  7. log.info("未处理消息", msg[1], msg[2], msg[3], msg[4])
  8. end
  9. local function dtuTask(uart_id, ip, port)
  10. d1Online = false
  11. local tx_buff = zbuff.create(1024)
  12. local rx_buff = zbuff.create(1024)
  13. local netc
  14. local result, param, is_err
  15. result = uart.setup(uart_id, 115200, 8, 1)
  16. uart.on(uart_id, "receive", function(id, len)
  17. uart.rx(id, com_buff)
  18. if d1Online then -- 如果已经在线了,则发送socket.EVENT消息来打断任务里的阻塞等待状态,让任务循环继续
  19. sysplus.sendMsg(d1Name, socket.EVENT, 0)
  20. end
  21. end)
  22. netc = socket.create(nil, d1Name)
  23. socket.debug(netc, true)
  24. socket.config(netc, nil, nil, nil)
  25. -- socket.config(netc, nil, true)
  26. while true do
  27. log.info(rtos.meminfo("sys"))
  28. result = libnet.waitLink(d1Name, 0, netc)
  29. result = libnet.connect(d1Name, 15000, netc, ip, port)
  30. -- result = libnet.connect(d1Name, 5000, netc, "112.125.89.8",34607)
  31. d1Online = result
  32. if result then
  33. log.info("服务器连上了")
  34. libnet.tx(d1Name, 0, netc, "helloworld")
  35. end
  36. while result do
  37. succ, param, _, _ = socket.rx(netc, rx_buff)
  38. if not succ then
  39. log.info("服务器断开了", succ, param, ip, port)
  40. break
  41. end
  42. if rx_buff:used() > 0 then
  43. log.info("收到服务器数据,长度", rx_buff:used())
  44. uart.tx(uart_id, rx_buff)
  45. rx_buff:del()
  46. end
  47. tx_buff:copy(nil, com_buff)
  48. com_buff:del()
  49. if tx_buff:used() > 0 then
  50. result, param = libnet.tx(d1Name, 15000, netc, tx_buff)
  51. end
  52. if not result then
  53. log.info("发送失败了", result, param)
  54. break
  55. end
  56. tx_buff:del()
  57. if com_buff:len() > 4096 then
  58. com_buff:resize(4096)
  59. end
  60. if tx_buff:len() > 1024 then
  61. tx_buff:resize(1024)
  62. end
  63. if rx_buff:len() > 1024 then
  64. rx_buff:resize(1024)
  65. end
  66. log.info(rtos.meminfo("sys"))
  67. -- 阻塞等待新的消息到来,比如服务器下发,串口接收到数据
  68. result, param = libnet.wait(d1Name, 15000, netc)
  69. if not result then
  70. log.info("服务器断开了", result, param)
  71. break
  72. end
  73. end
  74. d1Online = false
  75. libnet.close(d1Name, 5000, netc)
  76. log.info(rtos.meminfo("sys"))
  77. sys.wait(1000)
  78. end
  79. end
  80. function dtuDemo(uart_id, ip, port)
  81. sysplus.taskInitEx(dtuTask, d1Name, netCB, uart_id, ip, port)
  82. end