Chapter 5: Scripting
54 Complete example of a Lua script
local ctrl_pos = 1
new_prompt = tostring(resp)
-- Only use the part of the string after the last control
char
for i = 1, string.len(new_prompt) do
if string.sub(new_prompt,i) < " " then ctrl_pos = i end
end
new_prompt = string.sub(new_prompt, ctrl_pos)
if new_prompt == last_prompt then
eq_count = eq_count + 1
else
last_prompt = new_prompt
eq_count = 0
end
end
retries = retries - 1
until eq_count > 2 or retries == 0
if retries == 0 then
return nil
else
return last_prompt
end
end
function read_until_prompt(stream, prompt, timeout_ms)
local retbuf = ""
local pr_found
repeat
local newdata = stream:read(16)
if newdata == nil then
timeout_ms = timeout_ms - 100
else
retbuf = retbuf .. newdata
end
pr_found = string.find(retbuf, make_pattern(prompt) .. "$")
until pr_found or timeout_ms <= 0
return retbuf, pr_found
end
PROMPT = ""
function send_cmd(stream, cmd, extra_char)
1
local resp = ""
local pr
stream:write(cmd .. "\r")
stream:flush()
repeat
local resp_part = ""
resp_part, pr = read_until_prompt(stream, PROMPT, 2000)
1. Send a command and return the response in a single call