I made a post last year on how I was finally able to get the ESP to send MQTT data. I had forgotten all about that when I was able to flash the chips again, so I started digging for how to do it. I basically came across the same code somewhere else (can’t remember where), but this time I was able to get send and receiving to work. Decided to share. Once uploaded to the ESP you can see the printed results in the buffer window (I use ESPlorer). Code is below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
broker = "10.0.0.162" -- IP or hostname of IoT service mqttPort = 1883 -- MQTT port (default 1883: non-secure) userID = "" -- blank unless needed userPWD = "" -- blank unless needed --macID = "18fe349e543f" -- MAC address macID = wifi.sta.getmac():gsub(':','') -- set this manually if needed. Just hex digits, no collons/spaces/dashes/etc. clientID = "test-esp8266" -- Client ID count = 0 -- Test number of mqtt_do cycles mqttState = 0 -- State control topicpb = "test/" -- Topic to send data to topicmd = "commands/" -- Topic for subscribing commands -- Wifi credentials SSID = "YOURSSIDE" -- SSID wifiPWD = "yourpassword" -- key -- Connect to WiFi function wifi_connect() wifi.setmode(wifi.STATION) wifi.sta.config(SSID,wifiPWD) wifi.sta.connect() print("MAC address is " .. macID); end -- Start function function mqtt_do() count = count + 1 -- tmr.alarm counter if mqttState < 5 then mqttState = wifi.sta.status() -- State: Waiting for wifi wifi_connect() elseif mqttState == 5 then print("Starting to connect...") m = mqtt.Client(clientID, 120, userID, userPWD) m:on("offline", function(conn) print ("Checking IoT server...") mqttState = 0 -- Starting all over again end) m:on("message", function(conn, topic, data) print(topic .. ":" ) -- receive the commands if data ~= nil then print(data) end end) m:connect(broker , mqttPort, 0, function(conn) print("Connected to " .. broker .. ":" .. mqttPort) mqttState = 20 -- Go to publish state -- To disable send command, comment the next 4 lines of code. m:subscribe(topicmd,0, function(conn) print("Successfully subscribed to command topic.") end) -- end) elseif mqttState == 20 then mqttState = 25 -- Publishing... m:publish(topicpb ,'This is my test message', 0, 0, function(conn) -- Print confirmation of data published print("Sent #"..count.." test messages via MQTT") mqttState = 20 -- Finished publishing - go back to publish state. end) else print("Waiting..."..mqttState) mqttState = mqttState - 1 -- takes us gradually back to publish state to retry end end tmr.alarm(2, 10000, 1, function() mqtt_do() end) -- send data every 10s |