local P = {} local m local topic, cid local function p(msg) print("MQTT: "..msg) end local function mq_connected(con) -- p("connected") end local function mq_disconnected(con) -- p("disconnected") m:close() m = nil end local function mq_client_connected(con) p("connected") local majorVer, minorVer, devVer, chipId, flashId, flashSize, flashMode, flashSpeed, buildDate = node.info() payload = '{"version": "'..majorVer..'.'..minorVer..'.'..devVer..'", "chipId":'..chipId..', "flashId":'..flashId..', "flashSize":'..flashSize..', "flashMode":'..flashMode..', "flashSpeed":'..flashSpeed if buildDate then payload = payload..', "buildDate": "'..buildDate..'"' end if node.info_versions then major, minor, dev, buildDate, sdkVersion = node.info_versions() payload = payload..'", versions": {"major": '..major..', "minor": '..minor..', "dev": '..dev..', "buildDate": "'..buildDate..'", "sdk": "'..sdkVersion..'"}' end payload = payload.."}" P.publish("firmware", payload) end function mq_on_timer() -- This crashes the module: -- local status = wifi.sta.status() -- p("checking status, status="..status) local status = wifi.sta.getip() if status and status ~= "0.0.0.0" then if not m then p("connecting") -- client id, keepalive, username, password m = mqtt.Client(cid, 120) m:on("connect", mq_connected) m:on("offline", mq_disconnected) -- host, port, secure, auto_reconnect, function(client), ssl=8883 m:connect("trygvis.io", 1883, 0, 0, mq_client_connected) end else if m then p("Lost wifi connection, disconnecting") m:close() m = nil end end end function P.init(timer_id, client_id) p("Configuring") topic = "/esp8266/"..client_id cid = client_id tmr.alarm(timer_id, 3 * 1000, 1, mq_on_timer) p("Configured") end function P.publish(path, payload) if m then m:publish(topic.."/"..path, payload, 0, 0) end end return P