ymodem_receive.lua 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. --[[
  2. @module main
  3. @summary ymodem 接收文件应用功能模块
  4. @version 1.0
  5. @date 2025.07.01
  6. @author 杨鹏
  7. @usage
  8. 本文件为Air780EHM核心板演示ymodem功能的代码示例,核心业务逻辑为:
  9. 1. 初始化串口通信
  10. 2. 创建Ymodem处理对象
  11. local ymodem_handler = ymodem.create("/","save.bin")
  12. 3. 启动请求发送任务
  13. uart.write(uartid, "C")
  14. 4. 监听串口数据接收
  15. uart.on(uartid, "receive", ymodem_rx)
  16. 5. 处理Ymodem数据包
  17. local function ymodem_rx(id,len)
  18. ]]
  19. -- 根据实际设备选取不同的uartid
  20. local uartid = 1
  21. --初始化
  22. local result = uart.setup(
  23. uartid,--串口id
  24. 115200,--波特率
  25. 8,--数据位
  26. 1--停止位
  27. )
  28. local taskName = "ymodem_to"
  29. -- 处理未识别的消息
  30. local function ymodem_to_cb(msg)
  31. log.info("ymodem_to_cb", msg[1], msg[2], msg[3], msg[4])
  32. end
  33. -- 定义一个局部变量,用于表示Ymodem协议是否正在运行
  34. local ymodem_running = false
  35. -- 创建一个缓冲区,大小为1024 + 32
  36. local rxbuff = zbuff.create(1024 + 32)
  37. -- 创建一个ymodem处理程序,保存路径为"/",文件名为"save.bin"
  38. local ymodem_handler = ymodem.create("/","save.bin")
  39. -- 定义一个ymodem_to函数,用于发送C字符,并重置ymodem处理程序
  40. local function ymodem_to()
  41. while true do
  42. -- 如果ymodem协议没有在运行,则发送请求;并重置ymodem处理程序
  43. if not ymodem_running then
  44. uart.write(uartid, "C")
  45. ymodem.reset(ymodem_handler)
  46. end
  47. sys.wait(500)
  48. end
  49. end
  50. -- 定义一个ymodem_rx函数,用于接收数据
  51. local function ymodem_rx(id,len)
  52. -- 从uart接收数据到缓冲区
  53. uart.rx(id,rxbuff)
  54. -- 打印缓冲区已使用的大小
  55. log.info(rxbuff:used())
  56. -- 调用ymodem.receive函数,接收数据
  57. local result,ack,flag,file_done,all_done = ymodem.receive(ymodem_handler,rxbuff)
  58. ymodem_running = result
  59. log.info("result:",ymodem_running,ack,flag,file_done,all_done)
  60. rxbuff:del()
  61. if result then
  62. rxbuff:copy(0, ack,flag)
  63. uart.tx(id, rxbuff)
  64. end
  65. -- 所有数据都接收完毕
  66. if all_done then
  67. -- 判断/save.bin文件是否存在
  68. local exists=io.exists("/save.bin")
  69. -- 判断/save.bin文件是否存在,存在则打印日志,显示/save.bin文件大小;不存在则打印日志,显示/save.bin文件不存在
  70. if exists then
  71. log.info("io", "save.bin file exists:", exists)
  72. log.info("io", "save.bin file size:", io.fileSize("/save.bin"))
  73. else
  74. log.info("io", "save.bin file not exists")
  75. end
  76. --ymodem_running置为false,再次开始接收
  77. ymodem_running = false
  78. end
  79. rxbuff:del()
  80. end
  81. -- 监听串口接收事件
  82. uart.on(uartid, "receive", ymodem_rx)
  83. -- 监听串口发送事件
  84. uart.on(uartid, "sent", function(id)
  85. log.info("uart", "sent", id)
  86. end)
  87. --创建并且启动一个task
  88. --运行这个task的主函数ymodem_to
  89. sysplus.taskInitEx(ymodem_to, taskName,ymodem_to_cb)