uart_app.lua 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. --[[
  2. @module uart_app
  3. @summary 串口应用功能模块
  4. @version 1.0
  5. @date 2025.11.03
  6. @author 王世豪
  7. @usage
  8. 本文件为串口应用功能模块,核心业务逻辑为:
  9. 1、打开uart1,波特率115200,数据位8,停止位1,无奇偶校验位;
  10. 2、uart1和pc端的串口工具相连;
  11. 3、从uart1接收到pc端串口工具发送的数据后,通过lora发送;
  12. 4、收到lora数据后,将数据通过uart1发送到pc端串口工具;
  13. 本文件的对外接口有两个:
  14. 1、sys.publish("SEND_DATA_REQ", "uart", read_buf) ,通知lora2_sender 模块发送read_buf数据;
  15. 2、sys.subscribe("LORA_RECV_DATA", recv_data_from_lora_proc),订阅LORA_RECV_DATA消息,处理消息携带的数据;
  16. ]]
  17. -- 使用UART1
  18. local UART_ID = 1
  19. -- 串口接收数据缓冲区
  20. local read_buf = ""
  21. -- 末尾增加回车换行两个字符,通过uart发送出去,方便在PC端换行显示查看
  22. local function recv_data_from_lora_proc(data)
  23. uart.write(UART_ID, data.."\r\n")
  24. end
  25. local function concat_timeout_func()
  26. -- 如果存在尚未处理的串口缓冲区数据;
  27. -- 将数据通过publish通知其他应用功能模块处理;
  28. -- 然后清空本文件的串口缓冲区数据
  29. if read_buf:len() > 0 then
  30. sys.publish("SEND_DATA_REQ", "uart", read_buf)
  31. read_buf = ""
  32. end
  33. end
  34. -- UART1的数据接收中断处理函数,UART1接收到数据时,会执行此函数
  35. local function read()
  36. local s
  37. while true do
  38. -- 非阻塞读取UART1接收到的数据,最长读取1024字节
  39. s = uart.read(UART_ID, 1024)
  40. -- 如果从串口没有读到数据
  41. if not s or s:len() == 0 then
  42. -- 启动50毫秒的定时器,如果50毫秒内没收到新的数据,则处理当前收到的所有数据
  43. -- 这样处理是为了防止将一大包数据拆分成多个小包来处理
  44. -- 例如pc端串口工具下发1100字节的数据,可能会产生将近20次的中断进入到read函数,才能读取完整
  45. -- 此处的50毫秒可以根据自己项目的需求做适当修改,在满足整包拼接完整的前提下,时间越短,处理越及时
  46. sys.timerStart(concat_timeout_func, 50)
  47. -- 跳出循环,退出本函数
  48. break
  49. end
  50. log.info("uart_app.read len", s:len())
  51. -- 将本次从串口读到的数据拼接到串口缓冲区read_buf中
  52. read_buf = read_buf..s
  53. end
  54. end
  55. -- 初始化UART1,波特率115200,数据位8,停止位1
  56. uart.setup(UART_ID, 115200, 8, 1)
  57. -- 注册UART1的数据接收中断处理函数,UART1接收到数据时,会执行read函数
  58. uart.on(UART_ID, "receive", read)
  59. -- 订阅"LORA_RECV_DATA"消息的处理函数recv_data_from_lora_proc
  60. -- 收到"LORA_RECV_DATA"消息后,会执行函数recv_data_from_lora_proc
  61. sys.subscribe("LORA_RECV_DATA", recv_data_from_lora_proc)