Skip to content

Instantly share code, notes, and snippets.

@JD-V
Last active January 29, 2022 16:23
Show Gist options
  • Save JD-V/a035b90dbb2300a04790d8e31983d732 to your computer and use it in GitHub Desktop.
Save JD-V/a035b90dbb2300a04790d8e31983d732 to your computer and use it in GitHub Desktop.
alpn_mqtt.py
from __future__ import print_function
import sys
import ssl
import time
import datetime
import logging, traceback
import paho.mqtt.client as mqtt
IoT_protocol_name = "x-amzn-mqtt-ca"
aws_iot_endpoint = "iot.us-east-1.amazonaws.com" # <random>.iot.<region>.amazonaws.com
url = "https://{}".format(aws_iot_endpoint)
ca = "ca/AmazonRootCA1.pem"
cert = "certs/d72f6936098c78fbf367261a9828ec2752800e4a4d878d187edd83fbd1846c35-certificate.pem.crt"
private = "key/d72f6936098c78fbf367261a9828ec2752800e4a4d878d187edd83fbd1846c35-private.pem.key"
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
if __name__ == '__main__':
topic = "test/date"
try:
mqttc = mqtt.Client()
ssl_context= ssl_alpn()
mqttc.tls_set_context(context=ssl_context)
logger.info("start connect")
mqttc.connect(aws_iot_endpoint, port=443)
logger.info("connect success")
mqttc.loop_start()
while True:
now = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
logger.info("try to publish:{}".format(now))
mqttc.publish(topic, now)
time.sleep(1)
except Exception as e:
logger.error("exception main()")
logger.error("e obj:{}".format(vars(e)))
logger.error("message:{}".format(e.message))
traceback.print_exc(file=sys.stdout)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment