Mahan
Mahan

Reputation: 441

Not able to connect to AmazonMQ via MQTT protocol using Python(paho.mqtt.python) library

import paho.mqtt.publish as publish
import paho.mqtt.client as mqtt

USERNAME = "admin-user"
PASSWORD = "admin-user@12345"
AUTH = {"username":USERNAME, "password":PASSWORD}
HOSTNAME = "ssl://b-c7d1ea8g-f777-4c71-23a3-2d73088fdb64-1.mq.us-west-2.amazonaws.com"
PORT = 8883
TOPICNAME = "paho/test/single"
PAYLOAD = "Hope Stackoverflow Help Me Resolve This Issue!"

publish.single(TOPICNAME, payload=PAYLOAD, hostname=HOSTNAME, port=PORT, auth=AUTH, protocol=mqtt.MQTTv311, transport="tcp", client_id="", keepalive=60, will=None) # This won't work
# publish.single(TOPICNAME, payload=PAYLOAD, hostname="localhost") # This works!

print('published message payload = ', PAYLOAD)

I am able to connect to AmazonMQ with Java eclipse Paho client, but not able to do same the in Python. It gives me an error "gaierror: [Errno -2] Name or service not known".

The above python code works fine with a locally hosted ActiveMQ MQTT broker and also in stand alone server where I have hosted ActiveMQ MQTT broker. But the same is not working with AmazonMQ broker.

This issue is already mentioned in the issue tracker of Github Paho, but still there is no solution that will help.

Upvotes: 1

Views: 1624

Answers (1)

Lorin Metzger
Lorin Metzger

Reputation: 56

You need to remove the "ssl://" from your host variable, and set a ssl context in order to connect to Amazon-MQ with paho.

context = ssl.create_default_context()
client.tls_set_context(context=context)

Here is a working version of the example posted on your github issue.

import paho.mqtt.client as mqttClient

import time
import ssl

context = ssl.create_default_context()

Connected = False 
broker_address= "b-xxxxxx-acbf-xxxx-xxxx-xxxxx-1.mq.us-east-1.amazonaws.com" # No ssl://
port = 8883
user = "xxxxxx"
password = "xxxxx"

def on_connect(client, userdata, flags, rc):

    if rc == 0:
        print("Connected to broker")
        global Connected                #Use global variable
        Connected = True                #Signal connection  
        client.subscribe("test/data")
    else:
        print("Connection failed")

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

client = mqttClient.Client("Test") #create new instance
client.username_pw_set(user, password=password) #set username and password
client.on_connect=on_connect
client.on_message=on_message
client.tls_set_context(context=context)
client.connect(broker_address, port=port)
client.loop_start()

while Connected != True:
    time.sleep(0.1)

client.publish("test/data", "This is my test msg 123.")
time.sleep(10)

Upvotes: 3

Related Questions