订阅主题时我可能会遗漏一些东西但不确定.Below是我的iot python订阅代码,它完美无缺。但是,如果我运行没有订阅代码的代码“myAWSIoTMQTTClient.subscribe(”topic_1“,1,customCallback)”topic_1被发布但是如果尝试访问从python的另一个控制台订阅topic_1它只返回true并且不打印消息从自定义调用back.only如果保持订阅和发布在相同的python控制台它工作,但我尝试它运行订阅并在单独的控制台发布然后它抛出一个错误。换句话说,我如何订阅已创建的主题?
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import time
import argparse
import json
host = "XXXXXXXX.iot.us-east-2.amazonaws.com"
rootCAPath = "root-CA.crt"
certificatePath = "XXXXX.cert.pem"
privateKeyPath = "XXXXX.private.key"
port = 8883
clientId = "sdk-java"
topic = "topic_1"
message_to_print="aws aws_preethi"
def customCallback(client, userdata, message):
print("Received a new message: ")
print(message.payload)
print("from topic: ")
print(message.topic)
print("--------------\n\n")
myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
myAWSIoTMQTTClient.configureEndpoint(host, port)
myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec
# Connect and subscribe to AWS IoT
myAWSIoTMQTTClient.connect()
myAWSIoTMQTTClient.subscribe("topic_1", 1, customCallback)
# Publish to the same topic in a loop forever
loopCount = 0
while True:
message = {}
message['message'] = message_to_print
message['sequence'] = loopCount
messageJson = json.dumps(message)
myAWSIoTMQTTClient.publish(topic, messageJson, 1)
loopCount += 1
time.sleep(10)
我相信你需要为每个运行的脚本实例使用clientId的唯一值,否则第二个运行的实例将断开第一个实例的连接。
来自此论坛帖子:https://forums.aws.amazon.com/thread.jspa?threadID=219513
MQTT客户端ID与AWS IoT中的Thing没有关联。这些客户端ID纯粹是唯一标识MQTT连接。关于MQTT客户端ID需要考虑的一件重要事情是,它们需要在您的AWS账户中的设备之间保持唯一。如果您将客户端连接为“客户端ID 1”,并且第二个客户端使用相同的ID(“客户端ID 1”)连接,则第一个客户端的连接将被强制断开连接。这是MQTT规范的一项功能,可以使客户端产生间歇性连接,从而产生多个MQTT会话。
这样做如下:
# Connect and subscribe to AWS IoT
myAWSIoTMQTTClient.connect()
# Publish to the same topic in a loop forever
loopCount = 0
while True:
myAWSIoTMQTTClient.subscribe("topic_1", 1, customCallback)
message = {}
message['message'] = message_to_print
message['sequence'] = loopCount
messageJson = json.dumps(message)
myAWSIoTMQTTClient.publish(topic, messageJson, 1)
loopCount += 1
time.sleep(1)