|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0. |
| 3 | + |
| 4 | +import argparse |
| 5 | +from awscrt import io, mqtt |
| 6 | +from awsiot import mqtt_connection_builder |
| 7 | +import sys |
| 8 | +import threading |
| 9 | +import time |
| 10 | +from uuid import uuid4 |
| 11 | +import json |
| 12 | + |
| 13 | +# This sample is similar to `samples/pubsub.py` but the private key |
| 14 | +# for mutual TLS is stored on a PKCS#11 compatible smart card or |
| 15 | +# Hardware Security Module (HSM). |
| 16 | +# |
| 17 | +# See `samples/README.md` for instructions on setting up your PKCS#11 device |
| 18 | +# to run this sample. |
| 19 | +# |
| 20 | +# WARNING: Unix only. Currently, TLS integration with PKCS#11 is only available on Unix devices. |
| 21 | + |
| 22 | +parser = argparse.ArgumentParser(description="Send and receive messages through and MQTT connection.") |
| 23 | +parser.add_argument('--endpoint', required=True, help="Your AWS IoT custom endpoint, not including a port. " + |
| 24 | + "Ex: \"abcd123456wxyz-ats.iot.us-east-1.amazonaws.com\"") |
| 25 | +parser.add_argument('--port', type=int, help="Specify port. AWS IoT supports 443 and 8883. (default: auto)") |
| 26 | +parser.add_argument('--cert', required=True, help="File path to your client certificate, in PEM format.") |
| 27 | +parser.add_argument('--pkcs11-lib', required=True, help="Path to PKCS#11 library.") |
| 28 | +parser.add_argument('--pin', required=True, help="User PIN for logging into PKCS#11 token.") |
| 29 | +parser.add_argument('--token-label', help="Label of PKCS#11 token to use. (default: None) ") |
| 30 | +parser.add_argument('--slot-id', help="Slot ID containing PKCS#11 token to use. (default: None)") |
| 31 | +parser.add_argument('--key-label', help="Label of private key on the PKCS#11 token. (default: None)") |
| 32 | +parser.add_argument('--root-ca', help="File path to root certificate authority, in PEM format. (default: None)") |
| 33 | +parser.add_argument('--client-id', default="test-" + str(uuid4()), |
| 34 | + help="Client ID for MQTT connection. (default: 'test-*')") |
| 35 | +parser.add_argument('--topic', default="test/topic", |
| 36 | + help="Topic to subscribe to, and publish messages to. (default: 'test/topic')") |
| 37 | +parser.add_argument('--message', default="Hello World!", |
| 38 | + help="Message to publish. Specify empty string to publish nothing. (default: 'Hello World!')") |
| 39 | +parser.add_argument('--count', default=10, type=int, help="Number of messages to publish/receive before exiting. " + |
| 40 | + "Specify 0 to run forever. (default: 10)") |
| 41 | +parser.add_argument('--verbosity', choices=[x.name for x in io.LogLevel], default=io.LogLevel.NoLogs.name, |
| 42 | + help="Logging level. (default: 'NoLogs')") |
| 43 | + |
| 44 | +# Using globals to simplify sample code |
| 45 | +args = parser.parse_args() |
| 46 | + |
| 47 | +io.init_logging(getattr(io.LogLevel, args.verbosity), 'stderr') |
| 48 | + |
| 49 | +received_count = 0 |
| 50 | +received_all_event = threading.Event() |
| 51 | + |
| 52 | + |
| 53 | +def on_connection_interrupted(connection, error, **kwargs): |
| 54 | + # Callback when connection is accidentally lost. |
| 55 | + print("Connection interrupted. error: {}".format(error)) |
| 56 | + |
| 57 | + |
| 58 | +def on_connection_resumed(connection, return_code, session_present, **kwargs): |
| 59 | + # Callback when an interrupted connection is re-established. |
| 60 | + print("Connection resumed. return_code: {} session_present: {}".format(return_code, session_present)) |
| 61 | + |
| 62 | + |
| 63 | +# Callback when the subscribed topic receives a message |
| 64 | +def on_message_received(topic, payload, dup, qos, retain, **kwargs): |
| 65 | + print("Received message from topic '{}': {}".format(topic, payload)) |
| 66 | + global received_count |
| 67 | + received_count += 1 |
| 68 | + if received_count == args.count: |
| 69 | + received_all_event.set() |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == '__main__': |
| 73 | + # Spin up resources |
| 74 | + event_loop_group = io.EventLoopGroup(1) |
| 75 | + host_resolver = io.DefaultHostResolver(event_loop_group) |
| 76 | + client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) |
| 77 | + |
| 78 | + print(f"Loading PKCS#11 library '{args.pkcs11_lib}' ...") |
| 79 | + pkcs11_lib = io.Pkcs11Lib( |
| 80 | + file=args.pkcs11_lib, |
| 81 | + behavior=io.Pkcs11Lib.InitializeFinalizeBehavior.STRICT) |
| 82 | + print("Loaded!") |
| 83 | + |
| 84 | + # Create MQTT connection |
| 85 | + mqtt_connection = mqtt_connection_builder.mtls_with_pkcs11( |
| 86 | + pkcs11_lib=pkcs11_lib, |
| 87 | + user_pin=args.pin, |
| 88 | + slot_id=int(args.slot_id) if args.slot_id else None, |
| 89 | + token_label=args.token_label, |
| 90 | + private_key_label=args.key_label, |
| 91 | + cert_filepath=args.cert, |
| 92 | + endpoint=args.endpoint, |
| 93 | + port=args.port, |
| 94 | + client_bootstrap=client_bootstrap, |
| 95 | + ca_filepath=args.root_ca, |
| 96 | + on_connection_interrupted=on_connection_interrupted, |
| 97 | + on_connection_resumed=on_connection_resumed, |
| 98 | + client_id=args.client_id, |
| 99 | + clean_session=False, |
| 100 | + keep_alive_secs=30) |
| 101 | + |
| 102 | + print("Connecting to {} with client ID '{}'...".format( |
| 103 | + args.endpoint, args.client_id)) |
| 104 | + |
| 105 | + connect_future = mqtt_connection.connect() |
| 106 | + |
| 107 | + # Future.result() waits until a result is available |
| 108 | + connect_future.result() |
| 109 | + print("Connected!") |
| 110 | + |
| 111 | + # Subscribe |
| 112 | + print("Subscribing to topic '{}'...".format(args.topic)) |
| 113 | + subscribe_future, packet_id = mqtt_connection.subscribe( |
| 114 | + topic=args.topic, |
| 115 | + qos=mqtt.QoS.AT_LEAST_ONCE, |
| 116 | + callback=on_message_received) |
| 117 | + |
| 118 | + subscribe_result = subscribe_future.result() |
| 119 | + print("Subscribed with {}".format(str(subscribe_result['qos']))) |
| 120 | + |
| 121 | + # Publish message to server desired number of times. |
| 122 | + # This step is skipped if message is blank. |
| 123 | + # This step loops forever if count was set to 0. |
| 124 | + if args.message: |
| 125 | + if args.count == 0: |
| 126 | + print("Sending messages until program killed") |
| 127 | + else: |
| 128 | + print("Sending {} message(s)".format(args.count)) |
| 129 | + |
| 130 | + publish_count = 1 |
| 131 | + while (publish_count <= args.count) or (args.count == 0): |
| 132 | + message = "{} [{}]".format(args.message, publish_count) |
| 133 | + print("Publishing message to topic '{}': {}".format(args.topic, message)) |
| 134 | + message_json = json.dumps(message) |
| 135 | + mqtt_connection.publish( |
| 136 | + topic=args.topic, |
| 137 | + payload=message_json, |
| 138 | + qos=mqtt.QoS.AT_LEAST_ONCE) |
| 139 | + time.sleep(1) |
| 140 | + publish_count += 1 |
| 141 | + |
| 142 | + # Wait for all messages to be received. |
| 143 | + # This waits forever if count was set to 0. |
| 144 | + if args.count != 0 and not received_all_event.is_set(): |
| 145 | + print("Waiting for all messages to be received...") |
| 146 | + |
| 147 | + received_all_event.wait() |
| 148 | + print("{} message(s) received.".format(received_count)) |
| 149 | + |
| 150 | + # Disconnect |
| 151 | + print("Disconnecting...") |
| 152 | + disconnect_future = mqtt_connection.disconnect() |
| 153 | + disconnect_future.result() |
| 154 | + print("Disconnected!") |
0 commit comments