为什么我没有从AWS Iot Core接收on_message回调

时间:2020-06-15 20:33:19

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

我试图从aws上订阅的主题中接收消息,我能够发布到该主题,但是我无法在paho-mqtt应用程序中接收到该消息。 在AWS IOT客户端中,它可以完美工作。

我的代码

import ssl

prefix = 'prefix'
uid = 'udi'
aws_region = 'us-west-2'
topic = 'node/test'

client_id = 'myNode'
device_cert = f'{prefix}-certificate.pem.crt'
device_privatekey = f'{prefix}-private.pem.key'
ca_cert = 'AmazonRootCA1.pem'
mqtt_url = f'{uid}.iot.{aws_region}.amazonaws.com'


def on_connect(client, userdata, flags, response_code):
    print(f"Connected with status: {response_code}")
    mqtt.subscribe(topic)

def on_disconnect(client, userdata, response_code):
    if response_code != 0:
        print(f"Unexpected disconnection. With Error code {response_code}")

def on_message(client, userdata, message):
    # print("Received message '" + str(message.payload) + "' on topic '"
    #     + message.topic + "' with QoS " + str(message.qos))
    print(message)

if __name__ == "__main__":
    print ("Loaded MQTT configuration information.")

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

    client.tls_set(ca_cert,
                   certfile = device_cert,
                   keyfile = device_privatekey,
                   cert_reqs = ssl.CERT_REQUIRED,
                   tls_version = ssl.PROTOCOL_TLSv1_2,
                   ciphers = None)

    client.tls_insecure_set(False)
    client.on_connect = on_connect
    client.on_message = on_message

    print ("Connecting to AWS IoT Broker...")
    client.connect(mqtt_url, port = 8883, keepalive=60)
    client.loop_forever()

我的物联网策略: { “ Version”:“ 2012-10-17”, “声明”:[ { “效果”:“允许”, “ Action”:“ iot:Connect”, “资源”:“ arn:aws:iot:us-west-2:account_id:client / myNode” }, { “效果”:“允许”, “ Action”:“ iot:Subscribe”, “资源”:“ arn:aws:iot:us-west-2:account_id:topicfilter / node / test” }, { “效果”:“允许”, “ Action”:“ iot:Receive”, “资源”:“ arn:aws:iot:us-west-2:account_id:topic / node / test” } ] }

PD:出于安全原因,我没有显示我的帐户ID,前缀和UID

1 个答案:

答案 0 :(得分:0)

on_connect()回调中,mqtt.subscribe(topic)应该是client.subscribe(topic)