add: 添加新的阿里云物联网库-aliyun2库,及搭配的demo, 逐步完善中
[LuatOS.git] / script / libs / xmodem.lua
blob7a6812bf07ca3fa9ff43efe10e9b25b91c81bfa0
1 --[[
2 @module xmodem
3 @summary xmodem 驱动
4 @version 1.0
5 @date 2022.06.01
6 @author Dozingfiretruck
7 @usage
8 --注意:因使用了sys.wait()所有api需要在协程中使用
9 -- 用法实例
10 local xmodem = require "xmodem"
11 sys.taskInit(function()
12 xmodem.send(2,115200,"/luadb/test.bin")
13 while 1 do
14 sys.wait(1000)
15 end
16 end)
18 local xmodem = {}
20 local sys = require "sys"
22 local HEAD
23 local DATA_SIZE
25 local SOH = 0x01 -- Modem数据头 128
26 local STX = 0x02 -- Modem数据头 1K
27 local EOT = 0x04 -- 发送结束
28 local ACK = 0x06 -- 应答
29 local NAK = 0x15 -- 非应答
30 local CAN = 0x18 -- 取消发送
31 local CTRLZ = 0x1A -- 填充
32 local CRC_CHR = 0x43 -- C: ASCII字符C
33 local CRC_SIZE = 2
34 local FRAME_ID_SIZE = 2
35 local DATA_SIZE_SOH = 128
36 local DATA_SIZE_STX = 1024
38 local function uart_cb(id, len)
39 local data = uart.read(id, len)
40 data = data:byte(1,1)
41 sys.publish("xmodem", data)
42 end
44 --[[
45 xmodem 发送文件
46 @api xmodem.send(uart_id, uart_br, file_path,type)
47 @number uart_id uart端口号
48 @number uart_br uart波特率
49 @string file_path 文件路径
50 @bool type 1k/128 默认1k
51 @return bool 发送结果
52 @usage
53 xmodem.send(2,115200,"/luadb/test.bin")
56 function xmodem.send(uart_id, uart_br, file_path,type)
57 local ret, flen, cnt, crc
59 if type then
60 HEAD = SOH
61 DATA_SIZE = DATA_SIZE_SOH
62 else
63 HEAD = STX
64 DATA_SIZE = DATA_SIZE_STX
65 end
66 local XMODEM_SIZE = 1+FRAME_ID_SIZE+DATA_SIZE+CRC_SIZE
67 local packsn = 0
68 local xmodem_buff = zbuff.create(XMODEM_SIZE)
69 local data_buff = zbuff.create(DATA_SIZE)
70 local fd = io.open(file_path, "rb")
71 if fd then
72 uart.setup(uart_id,uart_br)
73 uart.on(uart_id, "receive", uart_cb)
74 local result, data = sys.waitUntil("xmodem", 120000)
75 if result and data == CRC_CHR then
76 cnt = 1
77 while true do
78 data_buff:set(0, CTRLZ)
79 ret, flen = fd:fill(data_buff,0,DATA_SIZE)
80 log.info("发送第", cnt, "包")
81 if flen > 0 then
82 data_buff:seek(0)
83 crc = crypto.crc16("XMODEM",data_buff)
84 packsn = (packsn+1) & 0xff
85 xmodem_buff[0] = 0x02
86 xmodem_buff[1] = packsn
87 xmodem_buff[2] = 0xff-xmodem_buff[1]
88 data_buff:seek(DATA_SIZE)
89 xmodem_buff:copy(3, data_buff)
90 xmodem_buff[1027] = crc>>8
91 xmodem_buff[1028] = crc&0xff
92 xmodem_buff:seek(XMODEM_SIZE)
93 log.info(xmodem_buff:used())
94 :: RESEND ::
95 uart.tx(uart_id, xmodem_buff)
96 result, data = sys.waitUntil("xmodem", 10000)
97 if result and data == ACK then
98 cnt = cnt + 1
99 elseif result and data == NAK then
100 goto RESEND
101 else
102 log.info("发送失败")
103 return false
105 if flen ~= DATA_SIZE then
106 log.info("文件到头了")
107 break
109 else
110 log.info("文件到头了")
111 break
114 uart.write(uart_id, string.char(EOT))
115 fd:close()
116 return true
117 else
118 log.info("不支持",data)
119 return false
121 else
122 log.info("no file")
123 return false
127 return xmodem