28.09.2020, 06:31
You can use selectfds to check if there's data in udp/tcp socket or when tcp socket is closed.
Code:
--log in--
function log_in()
local ip, port = "192.168.1.61", 1918
client = assert(require('socket').tcp())
client:connect(ip, port)
client:settimeout(0.5)
log("Connecting to Alarm at ip:" .. ip .. ' port: '.. tostring(port)..' at '.. os.date("%H:%M:%S"))
-- log("logging Out of alarm")
client:send(string.char(0x49,0x43,0x08,0x00,0x00,0x00,0x00,0x03))
-- log("logging In")
client:send(string.char(0x49,0x43,0x0D,0x00,0x00,0x00,0x00,0x02,0x01,0x02,0x03,0x04,0xFF))
-- log("Setting alarm timeout")
client:send(string.char(0x49,0x43,0x0A,0x00,0x00,0x00,0x00,0x04,0x70,0x17))
-- log("Turning alarm events on")
client:send(string.char(0x49,0x43,0x0A,0x00,0x00,0x00,0x00,0x06,0x01,0x01))
end
log_in_time = os.time() + 900
log_in()
--udp server for recieving commands from event script
if not server then
server = require('socket').udp()
server:setsockname('127.0.0.1', 5432)
end
sfd = socket.fdmaskset(server:getfd(), 'r')
cfd = socket.fdmaskset(client:getfd(), 'r')
while true do
res, sstat, cstat = socket.selectfds(10, sfd, cfd)
if res then
if sstat then
cmd = server:receive()
if cmd then
log("udp server message", cmd)
end
end
if cstat then
rx, err = client:receive()
if rx then
log("tcp client message", rx)
else
log_in_time = 0
log("tcp client error", err)
end
end
end
if os.time() > log_in_time then
client:close()
log_in()
log_in_time = os.time() + 900
end
end