-- broker = "io.adafruit.com" -- IP or hostname of MQTT broker mqttPort = 1883 -- MQTT port (default 1883) userID = "Your Adafruit account name" -- username for authentication if required userPWD = "Your AIO Key" -- user password if needed for security --LED_PIN1 = 10 -- GPIO-01 LED_PIN1 = 4 -- GPIO-02 -- Wifi credentials SSID = "Your Wifi SSID" -- Wifi SSID wifiPWD = "Your SSID password" -- Wifi password function wifi_connect() wifi.setmode(wifi.STATION) wifi.sta.config(SSID,wifiPWD) wifi.sta.connect() end wifi_connect() -- init mqtt client with keepalive timer 60sec m = mqtt.Client(wifi.sta.getmac(), 60, userID, userPWD) -- setup Last Will and Testament (optional) -- Broker will publish a message with qos = 0, retain = 0, data = "offline" -- to topic "/lwt" if client don't send keepalive packet m:lwt("/lwt", "offline", 0, 0) -- try to reconnect if offline m:on("offline", function(conn) print ("reconnecting...") print(node.heap()) tmr.alarm(1, 10000, 0, function() m:connect(broker, mqqtPort, 0) end) end) -- if connect then subscribe to Topic: userID/f/lamp m:on("connect", function(conn) print ("connected") m:subscribe(userID .. "/f/lamp",0, function(conn) print("subscribe success") end) end) -- on publish message receive event m:on("message", function(conn, topic, data) print(topic .. ":" ) if data ~= nil then print(data) end tmr.stop(2) sw1 = true gpio.mode(LED_PIN1, gpio.OUTPUT) -- Turn on, off or blink the LED if data == "ON" then gpio.write(LED_PIN1, gpio.HIGH) elseif data == "OFF" then gpio.write(LED_PIN1, gpio.LOW) elseif data == "BLINK" then tmr.alarm(2,1000,1,function () if (sw1) then gpio.write(LED_PIN1, gpio.LOW) else gpio.write(LED_PIN1, gpio.HIGH) end sw1 = not sw1 end) end end) -- Connect to the broker tmr.alarm(0, 1000, 1, function() if wifi.sta.status() == 5 then tmr.stop(0) m:connect(broker, mqqtPort, 0, function(conn) print("connected") end) end end)