Created
December 10, 2019 20:31
-
-
Save TerryE/4f113d84a7947775d0829cd78d1a001d to your computer and use it in GitHub Desktop.
Test Lua uploader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env lua | |
-- Cut-down Lua uploader for testing uart.on('data') functionality | |
local dev = '/dev/ttyUSB0' | |
local px = require "posix" | |
local tt = px.open(dev, px.O_RDWR + px.O_NONBLOCK) or | |
error('Could not open serial port '..dev, 0) | |
local fn = arg[1]:match('[\\/]([^\\/]*)$') or arg[1] | |
local f = io.open(arg[1]) or error("Must specify a valid file",0) | |
local fc = f:read("*a") -- '*' is ignored in Lua 5.3 | |
local null,soh,ack,nack = '\0', '\1','\6','\21' | |
local debug=false | |
print(dev .. ' connected to fd:' .. tt) | |
local function read_tt_until(cmp, timeout) | |
local resp = '' | |
while true do | |
if px.rpoll(tt, timeout) == 0 then | |
return error("Timeout on reading ESP:\n" .. resp, 0) | |
end | |
resp = resp .. px.read(tt, 999) | |
if resp:find(cmp) then | |
if debug then print("< !"..resp.."!") else io.write('.') io.flush() end | |
return resp | |
end | |
end | |
end | |
local function write_read(rec, cmp, timeout) | |
if debug then print("> !"..rec.."!") end | |
px.write(tt, rec) | |
return read_tt_until(cmp, 5000) | |
end | |
local function write_code(lines) | |
for l in lines:gmatch("[^\r\n]+") do | |
write_read(l.."\r\n",'\n>', 1000) | |
end | |
end | |
px.tcsetattr(tt, 0, { | |
cflag = px.B115200 + px.CS8 + px.CLOCAL + px.CREAD, | |
iflag = px.IGNPAR, oflag = px.OPOST, cc = {[px.VTIME] = 0, [px.VMIN] = 1} | |
}) | |
write_read('\n="hel".."lo"\n', '\nhello', 5000) | |
write_code([[ | |
function recv(fn, n) | |
local on,w,f,ack,nack=uart.on,uart.write,file.open(fn, 'w+'),'\6','\21' | |
local function ok(d) w(0, ack) end | |
on('data', 130, function(d) | |
local t,l = d:byte(1,2) | |
if t ~= 1 then w(0, nack); return on('data') end | |
if l >= 0 then f:write(d:sub(3, l+2)); end | |
if l < 128 then f:close(); ok(); return on('data') else ok() end | |
end, 0); ok(); end | |
]]) | |
write_read(('recv("%s",%u)\n'):format(fn, #fc),ack, 1000) | |
for i = 1, #fc, 128 do | |
local rec = fc:sub(i,i+127) | |
local l = #rec | |
rec = soh .. string.char(l) .. rec .. null:rep(128-l) | |
local resp = write_read(rec, ack, 1000) | |
end | |
if #fc % 128 == 0 then write_read(soh..null:rep(129), 1000) end | |
write_code('recv=nil\n') | |
local resp = write_read(("=file.list()['%s']..'b'\n"):format(fn), '\n>', 1000) | |
if resp:find("\n"..#fc..'b') then | |
print('\n'..#fc..' bytes written to '..fn) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment