66 lines
1.3 KiB
Lua
66 lines
1.3 KiB
Lua
MQTT = require("mosquitto")
|
|
mqtt = MQTT.new()
|
|
|
|
local function errLog(msg)
|
|
io.stderr:write(msg)
|
|
end
|
|
|
|
local connected = false
|
|
local broker = "localhost"
|
|
|
|
local onMessage = nil
|
|
local onConnect = nil
|
|
|
|
local function publish(topic,msg,retain)
|
|
retain = retain or false
|
|
mqtt:publish(topic,msg, qos, retain)
|
|
end
|
|
|
|
local function loop()
|
|
local ok,err,msg
|
|
|
|
if connected then
|
|
ok,err,msg = mqtt:loop(0)
|
|
if not ok then
|
|
errLog("MQTT:\t "..msg.."\n")
|
|
if onError then onError(1) end
|
|
connected = false
|
|
end
|
|
else
|
|
ok,err,msg = mqtt:loop(0)
|
|
if not ok then
|
|
if onError then onError(2) end
|
|
errLog("MQTT:\t "..msg.."\n")
|
|
mqtt:connect(broker,1883,5)
|
|
errLog("MQTT:\t Reconnect".."\n")
|
|
end
|
|
end
|
|
end
|
|
|
|
local function subscribe(msg)
|
|
mqtt:subscribe(msg)
|
|
end
|
|
|
|
mqtt.ON_CONNECT = function()
|
|
connected = true
|
|
if onConnect then onConnect() end
|
|
end
|
|
|
|
mqtt.ON_MESSAGE = function(mid, topic, payload)
|
|
if onMessage then onMessage(mid, topic, payload) end
|
|
end
|
|
|
|
local function begin(hostname)
|
|
broker = hostname
|
|
mqtt:connect(broker,1883,5)
|
|
end
|
|
|
|
return {
|
|
begin = begin;
|
|
loop = loop;
|
|
publish = publish;
|
|
subscribe = subscribe;
|
|
onConnect = function(callback) onConnect = callback end;
|
|
onMessage = function(callback) onMessage = callback end;
|
|
onError = function(callback) onError = callback end;
|
|
} |