MQTT library - examples for brokers that need usernames and passwords


#1

Greetings!

I see the Zerynth example for using MQTT and connecting to the test.mosquitto.org broker. I want to connect to the cloudmqtt broker.

For cloudmQTT, there is a username and password that must be provided on connection. I don’t see these methods in the Zerynth MQTT class or example - is there another MQTT library that provides these?


#2

Please hve a look at the set_username_pw function in MTQQ Library docs.
As an example:

Blockquote
try:
print(“testing”)
mqtt_c = mqtt.Client(“zerynth-mqtt”,True)
mqtt_c.on_disconnect = on_disconnect

        mqtt_c.set_username_pw("User","Password")
       
        for retry in range(2):
            try:
                mqtt_c.connect("m24.cloudmqtt.com",port=18711)
                break
            except Exception as e:
                print("connecting...")
        print("connected.")
        
        if not mqtt_c:
            print ('mqtt not connected')
        else:
            print ('mqtt connected')
            return
    except Exception as e:
        print ('exception from mqtt: ', e)
        sleep(30)

Let me know if you need further help!


#3

Okay, I’m pretty sure the script IS connecting to my wireless network, but it’s not connecting to the cloudmqtt server. I am using this script for the mqtt connection:

try:
# set the mqtt id to “zerynth-mqtt”
client = mqtt.Client(“zerynth-mqtt”,True)

# and try to connect to "test.mosquitto.org"
client.set_username_pw("my_user","my_password")

for retry in range(10):
    try:
        client.connect("m16.cloudmqtt.com", my_port)
        break
    except Exception as e:
        print("connecting...")
print("connected.")
# subscribe to channels
client.subscribe([["desktop/samples",1]])
client.subscribe([["desktop/others",2]])

In the console, I see these messages:

Establishing Link…

connecting…

connecting…

connecting…

connecting…

connecting…

connecting…

connecting…

connecting…

connecting…

connecting…

connected.
[Even though it isn’t really connected at this point]


#4

Hi @Richard_Tarbell,

are you trying to connect to the MQTT or MQTTs port?
With your implementation you are not setting TLS so you should use the MQTT one.
Let me know


#5

Hi Lorenzo,

CloudMQTT gives me three ports to choose from:
|Port |1xxxxxx|
|SSL Port |2xxxxxx|
|Websockets Port (TLS only) |3xxxxxxx|

–> I am using the “Port” value (1xxxxxx), not SSL, and not Websockets. Is this correct?


#6

Hi @Richard_Tarbell,

yes, it is correct. Anyway I noticed this call:

client.connect("m16.cloudmqtt.com", my_port)

which is not correct since the second parameter is MQTT keepalive time in seconds.
Try to replace it with:

client.connect("m16.cloudmqtt.com", 60, port=my_port)

#7

THANK YOU LorenzoR - it works! I can now see my ESP32 communicating with other devices - thank you for your help!