-- this should be loaded with loadfile('A/ptpmsg.lua')() -- can't use dofile, because yield will fail repeat msg=read_usb_msg(10000) if msg then -- print('['..msg..']') cmd = string.match(msg,'^%w+') -- print(cmd) if cmd == "quit" then done = true elseif cmd == "echo" then if write_usb_msg(msg) then print("ok") else print("fail") end elseif cmd == "exec" then f,err=loadstring(string.sub(msg,6)) if f then -- pcall would be safer but anything that yields will fail r={f()} -- put all results in array -- write each result as a message. -- nils before the last real value will be preserved -- unsupported types will trigger an error for i=1,table.maxn(r) do write_usb_msg(r[i]) end else write_usb_msg(err) print("loadstring:"..err) end elseif cmd == "exec1" then f,err=loadstring(string.sub(msg,7)) if f then -- pcall would be safer but anything that yields will fail -- will only return the first result -- intentionally NOT using tostring to verify handling of different types. -- no return value will trigger an error write_usb_msg(f()) else write_usb_msg(err) print("loadstring:"..err) end elseif cmd == "ls" then path = string.sub(msg,4) -- print(path) st,err = os.stat(path) if not st then write_usb_msg("stat failed:"..err) elseif not st.is_dir then write_usb_msg("not a directory") else files,err = os.listdir(path) if not files then write_usb_msg("listdir failed"..err) else s = ''; for i,v in ipairs(files) do s = s .. v .. "\n" end write_usb_msg(s) end end elseif cmd == "lsa" then path = string.sub(msg,5) -- print(path) st,err = os.stat(path) if not st then write_usb_msg("stat failed:"..err) elseif not st.is_dir then write_usb_msg("not a directory") else files,err = os.listdir(path) if not files then write_usb_msg("listdir failed"..err) else for i,v in ipairs(files) do s = path if string.sub(s,-1) ~= '/' then s = s .. '/' end s = s .. v; st,err = os.stat(s) if not st then s = s .. ' ' elseif st.is_dir then s = s .. ' ' elseif st.is_file then s = s .. ' ' .. st.size else s = s .. ' ' end while not write_usb_msg(s,2000) do -- demonstrating write timeout print("w timeout: " .. s); end end end end end -- else -- print("read timeout") end until done