dtu_demo.lua 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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
  19. sys_send(d1Name, socket.EVENT, 0)
  20. end
  21. end)
  22. netc = socket.create(socket.ETH0, d1Name)
  23. -- socket.debug(netc, true)
  24. socket.config(netc, nil, nil, nil)
  25. while true do
  26. log.info(rtos.meminfo("sys"))
  27. result = libnet.waitLink(d1Name, 0, netc)
  28. result = libnet.connect(d1Name, 5000, netc, ip, port)
  29. -- result = libnet.connect(d1Name, 5000, netc, "112.125.89.8",34607)
  30. d1Online = result
  31. if result then
  32. log.info("服务器连上了")
  33. libnet.tx(d1Name, 0, netc, "helloworld")
  34. end
  35. while result do
  36. succ, param, _, _ = socket.rx(netc, rx_buff)
  37. if not succ then
  38. log.info("服务器断开了", succ, param, ip, port)
  39. break
  40. end
  41. if rx_buff:used() > 0 then
  42. log.info("收到服务器数据,长度", rx_buff:used())
  43. uart.tx(uart_id, rx_buff)
  44. rx_buff:del()
  45. end
  46. tx_buff:copy(nil, com_buff)
  47. com_buff:del()
  48. if tx_buff:used() > 0 then
  49. result, param = libnet.tx(d1Name, 5000, netc, tx_buff)
  50. end
  51. if not result then
  52. log.info("发送失败了", result, param)
  53. break
  54. end
  55. tx_buff:del()
  56. if com_buff:len() > 4096 then
  57. com_buff:resize(4096)
  58. end
  59. if tx_buff:len() > 1024 then
  60. tx_buff:resize(1024)
  61. end
  62. if rx_buff:len() > 1024 then
  63. rx_buff:resize(1024)
  64. end
  65. log.info(rtos.meminfo("sys"))
  66. result, param = libnet.wait(d1Name, 5000, netc)
  67. if not result then
  68. log.info("服务器断开了", result, param)
  69. break
  70. end
  71. end
  72. d1Online = false
  73. libnet.close(d1Name, 5000, netc)
  74. log.info(rtos.meminfo("sys"))
  75. sys.wait(1000)
  76. end
  77. end
  78. function dtuDemo(uart_id, ip, port)
  79. sysplus.taskInitEx(dtuTask, d1Name, netCB, uart_id, ip, port)
  80. end