5
respostas

Erro após alterar denominação do tópico

Estou obtendo o mesmo erro já reportado pelo Alessandro. Só funciona com o tópico default "sdk/test/Python". De acordo com o código, há apenas um único parâmetro (topic) para alterar, mas, ao processar a mudança para "telemetria/temperatura" o erro abaixo é apresentado:

" File "aws-iot-device-sdk-python/samples/basicPubSub/basicPubSub.py", line 115, in myAWSIoTMQTTClient.subscribe(topic, 0, customCallback) File "/home/pi/.local/lib/python2.7/site-packages/AWSIoTPythonSDK/MQTTLib.py", line 668, in subscribe return self.mqttcore.subscribe(topic, QoS, callback) File "/home/pi/.local/lib/python2.7/site-packages/AWSIoTPythonSDK/core/protocol/mqtt_core.py", line 302, in subscribe raise subscribeTimeoutException() AWSIoTPythonSDK.exception.AWSIoTExceptions.subscribeTimeoutException "

Poderiam esclarecer o motivo que impede a alteração desda denominação? Manipulando (subscribe/publish) via console AWS tudo funciona 100% e independente da nomenclatura utilizada.

No aguardo.

Att.,

Antonio Brito

5 respostas

Poderia postar seu código para a gente dar uma analisada?

Oi André, claro! Segue abaixo, mas, adianto que é o código default. Só realizei a alteração do nome default do tópico de "sdk/test/Python" para "telemetria/temperatura".

Segue : import os import sys import AWSIoTPythonSDK sys.path.insert(0, os.path.dirname(AWSIoTPythonSDK.file))

Now the import statement should work

from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient

import logging import time import argparse import json

AllowedActions = ['both', 'publish', 'subscribe']

Custom MQTT message callback

def customCallback(client, userdata, message): print("Received a new message: ") print(message.payload) print("from topic: ") print(message.topic) print("--------------\n\n")

Read in command-line parameters

parser = argparse.ArgumentParser() parser.add_argument("-e", "--endpoint", action="store", required=True, dest="host", help="Your AWS IoT custom endpoint") parser.add_argument("-r", "--rootCA", action="store", required=True, dest="rootCAPath", help="Root CA file path") parser.add_argument("-c", "--cert", action="store", dest="certificatePath", help="Certificate file path") parser.add_argument("-k", "--key", action="store", dest="privateKeyPath", help="Private key file path") parser.add_argument("-p", "--port", action="store", dest="port", type=int, help="Port number override") parser.add_argument("-w", "--websocket", action="store_true", dest="useWebsocket", default=False, help="Use MQTT over WebSocket") parser.add_argument("-id", "--clientId", action="store", dest="clientId", default="basicPubSub", help="Targeted client id") parser.add_argument("-t", "--topic", action="store", dest="topic", default="telemetria/temperatura", help="Targeted topic") parser.add_argument("-m", "--mode", action="store", dest="mode", default="both", help="Operation modes: %s"%str(AllowedActions)) parser.add_argument("-M", "--message", action="store", dest="message", default="Hello World!", help="Message to publish")

args = parser.parse_args() host = args.host rootCAPath = args.rootCAPath certificatePath = args.certificatePath privateKeyPath = args.privateKeyPath port = args.port useWebsocket = args.useWebsocket clientId = args.clientId topic = args.topic

if args.mode not in AllowedActions: parser.error("Unknown --mode option %s. Must be one of %s" % (args.mode, str(AllowedActions))) exit(2)

if args.useWebsocket and args.certificatePath and args.privateKeyPath: parser.error("X.509 cert authentication and WebSocket are mutual exclusive. Please pick one.") exit(2)

if not args.useWebsocket and (not args.certificatePath or not args.privateKeyPath): parser.error("Missing credentials for authentication.") exit(2)

Port defaults

if args.useWebsocket and not args.port: # When no port override for WebSocket, default to 443 port = 443 if not args.useWebsocket and not args.port: # When no port override for non-WebSocket, default to 8883 port = 8883

Configure logging

logger = logging.getLogger("AWSIoTPythonSDK.core") logger.setLevel(logging.DEBUG) streamHandler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') streamHandler.setFormatter(formatter) logger.addHandler(streamHandler)

Init AWSIoTMQTTClient

myAWSIoTMQTTClient = None if useWebsocket: myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True) myAWSIoTMQTTClient.configureEndpoint(host, port) myAWSIoTMQTTClient.configureCredentials(rootCAPath) else: 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() if args.mode == 'both' or args.mode == 'subscribe': myAWSIoTMQTTClient.subscribe(topic, 0, customCallback) time.sleep(2)

Publish to the same topic in a loop forever

loopCount = 0 while True: if args.mode == 'both' or args.mode == 'publish': message = {} message['message'] = args.message message['sequence'] = loopCount messageJson = json.dumps(message) myAWSIoTMQTTClient.publish(topic, messageJson, 0) if args.mode == 'publish': print('Published topic %s: %s\n' % (topic, messageJson)) loopCount += 1 time.sleep(1)

Versão 3.5.3 do Python.

pi@raspberrypi:~/iot $ python --version Python 3.5.3

Para facilitar: https://s3.amazonaws.com/aws-iot-device-sdk-python/aws-iot-device-sdk-python-latest.zip

Att.,

Antonio Brito

Estou sem ideias, preciso estudar mais sobre esse assunto. Algum instrutor poderia nos ajudar a chegar nessa solução?

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software