20.01.2021, 09:19
Resident script (sleep time = 0), log(msg) will output the received real-time data decoded from JSON.
Code:
if not broker then
require('json')
require('socket')
broker, port = '127.0.0.1', 1883
mclient = require('mosquitto').new()
mclient.ON_CONNECT = function(res, rc, msg)
log('mqtt connect status', res, rc, msg)
if res then
mclient:subscribe('servicelocation/+/realtime')
else
mclient:disconnect()
end
end
mclient.ON_MESSAGE = function(mid, topic, payload)
local msg = json.pdecode(payload)
if type(msg) == 'table' then
log(msg)
end
end
mclient.ON_DISCONNECT = function(...)
log('mqtt disconnect', ...)
mclientfd = nil
end
mclient.ON_ERROR = function(...)
log('callback error', ...)
end
function mconnect()
local fd
mclient:connect(broker, port)
fd = mclient:socket()
-- fd ref is valid
if fd then
mclientfd = fd
end
end
mconnect()
-- run timer every 5 seconds
timer = require('timerfd').new(5)
timerfd = socket.fdmaskset(timer:getfd(), 'r')
end
-- mqtt connected
if mclientfd then
mclientfdset = socket.fdmaskset(mclientfd, mclient:want_write() and 'rw' or 'r')
res, timerstat, mclientstat = socket.selectfds(10, timerfd, mclientfdset)
-- mqtt not connected
else
res, timerstat = socket.selectfds(10, timerfd)
end
if res then
if mclientfd and mclientstat then
if socket.fdmaskread(mclientstat) then
mclient:loop_read()
end
if socket.fdmaskwrite(mclientstat) then
mclient:loop_write()
end
end
if timerstat then
-- clear armed timer
timer:read()
if mclientfd then
mclient:loop_misc()
else
mconnect()
end
end
end