11.09.2019, 07:50
Working example:
Code:
if not ready then
copas = require('copas')
socket = require('socket')
udpserver = socket.udp()
udpserver:setsockname('127.0.0.1', 51034)
function udphandler(udpsock)
udpsock = copas.wrap(udpsock)
log('udp connection handler')
while true do
local data, err = udpsock:receive()
if data then
log('received data', data)
end
end
end
function parse(data)
log(data)
end
function sendtcp(command)
if connected then
tcpsock:send(command)
copas.sleep(0.5)
end
end
ready = true
function tcpconnect()
local sock = socket.tcp()
tcpsock = copas.wrap(sock)
tcpsock:settimeout(1)
connected, err = tcpsock:connect('192.168.0.175', 4999)
if connected then
log('connect ok')
sendtcp('#COSMSGS=false\r')
sendtcp('#MODEL?\r')
else
log('connect failed', err)
copas.sleep(1)
end
end
function tcphandler()
while true do
if connected then
local resp, err = tcpsock:receive('*r')
if resp then
local status, data = pcall(parse, resp)
if not status then
log('parse failed', data)
end
elseif err == 'closed' then
log('disconnected')
connected = false
tcpsock:close()
tcpsock = nil
collectgarbage('step')
copas.sleep(1)
end
end
if not connected then
tcpconnect()
end
end
end
copas.addserver(udpserver, udphandler, 0)
copas.addthread(tcphandler)
end
copas.loop()