Я пытаюсь использовать AWS IoT с Python. Я реализую клиент MQTT:
#Exte codigo SOLO SIRVE para escritorio
#NO USARLO en una PYCOM
#
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from pathlib import Path
import time
#
cert_folder=Path("certificados")
# user specified callback function
def customCallback(client, userdata, message):
print("Received a new message: ")
print(message.payload)
print("from topic: ")
print(message.topic)
print("--------------\n\n")
# AWS general configuration
AWS_PORT = 8883
AWS_HOST = '*****.amazonaws.com'
AWS_ROOT_CA = cert_folder / "*****.pem"
AWS_CLIENT_CERT = cert_folder / "*****.cert.pem"
AWS_PRIVATE_KEY = cert_folder / "*****.private.key"
# For certificate based connection
myMQTTClient = AWSIoTMQTTClient("Pycom-client")
# For Websocket connection
# myMQTTClient = AWSIoTMQTTClient("Pycom-client", useWebsocket=True)
# Configurations
# For TLS mutual authentication
myMQTTClient.configureEndpoint(AWS_HOST, 8883)
# For Websocket
# myShadowClient.configureEndpoint(AWS_HOST, 443)
myMQTTClient.configureCredentials(AWS_ROOT_CA, AWS_PRIVATE_KEY, AWS_CLIENT_CERT)
# For Websocket, we only need to configure the root CA
# myMQTTClient.configureCredentials(AWS_ROOT_CA)
myMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz
myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec
myMQTTClient.configureMQTTOperationTimeout(50) # 5 sec
#
if myMQTTClient.connect():
print('AWS connection succeeded')
myMQTTClient.publish("topic_1", "Hola AWS!!!", 0)
# Subscribe to topic
myMQTTClient.subscribe("topic_2", 1, customCallback)
myMQTTClient.disconnect()
#Ciclo principal
while True:
myMQTTClient.connect()
myMQTTClient.publish("topic_1", "Hola AWS!!!", 0)
# Subscribe to topic
myMQTTClient.subscribe("topic_2", 1, customCallback)
myMQTTClient.disconnect()
Однако соединение по-прежнему очень нестабильно. Я очень часто получаю сообщения о тайм-ауте или отказе сервера. Я могу отправить пару сообщений и получить другие. Но получать сообщения по подписке сложно, и я не знаю, следует ли использовать дополнительный код, чтобы улучшить его.