Skip to content

Instantly share code, notes, and snippets.

@claytantor
Created January 13, 2019 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save claytantor/d76c893e97b5c7031523e0f380454c90 to your computer and use it in GitHub Desktop.
Save claytantor/d76c893e97b5c7031523e0f380454c90 to your computer and use it in GitHub Desktop.
IOT client using MQTT
#!/usr/bin/env python
# coding: utf-8
import yaml
import os, sys
import time
import logging
import json
# Import SDK packages
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/..'))
# 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)
def make_fullpath(suffix_path):
return os.path.join(os.path.dirname(__file__), suffix_path)
def initIOT(config):
myMQTTClient = AWSIoTMQTTClient(config['iot']['iot_id'])
myMQTTClient.configureEndpoint(config['iot']['mqqt_endpoint'], 8883)
myMQTTClient.configureCredentials(
make_fullpath(config['iot']['credentials']['root_ca_path']),
make_fullpath(config['iot']['credentials']['private_key_path']),
make_fullpath(config['iot']['credentials']['cert_path']))
#myMQTTClient connection configuration
myMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz
myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec
myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec
# Connect and subscribe to AWS IoT
myMQTTClient.connect()
return myMQTTClient
def publish(myMQTTClient, config, messageModel):
print("publishing message to topic:{0}".format(config['iot']['mqqt_led_message_topic']))
messageJson = json.dumps(messageModel)
myMQTTClient.publish(config['iot']['mqqt_led_message_topic'], messageJson, 1)
print('Published topic %s: %s\n' % (config['iot']['mqqt_led_message_topic'], messageJson))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment