|
| 1 | +''' |
| 2 | +/* |
| 3 | + * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"). |
| 6 | + * You may not use this file except in compliance with the License. |
| 7 | + * A copy of the License is located at |
| 8 | + * |
| 9 | + * http://aws.amazon.com/apache2.0 |
| 10 | + * |
| 11 | + * or in the "license" file accompanying this file. This file is distributed |
| 12 | + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either |
| 13 | + * express or implied. See the License for the specific language governing |
| 14 | + * permissions and limitations under the License. |
| 15 | + */ |
| 16 | + ''' |
| 17 | + |
| 18 | +from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient |
| 19 | +import logging |
| 20 | +import time |
| 21 | +import argparse |
| 22 | + |
| 23 | + |
| 24 | +class CallbackContainer(object): |
| 25 | + |
| 26 | + def __init__(self, client): |
| 27 | + self._client = client |
| 28 | + |
| 29 | + def messagePrint(self, client, userdata, message): |
| 30 | + print("Received a new message: ") |
| 31 | + print(message.payload) |
| 32 | + print("from topic: ") |
| 33 | + print(message.topic) |
| 34 | + print("--------------\n\n") |
| 35 | + |
| 36 | + def messageForward(self, client, userdata, message): |
| 37 | + topicRepublish = message.topic + "/republish" |
| 38 | + print("Forwarding message from: %s to %s" % (message.topic, topicRepublish)) |
| 39 | + print("--------------\n\n") |
| 40 | + self._client.publishAsync(topicRepublish, str(message.payload), 1, self.pubackCallback) |
| 41 | + |
| 42 | + def pubackCallback(self, mid): |
| 43 | + print("Received PUBACK packet id: ") |
| 44 | + print(mid) |
| 45 | + print("++++++++++++++\n\n") |
| 46 | + |
| 47 | + def subackCallback(self, mid, data): |
| 48 | + print("Received SUBACK packet id: ") |
| 49 | + print(mid) |
| 50 | + print("Granted QoS: ") |
| 51 | + print(data) |
| 52 | + print("++++++++++++++\n\n") |
| 53 | + |
| 54 | + |
| 55 | +# Read in command-line parameters |
| 56 | +parser = argparse.ArgumentParser() |
| 57 | +parser.add_argument("-e", "--endpoint", action="store", required=True, dest="host", help="Your AWS IoT custom endpoint") |
| 58 | +parser.add_argument("-r", "--rootCA", action="store", required=True, dest="rootCAPath", help="Root CA file path") |
| 59 | +parser.add_argument("-c", "--cert", action="store", dest="certificatePath", help="Certificate file path") |
| 60 | +parser.add_argument("-k", "--key", action="store", dest="privateKeyPath", help="Private key file path") |
| 61 | +parser.add_argument("-w", "--websocket", action="store_true", dest="useWebsocket", default=False, |
| 62 | + help="Use MQTT over WebSocket") |
| 63 | +parser.add_argument("-id", "--clientId", action="store", dest="clientId", default="basicPubSub", |
| 64 | + help="Targeted client id") |
| 65 | +parser.add_argument("-t", "--topic", action="store", dest="topic", default="sdk/test/Python", help="Targeted topic") |
| 66 | + |
| 67 | +args = parser.parse_args() |
| 68 | +host = args.host |
| 69 | +rootCAPath = args.rootCAPath |
| 70 | +certificatePath = args.certificatePath |
| 71 | +privateKeyPath = args.privateKeyPath |
| 72 | +useWebsocket = args.useWebsocket |
| 73 | +clientId = args.clientId |
| 74 | +topic = args.topic |
| 75 | + |
| 76 | +if args.useWebsocket and args.certificatePath and args.privateKeyPath: |
| 77 | + parser.error("X.509 cert authentication and WebSocket are mutual exclusive. Please pick one.") |
| 78 | + exit(2) |
| 79 | + |
| 80 | +if not args.useWebsocket and (not args.certificatePath or not args.privateKeyPath): |
| 81 | + parser.error("Missing credentials for authentication.") |
| 82 | + exit(2) |
| 83 | + |
| 84 | +# Configure logging |
| 85 | +logger = logging.getLogger("AWSIoTPythonSDK.core") |
| 86 | +logger.setLevel(logging.DEBUG) |
| 87 | +streamHandler = logging.StreamHandler() |
| 88 | +formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') |
| 89 | +streamHandler.setFormatter(formatter) |
| 90 | +logger.addHandler(streamHandler) |
| 91 | + |
| 92 | +# Init AWSIoTMQTTClient |
| 93 | +myAWSIoTMQTTClient = None |
| 94 | +if useWebsocket: |
| 95 | + myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True) |
| 96 | + myAWSIoTMQTTClient.configureEndpoint(host, 443) |
| 97 | + myAWSIoTMQTTClient.configureCredentials(rootCAPath) |
| 98 | +else: |
| 99 | + myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId) |
| 100 | + myAWSIoTMQTTClient.configureEndpoint(host, 8883) |
| 101 | + myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath) |
| 102 | + |
| 103 | +# AWSIoTMQTTClient connection configuration |
| 104 | +myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20) |
| 105 | +myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing |
| 106 | +myAWSIoTMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz |
| 107 | +myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec |
| 108 | +myAWSIoTMQTTClient.configureMQTTOperationTimeout(5) # 5 sec |
| 109 | + |
| 110 | +myCallbackContainer = CallbackContainer(myAWSIoTMQTTClient) |
| 111 | + |
| 112 | +# Connect and subscribe to AWS IoT |
| 113 | +myAWSIoTMQTTClient.connect() |
| 114 | + |
| 115 | +# Perform synchronous subscribes |
| 116 | +myAWSIoTMQTTClient.subscribe(topic, 1, myCallbackContainer.messageForward) |
| 117 | +myAWSIoTMQTTClient.subscribe(topic + "/republish", 1, myCallbackContainer.messagePrint) |
| 118 | +time.sleep(2) |
| 119 | + |
| 120 | +# Publish to the same topic in a loop forever |
| 121 | +loopCount = 0 |
| 122 | +while True: |
| 123 | + myAWSIoTMQTTClient.publishAsync(topic, "New Message " + str(loopCount), 1, ackCallback=myCallbackContainer.pubackCallback) |
| 124 | + loopCount += 1 |
| 125 | + time.sleep(1) |
0 commit comments