require"socket"
cs_client = nil
SUCCESS = 0
FAILURE = 1
--[[
socket_open -
Creates a UDP connection to read the asynchronous events from the pyramid stack
--]]
function socket_open(host_addr)
cs_client=socket.udp()
cs_client:setsockname("127.0.0.1", 9090)
cs_client:settimeout(1)
end
--[[
split -
Uses string pattern matching to put all occurances of 'pattern' into a table
that is returned to the caller.
--]]
function split(str,pattern)
local ret={}
for w in string.gmatch(str,pattern) do
table.insert(ret,w)
end
return ret
end
--[[
spin -
Waits for a single named event, will return failure for the list of provided
named events resulting from failures, and log all other unexpected events.
--]]
function spin( event_name_string, ... )
local event, param1, param2
local expected_event_code = EVENT_CODE[event_name_string]
local failure_codes={}
local end_time = os.time() + 2
local eip_response, error_msg, values={}
-- Save the failure codes in a table
for i, v in ipairs{...} do
table.insert(failure_codes, EVENT_CODE[v])
end
repeat
eip_response, error_msg = cs_client:receive()
if eip_response == nil then
print(error_msg)
return FAILURE
else
values = split(eip_response,"%d+")
event = tonumber(string.format("%d",values[1]))
param1 = tonumber(string.format("%d",values[2]))
param2 = tonumber(string.format("%d",values[3]))
if event == expected_event_code then
return SUCCESS, event, param1, param2
else
if failure_codes[1] ~= nil then
for i,v in ipairs(failure_codes) do
if event == v then
return FAILURE, event, param1, param2
end
end
end
end
ep.error(string.format("Unexpected %d %d %d, Waiting on %s",
event, param1, param2, event_name_string))
end
until (os.time() >= end_time)-- or (stat == QUEUE_EMPTY)
return FAILURE
end