AWS IoT - 主题尝试发布未成功

AWS IoT - No success with publish on topic attempt

我正在测试连接并发布到在 AWS IoT 控制台中创建的事物。我正在使用以下代码:

import paho.mqtt.client as mqtt
import ssl, random
from time import sleep

mqtt_url = "XXXXXX.iot.us-east-2.amazonaws.com"
root_ca = './certs/iotRootCA.pem'
public_crt = './certs/deviceCert.crt'
private_key = './certs/deviceCert.key'

connflag = False

def on_connect(client, userdata, flags, response_code):
    global connflag
    connflag = True
    print("Connected with status: {0}".format(response_code))

def on_publish(client, userdata, mid):
    client.disconnect()

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

if __name__ == "__main__":
    print "Loaded MQTT configuration information."
    print "Endpoint URL: " + mqtt_url
    print "Root Cert: " + root_ca
    print "Device Cert: " + public_crt
    print "Private Key: " + private_key

    client = mqtt.Client("aws_connector")
    client.tls_set(root_ca,
                   certfile = public_crt,
                   keyfile = private_key,
                   cert_reqs = ssl.CERT_REQUIRED,
                   tls_version = ssl.PROTOCOL_TLSv1_2,
                   ciphers = None)

    client.on_connect = on_connect
    client.on_message = on_message

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

    while 1==1:
        sleep(0.5)
        if connflag == True:
            print "Publishing..."
            ap_measurement = random.uniform(25.0, 150.0)
            client.publish("ActivePower", ap_measurement, qos=1)
        else:
            print("Waiting for connection...")

我的政策描述如下:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "iot:Connect",
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": "iot:Publish",
      "Resource": "arn:aws:iot:us-east-2:338639570104:topic/sm1"
    },
    {
      "Effect": "Allow",
      "Action": "iot:Subscribe",
      "Resource": "arn:aws:iot:us-east-2:338639570104:topic/sm1"
    }
  ]
}

显然,连接正常,我得到以下输出:

Loaded MQTT configuration information.
Endpoint URL: XXXXXX.iot.us-east-2.amazonaws.com
Root Cert: ./certs/iotRootCA.pem Device Cert: ./certs/deviceCert.crt > Private Key: ./certs/deviceCert.key
Connecting to AWS IoT Broker...
Connected with status: 0
Publishing...
Publishing...
Publishing...
Publishing...
Connected with status: 0
Publishing...

问题是我没有从发布过程中收到任何消息。难道我做错了什么?是不是少了什么?

确保与您的 IoT 证书关联的 AWS IoT 策略允许在 ActivePower 主题上发布。

目前您的策略只允许您发布主题 sm1。更新为

 {
    "Effect": "Allow",
    "Action": "iot:Publish",
    "Resource": "arn:aws:iot:us-east-2:338639570104:topic/ActivePower"
 }

或者如果这是一个政策问题,作为一种快速而肮脏的故障排除方法添加

{
    "Effect": "Allow",
    "Action": "iot:*",
    "Resource": "*"
}

不建议将这种宽松政策用于生产。

此外,您的订阅策略有错误的资源,如果您要订阅该主题,您需要为 iot:Receive 添加策略声明才能接收消息。

AWS IoT policy resource documentation