require("Frame") local uid="FF001200" local source="dbzoo.EAP.client" local state="off" publisher = coroutine.create( function() -- define timeout to 6 seconds local timeout = 6000000 -- reference the current coroutine local self = coroutine.running() -- create a queue local queue = {} -- init status to OK local status = "OK" -- init start_time to now local start_time = tmr.now() -- main loop while true do -- wait for status while accepting new items repeat value1, value2 = coroutine.yield() if value2 == nil then -- status if value1 == "CHECK" then if #queue > 0 and tmr.now() - start_time > timeout then status = "TIMEOUT" end else status = value1 end else -- topic + message table.insert(queue, {value1, value2}) end until status ~= "PENDING" -- consume the queue item = table.remove(queue) if item ~= nil then local topic, message = unpack(item) start_time = tmr.now() status = "PENDING" -- publish and set status to OK in callback c:publish(topic, message, 0, 0, function(conn) coroutine.resume(self, "OK") end) end end end ) coroutine.resume(publisher) tmr.alarm(1, 1000, 1, function() coroutine.resume(publisher, "CHECK") end) function heartBeat() print("heartbeat sent. heap: "..node.heap()) local s = string.format([=[ xap-hbeat { v=12 hop=1 uid=%s class=xap-hbeat.alive source=%s interval=60 }]=], uid, source) coroutine.resume(publisher, "dbzoo/EAP/client/xap", s) end function infoEvent(clazz) local msg = string.format([=[ xap-header { v=12 hop=1 uid=%s class=%s source=%s } output.state { state=%s }]=], uid, clazz, source, state) coroutine.resume(publisher, "dbzoo/EAP/client/xap", msg) end print ("Connecting to MQTT broker. Please wait...") print("heap: " .. node.heap() ) c = mqtt.Client("ESPClient", 120, nil, nil) c:on("message", function(con, topic, payload) print("payload received. heap: "..node.heap()) -- local f = Frame:new(payload) -- payload=nil -- local class = f:getValue("xap-header","class") -- if class == "xapBSC.query" then -- infoEvent("xapBSC.info") -- elseif class == "xapBSC.cmd" then -- state = f:getValue("output.state.1","state") -- infoEvent("xapBSC.event") -- end end) c:on("offline", function(con) print("offline") end) c:connect("192.168.1.73",1883,function(con) print("Connected") c:subscribe("dbzoo/EAP/client", 0, function(con) print("subscribe success") end) tmr.alarm(1, 60000, 1, heartBeat) end)