Skip to content

Instantly share code, notes, and snippets.

@claytantor

claytantor/iot.py

Created Jan 13, 2019
Embed
What would you like to do?
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