6 @author Dozingfiretruck
8 --注意:因使用了sys.wait()所有api需要在协程中使用
10 local xmodem = require "xmodem"
11 sys.taskInit(function()
12 xmodem.send(2,115200,"/luadb/test.bin")
20 local sys
= require
"sys"
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
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
, 1024)
43 log.info("xmodem", "uart读取到数据:", data
:toHex())
45 sys
.publish("xmodem", data
)
50 @api xmodem.send(uart_id, uart_br, file_path,type)
51 @number uart_id uart端口号
52 @number uart_br uart波特率
53 @string file_path 文件路径
54 @bool type 1k/128 默认1k
57 xmodem.send(2,115200,"/luadb/test.bin")
60 function xmodem
.send(uart_id
, uart_br
, file_path
, type)
61 local ret
, flen
, cnt
, crc
65 DATA_SIZE
= DATA_SIZE_SOH
68 DATA_SIZE
= DATA_SIZE_STX
70 local XMODEM_SIZE
= 1+FRAME_ID_SIZE
+DATA_SIZE
+CRC_SIZE
72 local xmodem_buff
= zbuff
.create(XMODEM_SIZE
)
73 local data_buff
= zbuff
.create(DATA_SIZE
)
74 local fd
= io
.open(file_path
, "rb")
76 uart
.setup(uart_id
,uart_br
)
77 uart
.on(uart_id
, "receive", uart_cb
)
78 local result
, data
= sys
.waitUntil("xmodem", 12000)
79 if result
and (data
== CRC_CHR
or data
== NAK
) then
82 data_buff
:set(0, CTRLZ
)
83 ret
, flen
= fd
:fill(data_buff
,0,DATA_SIZE
)
84 log.info("xmodem", "发送第", cnt
, "包")
87 crc
= crypto
.crc16("XMODEM",data_buff
)
88 packsn
= (packsn
+1) & 0xff
90 xmodem_buff
[1] = packsn
91 xmodem_buff
[2] = 0xff-xmodem_buff
[1]
92 data_buff
:seek(DATA_SIZE
)
93 xmodem_buff
:copy(3, data_buff
)
94 xmodem_buff
[1027] = crc
>>8
95 xmodem_buff
[1028] = crc
&0xff
96 xmodem_buff
:seek(XMODEM_SIZE
)
97 -- log.info(xmodem_buff:used())
99 uart
.tx(uart_id
, xmodem_buff
)
100 result
, data
= sys
.waitUntil("xmodem", 10000)
101 if result
and data
== ACK
then
103 elseif result
and data
== NAK
then
106 log.info("xmodem", "发送失败")
109 if flen
~= DATA_SIZE
then
110 log.info("xmodem", "文件到头了")
114 log.info("xmodem", "文件到头了")
118 uart
.write(uart_id
, string.char(EOT
))
122 log.info("xmodem", "不支持的起始数据包",data
)
126 log.info("xmodem", "待传输的文件不存在")
133 @api xmodem.close(uart_id)
134 @number uart_id uart端口号
136 -- 执行xmodem传输后, 无论是否传输成功, 都建议关闭xmodem上下文, 也会关闭uart
139 function xmodem
.close(uart_id
)
140 uart
.on(uart_id
, "receive")