Connecting M2MQTT Paho Python Client to AWS IoT

0

I am having difficulty connecting to AWS IoT with the following Python script. I followed AWS IoT Core console and created a Thing and Security Certificate, then created policy and attached it certificate, then attached certificate to a Thing. Eventually I downloaded private key PEM, security certificate PEM and CA certificates (AmazonRootCA1.crt and AmazonCARoot3.crt).

So here is the script - there is no errors generated when I run it - it simply keeps waiting for server response...

Any help or clue would be greatly appreciated. I had no problem connecting to AWS IoT with C# client that I wrote which in addition to CA certificate required private key in .PFX format which I created...

#! /usr/bin/python3.5
import serial
import time
import datetime
import os
import socket
import ssl
import logging
import paho.mqtt.client as mqtt
import sys
print(sys.executable)

def on_disconnect(client, userdata, rc):
if rc==0:
print("client disconnected OK")
client.connected_flag=False
#client.disconnect_flag=True

def on_connect(client, userdata, flags, rc):
if rc==0:
print("Connected OK")
mqtt.Client.connected_flag=True
mqtt.Client.bad_connection_params=False
else:
mqtt.Client.bad_connection_params=True

    if rc==1:  
        print("Failed to connect. Connection refused, unacceptable protocol version. Error Code=", rc)  
    elif rc==2:  
        print("Failed to connect.Connection refused, identifier rejected. Error Code=", rc)  
    elif rc==3:  
        print("Failed to connect.Connection refused, server unavailable. Error Code=", rc)  
    elif rc==4:  
        print("Failed to connect.Connection refused, bad user name or password. Error Code=", rc)  
    elif rc==5:  
        print("Failed to connect.Connection refused, not authorized. Error Code=", rc)  

    rpiclient.loop_stop()  
    sys.exit()  

def on_publish(client, userdata, mid):
if rc==0:
print("Data published OK: ", userdata)
else:
print("Failed to publish data. MessageID=", mid)
pass

broker="xxxxxxxxxxxxxxxx-ats.iot.us-west-2.amazonaws.com"
port=8883

rpiclient = mqtt.Client("GravityStorms", clean_session=True, userdata=None, protocol=MQTTv311, transport="tcp")

caCertPath = "./AmazonRootCA1.crt"
clientCertFilePath = "./xxxxxxxxxx-certificate.pem.crt"
keyFilePath = "./xxxxxxxxxx-private.pem.key"
rpiclient.tls_set(caCertPath,
certfile=clientCertFilePath,
keyfile=keyFilePath,
cert_reqs=ssl.CERT_REQUIRED,
tls_version=ssl.PROTOCOL_TLSv1_2,
ciphers=None)

rpiclient.tls_insecure_set(False)

mqtt.Client.connected_flag = False

mqtt.Client.bad_connection_params=False

rpiclient.on_connect = on_connect

rpiclient.on_publish = on_publish

rpiclient.on_disconnect = on_disconnect

rpiclient.loop_start()

rpiclient.will_set("dwm/position", "Client PahoClient-on-RPi2 had unexpectedly disconnected", 1, True)

try:
print("Connecting to MQTT broker ",broker)
rpiclient.connect(broker, port, keepalive=60)
time.sleep(1)

print("mqtt.Client.connected_flag={}, mqtt.Client.bad_connection_params={}".format(mqtt.Client.connected_flag, mqtt.Client.bad_connection_params))  
while mqtt.Client.connected_flag == False and mqtt.Client.bad_connection_params == False:  
    print("Waiting for connection...");  
    time.sleep(1)  
if mqtt.Client.bad_connection_params == True:  
    rpiclient.loop_stop()  
    sys.exit()  
      

except Exception as ex:
print("Connection to MQTT Broker failed: ", ex)
rpiclient.loop_stop()
sys.exit()

rpiclient.loop_stop()

rpiclient.disconnect()

demandé il y a 5 ans604 vues
2 réponses
0

Hi,
I was able to get your code to connect. I had to comment out the following to get it to work:

#rpiclient.will_set("dwm/position", "Client PahoClient-on-RPi2 had unexpectedly disconnected", 1, True)

I also had to change MQTTv111 to mqtt.MQTTv311 to get it to compile

Working code below....

#! /usr/bin/python3.5
import serial
import time
import datetime
import os
import socket
import ssl
import logging
import paho.mqtt.client as mqtt
import sys
print(sys.executable)

def on_disconnect(rpiclient, userdata, rc):
  if rc==0:
    print("client disconnected OK")
    mqtt.connected_flag=False
    #client.disconnect_flag=True

def on_connect(rpiclient, userdata, flags, rc):
  if rc==0:
    print("Connected OK")
    mqtt.Client.connected_flag=True
    mqtt.Client.bad_connection_params=False
  else:
    mqtt.Client.bad_connection_params=True
    if rc==1:
      print("Failed to connect. Connection refused, unacceptable protocol version. Error Code=", rc)
    elif rc==2:
      print("Failed to connect.Connection refused, identifier rejected. Error Code=", rc)
    elif rc==3:
      print("Failed to connect.Connection refused, server unavailable. Error Code=", rc)
    elif rc==4:
      print("Failed to connect.Connection refused, bad user name or password. Error Code=", rc)
    elif rc==5:
      print("Failed to connect.Connection refused, not authorized. Error Code=", rc)

    rpiclient.loop_stop()
    sys.exit()

def on_publish(rpiclient, userdata, mid, rc):
  if rc==0:
    print("Data published OK: ", userdata)
  else:
    print("Failed to publish data. MessageID=", mid)
  pass

broker="xxxxxxxxxxxxxx-ats.iot.us-east-1.amazonaws.com"
port=8883

rpiclient = mqtt.Client("GravityStorms", clean_session=True, userdata=None, protocol=mqtt.MQTTv311, transport="tcp")

caCertPath = "./root-CA.crt"
clientCertFilePath = "./HomeComputer.cert.pem"
keyFilePath = "./HomeComputer.private.key"

rpiclient.tls_set(caCertPath,
    certfile=clientCertFilePath,
    keyfile=keyFilePath,
    cert_reqs=ssl.CERT_REQUIRED,
    tls_version=ssl.PROTOCOL_TLSv1_2,
    ciphers=None)


rpiclient.tls_insecure_set(False)

mqtt.Client.connected_flag = False

mqtt.Client.bad_connection_params=False

rpiclient.on_connect = on_connect
rpiclient.on_publish = on_publish
rpiclient.on_disconnect = on_disconnect

rpiclient.loop_start()

#rpiclient.will_set("dwm/position", "Client PahoClient-on-RPi2 had unexpectedly disconnected", 1, True)


try:
  print("Connecting to MQTT broker ",broker)
  rpiclient.connect(broker, port, keepalive=60)

  time.sleep(1)
  print("mqtt.Client.connected_flag={}, mqtt.Client.bad_connection_params={}".format(mqtt.Client.connected_flag, mqtt.Client.bad_connection_params))
  while mqtt.Client.connected_flag == False and mqtt.Client.bad_connection_params == False:
    print("Waiting for connection...");
    time.sleep(1)
    if mqtt.Client.bad_connection_params == True:
      rpiclient.loop_stop()
      sys.exit()
except Exception as ex:
  print("Connection to MQTT Broker failed: ", ex)
  rpiclient.loop_stop()
  sys.exit()

rpiclient.loop_stop()
rpiclient.disconnect()

Hope this helps!
-randy

répondu il y a 5 ans
0

Randi,

Wow! That great news. I really appreciate it. I spent enormous amount of time and examine plethora of options, except of course, the one you changed. I will try this today!

EDIT: Worked!

Edited by: securigy2 on Aug 19, 2019 6:50 PM

répondu il y a 5 ans

Vous n'êtes pas connecté. Se connecter pour publier une réponse.

Une bonne réponse répond clairement à la question, contient des commentaires constructifs et encourage le développement professionnel de la personne qui pose la question.

Instructions pour répondre aux questions