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
, len
)
41 sys
.publish("xmodem", data
)
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
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
61 DATA_SIZE
= DATA_SIZE_SOH
64 DATA_SIZE
= DATA_SIZE_STX
66 local XMODEM_SIZE
= 1+FRAME_ID_SIZE
+DATA_SIZE
+CRC_SIZE
68 local xmodem_buff
= zbuff
.create(XMODEM_SIZE
)
69 local data_buff
= zbuff
.create(DATA_SIZE
)
70 local fd
= io
.open(file_path
, "rb")
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
78 data_buff
:set(0, CTRLZ
)
79 ret
, flen
= fd
:fill(data_buff
,0,DATA_SIZE
)
80 log.info("发送第", cnt
, "包")
83 crc
= crypto
.crc16("XMODEM",data_buff
)
84 packsn
= (packsn
+1) & 0xff
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())
95 uart
.tx(uart_id
, xmodem_buff
)
96 result
, data
= sys
.waitUntil("xmodem", 10000)
97 if result
and data
== ACK
then
99 elseif result
and data
== NAK
then
105 if flen
~= DATA_SIZE
then
114 uart
.write(uart_id
, string.char(EOT
))