Search code examples
luamqttesp8266mosquittonodemcu

Cannot connect to MQTT broker from ESP8266


I have installed Mosquitto on my windows machine and it's a MQTT v3.1 broker (downloaded recently from mosquitto.org).

I am trying to connect to broker from ESP8266 and so far I have not been able to connect to the broker. I can connect to a public broker, but not to the broker installed on my machine which is connected to the same wifi network.

I have built the firmware using build-nodemcu service and used master branch. I think it has MQTT v3.1.1.

I came across this question and I guess I have ran into the same situation. Though the cause of the issue has been given, how to get rid of the problem has not been mentioned there.

Can you please suggest how to get rid of this problem?

UPDATE [13-09-2016]
Here is the code I am using:

sensorID = "sen_001"
tgtHost = "192.168.8.101"
tgtPort = "1883"
mqttUserID = "admin"
mqttPass = "word"
mqttTimeOut = 120
topicQueue = "/security"

WIFI_SSID = "Lakmal 4G"
WIFI_PASSWORD = "TF18BNY3M"
WIFI_SIGNAL_MODE = wifi.PHYMODE_N

ESP8266_IP=""
ESP8266_NETMASK=""
ESP8266_GATEWAY=""

if wifi.sta.getip() == nil then
    wifi.setmode(wifi.STATION) 
    wifi.setphymode(WIFI_SIGNAL_MODE)
    wifi.sta.config(WIFI_SSID, WIFI_PASSWORD) 
    wifi.sta.connect()
end

if ESP8266_IP ~= "" then
    wifi.sta.setip({ip=ESP8266_IP,netmask=ESP8266_NETMASK,gateway=ESP8266_GATEWAY})
end

print("IP: " .. wifi.sta.getip())

m = mqtt.Client(sensorID, mqttTimeOut, mqttUserID, mqttPass, 1)
m:lwt("/lwt", "offline", 0, 0)
m:on("connect", function(client) print ("connected") end)
m:on("offline", function(client) print ("offline") end)
m:on("message", function(client, topic, data) 
        print(topic .. ":" ) 
        if data ~= nil then
            print(data)
        end
    end)

m:connect(tgtHost, tgtPort, 0, function(client) print ("connected") end,     
                               function(client, reason) print("failed reason: "..reason) end)

I always get "failed reason: -5" error.

I tested the broker with MQTTLens chrome extension and the broker works nicely.


Solution

  • Sorry, too long for a comment.

    Both the NodeMCU MQTT docs and the SO question you referenced make it clear that you need MQTT 3.1.1, 3.1 won't suffice.

    The Mosquitto website states that

    Eclipse Mosquitto™ is an open source (EPL/EDL licensed) message broker that implements the MQTT protocol versions 3.1 and 3.1.1.

    Yet, you claim that your broker be 3.1 which sounds not to be the whole truth in light of the above statement.

    I'll update this answer if you update your question with more details. You have given neither code nor error messages. That fact that your NodeMCU/Lua code works fine with public brokers is a pretty strong case against your local broker, though.