使用AWS-IOT的MQTT发布/订阅似乎不起作用?

时间:2019-04-10 02:20:27

标签: python amazon-web-services aws-iot

我写了两个程序-Publisher和Subscriber。 但是,我看不到订户正在订阅该主题。 另外,订户没有收到任何消息/有效载荷。 我不确定如何解决此问题?

我已经验证了端点和证书,这似乎还可以。

发布者代码-

import paho.mqtt.client as mqtt
import ssl
import time

# Define variables

MQTT_PORT = 8883
MQTT_KEEPALIVE_INTERVAL = 45
MQTT_TOPIC = "driveLedTopic"


MQTT_HOST = "a3p01azi7xqox0-ats.iot.us-east-2.amazonaws.com"
CA_ROOT_CERT_FILE = "root-CA.crt"
THING_CERT_FILE = "MyFirstThing.cert.pem"
THING_PRIVATE_KEY = "MyFirstThing.private.key"

# Define on_publish event function

def on_publish(client, userdata, mid):
    print "Message Published..."

#Initiate MQTT client
mqttc = mqtt.Client()

# Regiser publish callback function
mqttc.on_publish = on_publish

# Configure TLS Set
mqttc.tls_set(CA_ROOT_CERT_FILE, certfile=THING_CERT_FILE,
              keyfile=THING_PRIVATE_KEY, cert_reqs=ssl.CERT_REQUIRED,
              tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)

# Connect with MQTT Broker
mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)
mqttc.loop_start()

counter = 0

while True:
    print("Publish Message")
    mqttc.publish(MQTT_TOPIC, "Hello User ", qos=1)
    time.sleep(10)

mqttc.disconnect()

用户代码-

import paho.mqtt.client as mqtt
import ssl

# Define Variables

MQTT_PORT = 8883
MQTT_KEEPALIVE_INTERVAL = 45
MQTT_TOPIC = "driveLedTopic"


MQTT_HOST = "a3p01azi7xqox0-ats.iot.us-east-2.amazonaws.com"
CA_ROOT_CERT_FILE = "root-CA.crt"
THING_CERT_FILE = "MyFirstThing.cert.pem"
THING_PRIVATE_KEY = "MyFirstThing.private.key"

# Define on connect event function
# We shall subscribe to our Topic in this function


def on_connect(mosq, obj, rc):
    mqttc.subscribe(MQTT_TOPIC, 0)

# Define on_message event function.
# This function will be invoked every time,
# a new message arrives for the subscribed topic


def on_message(mosq, obj, msg):
    print("Topic: " + str(msg.topic))
    print("QoS: " + str(msg.qos))
    print("Payload: " + str(msg.payoad))



def on_subscribe(mosq, obj, mid, granted_qos):
    print("Subscribed to Topic: ")

# Initiate MQTT Client


mqttc = mqtt.Client()

# Assign event callbacks

mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe

# Configure TLS Set
mqttc.tls_set(CA_ROOT_CERT_FILE, certfile=THING_CERT_FILE,
              keyfile=THING_PRIVATE_KEY, cert_reqs=ssl.CERT_REQUIRED,
              tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)

# Connect with MQTT Broker
mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)


# Continue Monitoring the incoming messages for subscribed topic
mqttc.loop_forever()

0 个答案:

没有答案