Last active
March 8, 2021 08:51
-
-
Save vhuynen/0e13e7e961048e0966e7b1bc1e47cb89 to your computer and use it in GitHub Desktop.
Simple example of MQTT subscriber using paho.mqtt and SSL Client Authentification for AWS Iot Core
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import ssl | |
import time | |
import datetime | |
import json | |
import logging, traceback | |
import paho.mqtt.client as mqtt | |
IoT_protocol_name = "x-amzn-mqtt-ca" | |
aws_iot_endpoint = "XXXXXXXXXX-ats.iot.us-west-2.amazonaws.com" # <random>.iot.<region>.amazonaws.com | |
url = "https://{}".format(aws_iot_endpoint) | |
ca = "/IoTMailboxPLP/certs/CA/VeriSign-Class-3-Public-Primary-Certification-Authority-G5.pem.crt" | |
cert = "/IoTMailboxPLP/certs/CERT/certificate.pem.crt" | |
private = "/IoTMailboxPLP/certs/KEY/private.pem.key" | |
MQTT_TOPIC = "thing/IoTMailboxPLP" | |
logger = logging.getLogger() | |
logger.setLevel(logging.DEBUG) | |
handler = logging.StreamHandler(sys.stdout) | |
log_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
handler.setFormatter(log_format) | |
logger.addHandler(handler) | |
def ssl_alpn(): | |
try: | |
#debug print opnessl version | |
logger.info("open ssl version:{}".format(ssl.OPENSSL_VERSION)) | |
ssl_context = ssl.create_default_context() | |
ssl_context.set_alpn_protocols([IoT_protocol_name]) | |
ssl_context.load_verify_locations(cafile=ca) | |
ssl_context.load_cert_chain(certfile=cert, keyfile=private) | |
return ssl_context | |
except Exception as e: | |
print("exception ssl_alpn()") | |
raise e | |
# Define on connect event function | |
# We shall subscribe to our Topic in this function | |
def on_connect(mosq, obj, flags, rc): | |
print "Connected!" | |
mqttc.subscribe(MQTT_TOPIC, 0) | |
# Define on_message event function. | |
# This function will be invoked every time, | |
# a new message arrives for the subscribed topic | |
def on_message(mosq, obj, msg): | |
print "Topic: " + str(msg.topic) | |
print "QoS: " + str(msg.qos) | |
print "Payload: " + str(msg.payload) | |
def on_subscribe(mosq, obj, mid, granted_qos): | |
print("Subscribed to Topic: " + | |
MQTT_TOPIC + " with QoS: " + str(granted_qos)) | |
mqttc = mqtt.Client() | |
ssl_context= ssl_alpn() | |
mqttc.tls_set_context(context=ssl_context) | |
# Assign event callbacks | |
mqttc.on_message = on_message | |
mqttc.on_connect = on_connect | |
mqttc.on_subscribe = on_subscribe | |
logger.info("start connect") | |
mqttc.connect(aws_iot_endpoint, port=443) | |
logger.info("connect success") | |
# Continue monitoring the incoming messages for subscribed topic | |
mqttc.loop_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment