Ejemplo n.º 1
1
 def init_mqtt_client(self):
     endpoint = self.iot_client.describe_endpoint()
     use_websocket = True if self.credentials else False
     endpoint_port = 443 if use_websocket else 8883
     self.mqtt_client = AWSIoTMQTTClient("testo", useWebsocket=use_websocket)
     self.mqtt_client.configureEndpoint(endpoint['endpointAddress'], endpoint_port)
     self.mqtt_client.configureOfflinePublishQueueing(-1)
     self.mqtt_client.configureConnectDisconnectTimeout(10)
     self.mqtt_client.configureMQTTOperationTimeout(10)
     self.configure_credentials()
     log.debug("OpenSSL version {}".format(ssl.OPENSSL_VERSION))
     log.debug("Connecting MQTT client to {} on port {}...".format(endpoint['endpointAddress'], endpoint_port))
     try:
         self.mqtt_client.connect()
         log.debug("MQTT client connected")
     except connectTimeoutException:
         log.error("Failed to connect MQTT client - timeout (check policy)")
         self.mqtt_client = None
Ejemplo n.º 2
1
class Subscriber(threading.Thread):
    """A threaded Subscriber object"""

    def __init__(self, endpoint, root_ca, key, cert, client_id=''):
        threading.Thread.__init__(self)
        self.endpoint = endpoint
        self.client_id = client_id
        self.root_ca = root_ca
        self.key = key
        self.cert = cert
        self._client = None
        self.finish = False
        self.daemon = True
        self.connected = False

    def connect(self):
        self._client = AWSIoTMQTTClient(self.client_id)
        self._client.configureEndpoint(self.endpoint, 8883)
        self._client.configureCredentials(self.root_ca, self.key, self.cert)
        self._client.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
        self._client.configureConnectDisconnectTimeout(10)  # 10 sec
        self._client.configureMQTTOperationTimeout(5)  # 5 sec
        self.connected = self._client.connect()

    def subscribe(self, topic, callback, qos=1):
        if not self.connected:
            self.connect()
        self._client.subscribe(topic, qos, callback)

    def run(self):
        while not self.finish:
            time.sleep(0.001)
def core_connect(device_name, config_file, root_ca, certificate, private_key,
                 group_ca_path):
    global ggd_name, mqttc
    cfg = GroupConfigFile(config_file)
    ggd_name = cfg['devices'][device_name]['thing_name']
    iot_endpoint = cfg['misc']['iot_endpoint']

    dip = DiscoveryInfoProvider()
    dip.configureEndpoint(iot_endpoint)
    dip.configureCredentials(
        caPath=root_ca, certPath=certificate, keyPath=private_key
    )
    dip.configureTimeout(10)  # 10 sec
    logging.info("[button] Discovery using CA:{0} cert:{1} prv_key:{2}".format(
        root_ca, certificate, private_key
    ))

    gg_core, discovery_info = utils.discover_configured_core(
        device_name=device_name, dip=dip, config_file=config_file,
    )
    if not gg_core:
        raise EnvironmentError("[button] Couldn't find the Core")

    ca_list = discovery_info.getAllCas()
    group_id, ca = ca_list[0]
    group_ca_file = utils.save_group_ca(ca, group_ca_path, group_id)

    mqttc = AWSIoTMQTTClient(ggd_name)
    # local Greengrass Core discovered, now connect to Core from this Device
    log.info("[button] gca_file:{0} cert:{1}".format(
        group_ca_file, certificate))
    mqttc.configureCredentials(group_ca_file, private_key, certificate)
    mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)

    return mqttc, gg_core
Ejemplo n.º 4
0
 def __init__(self):
     config = {}
     # read the config file
     try:
         config_file = open('./config/aws-iot.json')
         # parse the content into dictionary
         config = json.loads(config_file.read())
     except FileNotFoundError:
         print("file not found")
         raise
     
     # connect to iot
     try:
         self.client = AWSIoTMQTTClient(config["client"])
         self.client.configureEndpoint(config["host"], config["port"])
         self.client.configureCredentials(config["root-ca"], config["private-key"], config["certificate"])
         self.client.connect()
     except KeyError:
         print("Key not found")
         raise
     except (exception.operationTimeoutException, exception.operationError) as err:
         print(err)
         raise
     except:
         print("unknown error")
Ejemplo n.º 5
0
    def __init__(self, thing_name, cli, thing, cfg, args=(), kwargs={}):
        super(ElfThread, self).__init__(
            name=thing_name, args=args, kwargs=kwargs
        )
        self.thing_name = thing_name
        self.thing = thing
        self.root_cert = cli.root_cert
        self.topic = '{0}/{1}'.format(cli.topic, self.thing_name)

        self.region = cli.region
        self.cfg = cfg
        self.duration = cli.duration
        self.aws_iot = _get_iot_session(self.region, cli.profile_name)
        self.message_qos = cli.qos

        if policy_name_key not in thing.keys():
            policy_name, policy_arn = _create_and_attach_policy(
                self.region, self.topic,
                self.thing_name, self.thing['certificateArn'],
                cli
            )
            self.policy_name = policy_name
            self.policy_arn = policy_arn
            log.debug("[elf_thread] attached policy on cert:{0}".format(
                thing['certificateArn']))
        else:
            log.debug("[elf_thread] policy_name:{0} exists.".format(
                policy_name_key))
            self.policy_name = thing[policy_name_key]
            self.policy_arn = thing[policy_arn_key]

        # setup MQTT client
        elf_id = uuid.UUID(cfg[elf_id_key])

        # use ELF ID and a random string since we must use unique Client ID per
        # client.
        cid = elf_id.urn.split(":")[2] + "_" + make_string(3)

        self.mqttc = AWSIoTMQTTClient(clientID=cid)

        t_name = cfg_dir + thing_name_template.format(0)
        endpoint = self.aws_iot.describe_endpoint()
        log.info("ELF connecting asynchronously to IoT endpoint:'{0}'".format(
            endpoint['endpointAddress']))
        self.mqttc.configureEndpoint(
            hostName=endpoint['endpointAddress'], portNumber=AWS_IOT_MQTT_PORT
        )
        self.mqttc.configureCredentials(
            CAFilePath=self.root_cert,
            KeyPath=t_name + ".prv",
            CertificatePath=t_name + ".pem"
        )
        self.mqttc.configureAutoReconnectBackoffTime(1, 128, 20)
        self.mqttc.configureOfflinePublishQueueing(90, DROP_OLDEST)
        self.mqttc.configureDrainingFrequency(3)
        self.mqttc.configureConnectDisconnectTimeout(20)
        self.mqttc.configureMQTTOperationTimeout(5)

        self.mqttc.connect()  # keepalive default at 30 seconds
Ejemplo n.º 6
0
 def connect(self):
     self._client = AWSIoTMQTTClient(self.client_id)
     self._client.configureEndpoint(self.endpoint, 8883)
     self._client.configureCredentials(self.root_ca, self.key, self.cert)
     self._client.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
     self._client.configureConnectDisconnectTimeout(10)  # 10 sec
     self._client.configureMQTTOperationTimeout(5)  # 5 sec
     self.connected = self._client.connect()
Ejemplo n.º 7
0
if not args.useWebsocket and not args.port:  # When no port override for non-WebSocket, default to 8883
    port = 8883

# 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)

# Init AWSIoTMQTTClient
myAWSIoTMQTTClient = None
if useWebsocket:
    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True)
    myAWSIoTMQTTClient.configureEndpoint(host, port)
    myAWSIoTMQTTClient.configureCredentials(rootCAPath)
else:
    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
    myAWSIoTMQTTClient.configureEndpoint(host, port)
    myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath,
                                            certificatePath)

# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(
    -1)  # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec
Ejemplo n.º 8
0
    except BaseException as e:
        print("Error in discovery!")
        print("Type: %s" % str(type(e)))
        # print("Error message: %s" % e.message)
        retryCount -= 1
        print("\n%d/%d retries left\n" % (retryCount, MAX_DISCOVERY_RETRIES))
        print("Backing off...\n")
        backOffCore.backOff()

if not discovered:
    print("Discovery failed after %d retries. Exiting...\n" %
          (MAX_DISCOVERY_RETRIES))
    sys.exit(-1)

# Iterate through all connection options for the core and use the first successful one
myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
myAWSIoTMQTTClient.configureCredentials(groupCA, privateKeyPath,
                                        certificatePath)
myAWSIoTMQTTClient.onMessage = customOnMessage

connected = False
for connectivityInfo in coreInfo.connectivityInfoList:
    currentHost = connectivityInfo.host
    currentPort = connectivityInfo.port
    print("Trying to connect to core at %s:%d" % (currentHost, currentPort))
    myAWSIoTMQTTClient.configureEndpoint(currentHost, currentPort)
    try:
        myAWSIoTMQTTClient.connect()
        connected = True
        break
    except BaseException as e:
Ejemplo n.º 9
0
def customPubackCallback(mid):
    print("Received PUBACK packet id: ")
    print(mid)
    print("++++++++++++++\n\n")


# 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)

myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId2)
myAWSIoTMQTTClient.configureEndpoint(endpoint, 8883)
myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath,
                                        certificatePath)

# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 600, 300)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(
    -1)  # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(600)  # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec
myAWSIoTMQTTClient.onMessage = customOnMessage

# Connect and subscribe to AWS IoT
myAWSIoTMQTTClient.connect()
Ejemplo n.º 10
0
def awsConfig():
    """
    connect to AWS
    """
    host = "a1x0fiabery709-ats.iot.us-east-2.amazonaws.com"
    rootCAPath = "cert/root-CA.pem"
    certificatePath = "cert/4ad4027780-certificate.pem.crt"
    privateKeyPath = "cert/4ad4027780-private.pem.key"
    port = 8883
    clientId = "TEST_COMM"
    upstream_topic = "$aws/things/cse521/shadow/message_to_iot"
    downstream_topic = "$aws/things/cse521/shadow/message_to_pi"

    # myAWSIoTMQTTClient = None
    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
    myAWSIoTMQTTClient.configureEndpoint(host, port)
    myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath,
                                            certificatePath)

    myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
    myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1)
    myAWSIoTMQTTClient.configureDrainingFrequency(2)
    myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)
    myAWSIoTMQTTClient.configureMQTTOperationTimeout(awsSendPeriod)  # 5 sec

    # Connect and subscribe to AWS IoT
    myAWSIoTMQTTClient.on_connect = on_connect
    myAWSIoTMQTTClient.on_message = on_message

    myAWSIoTMQTTClient.connect()
    myAWSIoTMQTTClient.subscribe(downstream_topic, 1, on_message)

    return myAWSIoTMQTTClient, upstream_topic
Ejemplo n.º 11
0
def publishSign(message):
    host = "aq7kwp31awdde-ats.iot.us-east-1.amazonaws.com"
    rootCAPath = "credential/RootCA.pem"
    certificatePath = "credential/certificate.pem.crt"
    privateKeyPath = "credential/private.pem.key"

    my_rpi = AWSIoTMQTTClient("signPub")
    my_rpi.configureEndpoint(host, 8883)
    my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

    my_rpi.configureOfflinePublishQueueing(
        -1)  # Infinite offline Publish queueing
    my_rpi.configureDrainingFrequency(2)  # Draining: 2 Hz
    my_rpi.configureConnectDisconnectTimeout(10)  # 10 sec
    my_rpi.configureMQTTOperationTimeout(5)  # 5 sec

    # Connect and subscribe to AWS IoT
    my_rpi.connect()
    my_rpi.subscribe("output/sign", 1, customCallback)
    my_rpi.publish("output/sign", message, 1)
    sleep(2)
Ejemplo n.º 12
0
def initialize(device_name, config_file, root_ca, certificate, private_key,
               group_ca_path):
    global ggd_name

    cfg = GroupConfigFile(config_file)
    local = dict()
    remote = dict()

    # determine heartbeat device's thing name and endpoint for MQTT clients
    ggd_name = cfg['devices'][device_name]['thing_name']
    iot_endpoint = cfg['misc']['iot_endpoint']

    # Discover Greengrass Core
    dip = DiscoveryInfoProvider()
    dip.configureEndpoint(iot_endpoint)
    dip.configureCredentials(
        caPath=root_ca, certPath=certificate, keyPath=private_key
    )
    dip.configureTimeout(10)  # 10 sec
    log.info("Discovery using CA: {0} certificate: {1} prv_key: {2}".format(
        root_ca, certificate, private_key
    ))
    # Now discover the groups in which this device is a member.
    # The arm should only be in two groups. The local and master groups.
    discovered, discovery_info = utils.ggc_discovery(
        ggd_name, dip, retry_count=10, max_groups=2
    )

    # Each group returned has a groupId which can compare to the configured
    # groupId in the config file. If the IDs match, the 'local' Group has been
    # found and therefore local core.
    # If the groupId's do not match, the 'remote' or 'master' group has been
    # found.
    group_list = discovery_info.getAllGroups()
    for g in group_list:
        logging.info("[initialize] group_id:{0}".format(g.groupId))
        if g.groupId == cfg['group']['id']:
            local_cores = g.coreConnectivityInfoList
            local['core'] = local_cores[0]  # just grab first core as local
            local['ca'] = g.caList
        else:
            remote_cores = g.coreConnectivityInfoList
            remote['core'] = remote_cores[0]  # just grab first core as remote
            remote['ca'] = g.caList

    if len(local) > 1 and len(remote) > 1:
        logging.info("[initialize] local_core:{0} remote_core:{1}".format(
            local, remote
        ))
    else:
        raise EnvironmentError("Couldn't find the arm's Cores.")

    # just save one of the group's CAs to use as a CA file later
    local_core_ca_file = utils.save_group_ca(
        local['ca'][0], group_ca_path, local['core'].groupId
    )
    remote_core_ca_file = utils.save_group_ca(
        remote['ca'][0], group_ca_path, remote['core'].groupId
    )

    # Greengrass Cores discovered, now connect to Cores from this Device
    # get a client to send telemetry
    local_mqttc = AWSIoTMQTTClient(ggd_name)
    log.info("[initialize] local gca_file:{0} cert:{1}".format(
        local_core_ca_file, certificate))
    local_mqttc.configureCredentials(
        local_core_ca_file, private_key, certificate
    )
    local_mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)

    if not utils.mqtt_connect(mqtt_client=local_mqttc, core_info=local['core']):
        raise EnvironmentError("Connection to GG Core MQTT failed.")

    # get a shadow client to receive commands
    master_shadow_client = AWSIoTMQTTShadowClient(ggd_name)
    log.info("[initialize] remote ca_file:{0} cert:{1}".format(
        local_core_ca_file, certificate))
    remote_mqttc = master_shadow_client.getMQTTConnection()
    remote_mqttc.configureCredentials(
        remote_core_ca_file, private_key, certificate
    )

    if not utils.mqtt_connect(mqtt_client=master_shadow_client,
                              core_info=remote['core']):
        raise EnvironmentError("Connection to Master Shadow failed.")

    # create and register the shadow handler on delta topics for commands
    # with a persistent connection to the Master shadow
    master_shadow = master_shadow_client.createShadowHandlerWithName(
        cfg['misc']['master_shadow_name'], True)
    log.info("[initialize] created handler for shadow name: {0}".format(
        cfg['misc']['master_shadow_name']
    ))
    token = master_shadow.shadowGet(shadow_mgr, 5)
    log.info("[initialize] shadowGet() tk:{0}".format(token))

    return local_mqttc, remote_mqttc, master_shadow
Ejemplo n.º 13
0
ShadowClient.configureEndpoint("a1oa9tg9lcso0.iot.eu-west-1.amazonaws.com", 8883)
ShadowClient.configureCredentials(get_rootca(),
get_private(),get_cert())
ShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
ShadowClient.configureConnectDisconnectTimeout(30)  # 10 sec
ShadowClient.configureMQTTOperationTimeout(10)  # 5 sec
ShadowClient.connect()
deviceShadowHandler = ShadowClient.createShadowHandlerWithName(devicename, True)
#shadowCallbackContainer_Bot = shadowCallbackContainer(deviceShadowHandler)
#deviceShadowHandler.shadowRegisterDeltaCallback(shadowCallbackContainer_Bot.customShadowCallback_Delta)




# MQTT Connection establishement
myMQTTClient = AWSIoTMQTTClient(devicename)
myMQTTClient.configureEndpoint("a1oa9tg9lcso0.iot.eu-west-1.amazonaws.com", 8883)
myMQTTClient.configureCredentials(get_rootca(),
get_private(),get_cert())


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 publish
myMQTTClient.connect()


con = psycopg2.connect("host='litterbugdb.c1ekrfqx70oj.eu-west-1.rds.amazonaws.com' dbname='littering' user='******' password='******'")
cur = con.cursor()
Ejemplo n.º 14
0
except Exception as e:
    print(e)

bz = Buzzer(5)
# LCD display grants access
lcd = LCD()
displayDefaultMsg()

host = str(configurationFile["dynamoDB_configuration"]["host"])
rootCAPath = str(configurationFile["dynamoDB_configuration"]["rootCAPath"])
certificatePath = str(
    configurationFile["dynamoDB_configuration"]["certificatePath"])
privateKeyPath = str(
    configurationFile["dynamoDB_configuration"]["privateKeyPath"])
try:
    my_rpi = AWSIoTMQTTClient(
        str(configurationFile["dynamoDB_configuration"]["Pub-Sub"]))
    my_rpi.configureEndpoint(
        host, int(configurationFile["dynamoDB_configuration"]["port"]))
    my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

    my_rpi.configureOfflinePublishQueueing(
        -1)  # Infinite offline Publish queueing
    my_rpi.configureDrainingFrequency(2)  # Draining: 2 Hz
    my_rpi.configureConnectDisconnectTimeout(10)  # 10 sec
    my_rpi.configureMQTTOperationTimeout(5)  # 5 sec

    # Connect and subscribe to AWS IoT
    my_rpi.connect()
    my_rpi.subscribe("ACNA2/MQTT_subscription", 1, customCallback)
except Exception as e:
    print(e)
import time
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import configparser
import logging
import random
import time

logging.basicConfig(format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
                    level=logging.INFO)

#Load configuration from config.ini
config = configparser.ConfigParser()
config.read('config.ini')

#Setup MQTT client and security certificates
mqttc = AWSIoTMQTTClient("TemperatureSensor1_monitor")
mqttc.configureEndpoint(config['Endpoints']['BJS_IOT_ENDPOINT'],
                        int(config['Endpoints']['BJS_IOT_ENDPOINT_PORT']))
mqttc.configureCredentials(config['Certs']['ROOT_CA'],
                           config['Certs']['TEMPERATURE_SENSOR_1_PRIVATE_KEY'],
                           config['Certs']['TEMPERATURE_SENSOR_1_CERT'])

#Connect to IoT Core
mqttc.connect()
logging.info('MQTT Client Connected to IoT Core')


#Callback: MQTT Subscribe
def mqtt_subscribe_callback(client, userdata, message):
    logging.info(f'Received message on topic {message.topic} :')
    logging.info(message.payload)
import json
from datetime import datetime
from random import randint

host = "a1ggladwtvbsba-ats.iot.us-east-1.amazonaws.com"  #replace this with your IoT host name
rootCAPath = "root-CA.crt"  #replace this with your root CA certificate
certificatePath = "windturbine.cert.pem"  #replace this with your device certificate
privateKeyPath = "windturbine.private.key"  #replace this with your device private key
clientID = "basicPubSub"

print("Activating turbines...\n")

# Init AWSIoTMQTTClient
myAWSIoTMQTTClient = None

myAWSIoTMQTTClient = AWSIoTMQTTClient(clientID)

myAWSIoTMQTTClient.configureEndpoint(host, 8883)

myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath,
                                        certificatePath)

# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(
    -1)  # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

print("connecting...")
Ejemplo n.º 17
0
import json
from DocClientUtils import prettifyBatch, readJson
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from RGB import RGB
from Button import Button
import time
import socket
import numpy as np
import sys

HOST = "192.168.43.186"
TEMP_PORT = 8090
PRESS_PORT = 8091
duration = 30

myMQTTClient = AWSIoTMQTTClient("pi01")
myMQTTClient.configureEndpoint(
    "a1x06kutqzbjah-ats.iot.us-east-1.amazonaws.com", 8883)
myMQTTClient.configureCredentials(
    "Certificates/AmazonRootCA1.pem",
    "Certificates/900b9cf919-private.pem.key",
    "Certificates/900b9cf919-certificate.pem.crt")

myMQTTClient.configureOfflinePublishQueueing(-1)
myMQTTClient.configureDrainingFrequency(2)
myMQTTClient.configureConnectDisconnectTimeout(10)
myMQTTClient.configureMQTTOperationTimeout(5)

with open("Information/Bioreactor.json", 'r') as fp:
    Bioreactor = json.load(fp)
print(Bioreactor)
Ejemplo n.º 18
0
import RPi.GPIO as GPIO
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from time import sleep
from datetime import date, datetime
 
# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
 
# AWS IoT certificate based connection
myMQTTClient = AWSIoTMQTTClient("123afhlss456")
myMQTTClient.configureEndpoint("auf9cn18w1qbv.iot.us-east-2.amazonaws.com", 8883)
myMQTTClient.configureCredentials("/home/pi/certs/root-CA.pem", "/home/pi/certs/4b4aef80d1-private.pem.key", "/home/pi/certs/4b4aef80d1-certificate.pem.crt")
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 publish
myMQTTClient.connect()
myMQTTClient.publish("homesec/cam", "connected", 0)
 
#loop and publish sensor reading
while 1:
    now = datetime.utcnow()
    now_str = now.strftime('%Y-%m-%dT%H:%M:%SZ') #e.g. 2016-04-18T06:12:25.877Z
    #instance = dht11.DHT11(pin = 4) #BCM GPIO04
    #result = instance.read()
    #if result.is_valid():
    payload = '{ "Date_and_time:": "' + now_str + '","Intruder": ' + "name to be replaced" + ' }'
    port = 443
if not args.useWebsocket and not args.port:  # When no port override for non-WebSocket, default to 8883
    port = 8883

# 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)

# Init AWSIoTMQTTClient
myAWSIoTMQTTClient = None
if useWebsocket:
    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True)
    myAWSIoTMQTTClient.configureEndpoint(host, port)
    myAWSIoTMQTTClient.configureCredentials(rootCAPath)
else:
    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
    myAWSIoTMQTTClient.configureEndpoint(host, port)
    myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

myCallbackContainer = CallbackContainer(myAWSIoTMQTTClient)
Ejemplo n.º 20
0
def aws_mqtt_node():
    # init node
    rospy.init_node('aws_mqtt_node', anonymous=True)  #, log_level=rospy.DEBUG)

    # load parameters
    params = rospy.get_param("~", {})
    print(params)
    mqtt_params = params.pop("mqtt", {})
    bridge_params = params.pop("bridge", {})

    host = mqtt_params.pop("host", "")
    rootCAPath = mqtt_params.pop("rootCAPath", "")
    certificatePath = mqtt_params.pop("certificatePath", "")
    privateKeyPath = mqtt_params.pop("privateKeyPath", "")
    clientId = mqtt_params.pop("clientId", "")

    # Init AWSIoTMQTTClient
    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
    myAWSIoTMQTTClient.configureEndpoint(host, 8883)
    try:
        myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath,
                                                certificatePath)
    except:
        raise IOError("Cannot load certificates...")
    else:
        # AWSIoTMQTTClient connection configuration
        myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
        myAWSIoTMQTTClient.configureOfflinePublishQueueing(
            0)  # -1:Infinite offline Publish queueing. 0:no queue
        myAWSIoTMQTTClient.configureDrainingFrequency(50)  # Draining: 2 Hz
        myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
        myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

        # dependency injection
        config = create_config(myAWSIoTMQTTClient)
        inject.configure(config)

        # Connect to AWS IoT
        try:
            myAWSIoTMQTTClient.connect()
        except:
            raise IOError("Cannot connect to AWS IoT...")
        else:
            # configure bridges
            bridges = []
            # setup publishing bridge
            bridges.append(create_publish_bridge())
            # setup subscribing bridges
            for bridge_args in bridge_params:
                try:
                    bridges.append(create_subscribe_bridge(**bridge_args))
                except Exception, e:
                    rospy.logerr(str(e))
                    rospy.logerr("Cannot subscribe to the topic %s" %
                                 (bridge_args.pop("topic_from", "")))

            rospy.loginfo(rospy.get_caller_id() + " All settings are ready!")

            # spin() simply keeps python from exiting until this node is stopped
            for bridge in bridges:
                rospy.on_shutdown(bridge.on_shutdown)
            rospy.on_shutdown(myAWSIoTMQTTClient.disconnect)
            rospy.spin()
Ejemplo n.º 21
0
# Read in command-line parameters
host = argvs[1]
rootCAPath = argvs[2]
certificatePath = argvs[3]
privateKeyPath = argvs[4]

# 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)

# Configure Conncect Setting
myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSub")
myAWSIoTMQTTClient.configureEndpoint(host, 8883)
myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1)  
myAWSIoTMQTTClient.configureDrainingFrequency(2)  
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  

# Connect and subscribe to AWS IoT
myAWSIoTMQTTClient.connect()

# Publish to the same topic in a loop forever
loopCount = 0
Ejemplo n.º 22
0
# Take reference to the following example:
# https://docs.aws.amazon.com/iot/latest/developerguide/iot-moisture-raspi-setup.html
#
# Documentation for AWSIoTPythonSDK:
# https://github.com/aws/aws-iot-device-sdk-python

from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from .settings import *

# Init AWSIoTMQTTClient
aws_client = None
aws_client = AWSIoTMQTTClient(CLIENT_ID)
aws_client.configureEndpoint(HOST, PORT)
aws_client.configureCredentials(ROOT_CA, KEY, CERT)

# AWSIoTMQTTClient connection configuration
aws_client.configureAutoReconnectBackoffTime(1, 32, 20)
aws_client.configureOfflinePublishQueueing(
    -1)  # Infinite offline Publish queueing
aws_client.configureDrainingFrequency(2)  # Draining: 2 Hz
aws_client.configureConnectDisconnectTimeout(10)  # 10 sec
aws_client.configureMQTTOperationTimeout(5)  # 5 sec
def core_connect(device_name, config_file, root_ca, certificate, private_key,
                 group_ca_path):
    # read the config file
    cfg = GroupConfigFile(config_file)

    # determine heartbeat device's thing name and orient MQTT client to GG Core
    heartbeat_name = cfg['devices'][device_name]['thing_name']
    iot_endpoint = cfg['misc']['iot_endpoint']
    local_core = None

    # Discover Greengrass Core
    dip = DiscoveryInfoProvider()
    dip.configureEndpoint(iot_endpoint)
    dip.configureCredentials(
        caPath=root_ca, certPath=certificate, keyPath=private_key
    )
    dip.configureTimeout(10)  # 10 sec
    log.info("[hb] Discovery using CA: {0} cert: {1} prv_key: {2}".format(
        root_ca, certificate, private_key
    ))
    # Now discover the groups in which this device is a member.
    # The heartbeat should only be in one group
    discovered, discovery_info = utils.ggc_discovery(
        heartbeat_name, dip, retry_count=10, max_groups=1
    )

    ca_list = discovery_info.getAllCas()
    group_id, ca = ca_list[0]
    group_ca_file = utils.save_group_ca(ca, group_ca_path, group_id)

    if discovered is False:
        log.error(
            "[hb] Discovery failed for: {0} when connecting to "
            "service endpoint: {1}".format(
                heartbeat_name, iot_endpoint
            ))
        return
    log.info("[hb] Discovery success")

    mqttc = AWSIoTMQTTClient(heartbeat_name)

    # find this device Group's core
    for group in discovery_info.getAllGroups():
        utils.dump_core_info_list(group.coreConnectivityInfoList)
        local_core = group.getCoreConnectivityInfo(cfg['core']['thing_arn'])
        if local_core:
            log.info('[hb] Found the local core and Group CA.')
            break

    if not local_core:
        raise EnvironmentError("[hb] Couldn't find the local Core")

    # local Greengrass Core discovered, now connect to Core from this Device
    log.info("[hb] gca_file:{0} cert:{1}".format(group_ca_file, certificate))
    mqttc.configureCredentials(group_ca_file, private_key, certificate)
    mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)

    if not utils.mqtt_connect(mqtt_client=mqttc, core_info=local_core):
        raise EnvironmentError("[hb] Connection to GG Core MQTT failed.")

    return mqttc, heartbeat_name
Ejemplo n.º 24
0
# Import SDK packages
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient

# For certificate based connection
myMQTTClient = AWSIoTMQTTClient("iotconsole-1566721259865-4")
# For Websocket connection
# myMQTTClient = AWSIoTMQTTClient("myClientID", useWebsocket=True)
# Configurations
# For TLS mutual authentication
myMQTTClient.configureEndpoint("**5asn11fe**-ats.iot.ap-south-1.amazonaws.com",
                               8883)
# For Websocket
# myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443)
# For TLS mutual authentication with TLS ALPN extension
# myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443)
myMQTTClient.configureCredentials("CA.pem", "9ee8dcee7c-private.pem.key",
                                  "9ee8dcee7c-certificate.pem.crt")
# For Websocket, we only need to configure the root CA
# myMQTTClient.configureCredentials("YOUR/ROOT/CA/PATH")
myMQTTClient.configureOfflinePublishQueueing(
    -1)  # Infinite offline Publish queueing
myMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
myMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

myMQTTClient.connect()
myMQTTClient.publish("myTopic", "myPayload", 0)
myMQTTClient.subscribe("myTopic", 1, customCallback)
#myMQTTClient.unsubscribe("myTopic")
myMQTTClient.disconnect()
Ejemplo n.º 25
0

CLIENT_NAME = "store-sensor-seattle1"
TOPIC = "SeattleStoreTemp/1"

# Broker path is under AWS IoT > Settings (at the bottom left)
BROKER_PATH = "a2j1bxgczfkiaf-ats.iot.us-east-1.amazonaws.com"

# RSA 2048 bit key: Amazon Root CA 1 found here:
# https://docs.aws.amazon.com/iot/latest/developerguide/managing-device-certs.html
# change with certificates downloaded
ROOT_CA_PATH = './AmazonRootCA1.pem'
PRIVATE_KEY_PATH = './326bd30940-private.pem.key'
CERTIFICATE_PATH = './326bd30940-certificate.pem.crt'

IoTclient = AWSIoTMQTTClient(CLIENT_NAME)
IoTclient.configureEndpoint(BROKER_PATH, 8883)
IoTclient.configureCredentials(
    ROOT_CA_PATH, 
    PRIVATE_KEY_PATH, 
    CERTIFICATE_PATH
)

# Allow the device to queue infinite messages
IoTclient.configureOfflinePublishQueueing(-1)

# Number of messages to send after a connection returns
IoTclient.configureDrainingFrequency(1)  # 1 requests/second

# How long to wait for a [dis]connection to complete (in seconds)
IoTclient.configureConnectDisconnectTimeout(10)
Ejemplo n.º 26
0
class MQTTClient:

    def __init__(self, id):
        self.clientId = id
        self.myMQTTClient = None

    def initMQTTclient(self):
        # For certificate based connection
        self.myMQTTClient = AWSIoTMQTTClient(self.clientId)

        # For Websocket connection
        # myMQTTClient = AWSIoTMQTTClient("myClientID", useWebsocket=True)

        path = "../../Assignment1/keys/"
        values = readFromCSVFile(path + "key.txt")

        # Configurations
        # For TLS mutual authentication
        #self.myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 8883)
        self.myMQTTClient.configureEndpoint(values["clientEndpoint"], 8883)

        # For Websocket
        # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443)

        # For TLS mutual authentication with TLS ALPN extension
        # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443)

        #self.myMQTTClient.configureCredentials("YOUR/ROOT/CA/PATH", "PRIVATE/KEY/PATH", "CERTIFICATE/PATH")
        self.myMQTTClient.configureCredentials(path+values["rootCAFile"], path+values["privateKeyFile"], path+values["certificateFile"])

        # For Websocket, we only need to configure the root CA
        # myMQTTClient.configureCredentials("YOUR/ROOT/CA/PATH")

        self.myMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
        self.myMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
        self.myMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
        self.myMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec
        self.myMQTTClient.connect()

    def publish(self, topic, payload):
        self.myMQTTClient.publish(topic, payload, 0)

    def subscribe(self, topic):
        self.myMQTTClient.subscribe(topic, 1, customCallback)

    def unsubscribe(self, topic):
        self.myMQTTClient.unsubscribe(topic)

    def disconnect(self):
        self.myMQTTClient.disconnect()
Ejemplo n.º 27
0
class MQTTClient(PluginInterface):
    options = [
        'sensorid', 'topicid', 'topic_pfx', 'endpoint', 'rootca', 'prikey',
        'devcert', 'batch', 'interval', 'fields', 'datafmt'
    ]
    topic_pfx = 'gravity'
    endpoint = None
    rootca = 'root-CA.crt'
    prikey = 'iot.private.key'
    devcert = 'iot.cert.pem'
    interval = 1
    fields = ['gravity', 'long', 'cross', 'latitude', 'longitude', 'datetime']
    datafmt = 'marine'

    # Ordered list of marine fields
    _marine_fieldmap = [
        'header', 'gravity', 'long', 'cross', 'beam', 'temp', 'pressure',
        'etemp', 'vcc', 've', 'al', 'ax', 'status', 'checksum', 'latitude',
        'longitude', 'speed', 'course', 'datetime'
    ]
    _airborne_fieldmap = []

    # Defaults to integer cast if not specified here
    _field_casts = {
        'header': str,
        'gravity': float,
        'latitude': float,
        'longitude': float,
        'speed': float,
        'course': float,
        'datetime': convert_time
    }

    def __init__(self):
        super().__init__()
        # Set AWSIoTPythonSDK logger level from default
        logging.getLogger('AWSIoTPythonSDK').setLevel(logging.WARNING)
        self.client = None
        self.tick = 0
        self.sensorid = None
        self._errcount = 0

    @classmethod
    def extract_fields(cls, data: str, fieldmap=_marine_fieldmap):
        extracted = {}
        data = data.split(',')
        for i, field in enumerate(fieldmap):
            if field.lower() in cls.fields:
                try:
                    extracted[field] = cls._field_casts.get(
                        field.lower(), int)(data[i])
                except ValueError:
                    extracted[field] = data[i]
        return extracted

    @staticmethod
    def consumer_type() -> set:
        return {str}

    # def _batch_process(self):
    #     # TODO: Implement batch publish feature, perhaps collect items in a queue until a limit is reached
    #     # then publish as a list of json maps
    #     sendqueue = []
    #     limit = 10

    def configure_client(self):
        if self.endpoint is None:
            raise ValueError("No endpoint provided for MQTT Plugin.")
        try:
            self.sensorid = getattr(self, 'sensorid', str(uuid4())[0:8])
            topicid = getattr(self, 'topicid', self.sensorid)

            self.client = AWSIoTMQTTClient(self.sensorid, useWebsocket=False)
            self.client.configureEndpoint(self.endpoint, 8883)
            self.client.configureOfflinePublishQueueing(10000)
            self.client.configureConnectDisconnectTimeout(10)
            self.client.configureCredentials(join_cfg(self.rootca),
                                             join_cfg(self.prikey),
                                             join_cfg(self.devcert))
            self.client.configureDrainingFrequency(2)
            self.client.configureMQTTOperationTimeout(5)
            self.client.connect()

            topic = '/'.join([self.topic_pfx, topicid])
        except AttributeError:
            LOG.exception(
                "Missing attributes from configuration for MQTT plugin.")
            raise
        return topic

    def run(self):
        topic = self.configure_client()
        while not self.exiting:
            item = self.get(block=True, timeout=None)
            self.tick += 1
            if item is None or item == "" or self.tick % self.interval:
                self.task_done()
                continue
            else:
                try:
                    self.tick = 0  # reset tick count
                    fields = item.split(',')
                    timestamp = convert_time(fields[-1])
                    if not len(fields):
                        continue

                    data_dict = self.extract_fields(item)

                    item_json = json.dumps({
                        'd': self.sensorid,
                        't': timestamp,
                        'v': data_dict
                    })
                    self.client.publish(topic, item_json, 0)
                    self.task_done()
                except:
                    LOG.exception(
                        "Exception occured in mqtt-run loop. Item value: %s",
                        item)
                    self._errcount += 1
                    if self._errcount > 10:
                        # Terminate MQTT if errors accumulate
                        raise

        self.client.disconnect()
Ejemplo n.º 28
0
GPIO.setup(pinMotorFR2, GPIO.OUT)
GPIO.setup(pinMotorBL1, GPIO.OUT)
GPIO.setup(pinMotorBL2, GPIO.OUT)
GPIO.setup(pinMotorBR1, GPIO.OUT)
GPIO.setup(pinMotorBR2, GPIO.OUT)

host = "a27b8oybks6hla-ats.iot.us-east-2.amazonaws.com"
#host = "a1io5eo0eh1c6a-ats.iot.us-east-1.amazonaws.com"
#certPath = "/home/pi/demo/cert/"
certPath = "/home/pi/demo/demo-cert/"
clientId = "sajith-pi-demo-publisher"
topic = "LED"

# Init AWSIoTMQTTClient
myAWSIoTMQTTClient = None
myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
myAWSIoTMQTTClient.configureEndpoint(host, 8883)
#myAWSIoTMQTTClient.configureCredentials("{}root-CA.crt".format(certPath), "{}040198d3e3-private.pem.key".format(certPath), "{}040198d3e3-certificate.pem.crt".format(certPath))
myAWSIoTMQTTClient.configureCredentials(
    "{}aws-root-cert.pem".format(certPath),
    "{}private-key.pem.key".format(certPath),
    "{}iot-cert.pem.crt".format(certPath))


def go():
    print('ir hacia Delante')
    GPIO.output(pinMotorFL1, GPIO.HIGH)
    GPIO.output(pinMotorFL2, GPIO.LOW)
    GPIO.output(pinMotorFR1, GPIO.HIGH)
    GPIO.output(pinMotorFR2, GPIO.LOW)
Ejemplo n.º 29
0
import os
import random

#MQTT Istemci olusturma ve guvenlik sertifikalarini tanimlama
#Sertifa isimleri ile AWS IoT Thing indirdiginiz sertifika isimlerinin ayni olmasina dikkat edin.

currentPath = os.getcwd()
roboName = os.path.basename(currentPath)
latitude = 0
longtitude = 0
battery = 100
isBusy = 'false'
ID = 10000
print("RoboName--> " + roboName)

mqttClient = AWSIoTMQTTClient(roboName)

#Ayarlar sayfasindaki IoTEndpoint buraya ekleyin
mqttClient.configureEndpoint("ENDPOINT BURAYA KOPYALANACAK", 8883)
mqttClient.configureCredentials("../root-CA.crt", "PrivateKey.pem",
                                "certificate.pem.crt")


#JSON formatina encode eden fonksiyon
def toJSON(string):
    return json.dumps(string)


mqttClient.toJSON = toJSON

#Degiskenleri ve MQTT mesaji tanimlari
Ejemplo n.º 30
0
def get_iot_client(device_id, endpoint):
    client = AWSIoTMQTTClient(device_id, useWebsocket=True)
    client.configureEndpoint(endpoint, 443)
    client.configureCredentials('AmazonRootCA1.pem')
    return client
Ejemplo n.º 31
0
aws_access_key_id = args.aws_access_key_id
aws_secret_access_key = args.aws_secret_access_key
bucket_name = args.bucket_name

# Configure logging
logger = logging.getLogger("AWSIoTPythonSDK.core")
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler("test.log")
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)

# Init AWSIoTMQTTClient
myAWSIoTMQTTClient = None
myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True)
myAWSIoTMQTTClient.configureEndpoint(host, 443)
myAWSIoTMQTTClient.configureCredentials(rootCAPath)

# Set aws access key
os.environ["AWS_ACCESS_KEY_ID"] = aws_access_key_id
os.environ["AWS_SECRET_ACCESS_KEY"] = aws_secret_access_key

# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(
    -1)  # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(10)  # 5 sec
Ejemplo n.º 32
0
        message.topic, message.payload))
    print("--------------\n\n")
    if message.topic == 'rebootCommandguyi':
        # execute the reboot function
        info = json.loads(message.payload)
        location = info['Location']
        ip = info['ID']
        ssh_reboot.sshAndReboot(ip, location).judgements()


def offline():
    print('aws iot is offline.')


# Init AWSIoTMQTTClient
device = AWSIoTMQTTClient(clientId)
device.configureEndpoint(host, 80)
device.configureCredentials(caPath, keyPath, certPath)

# AWSIoTMQTTClient connection configuration
device.configureAutoReconnectBackoffTime(1, 32, 20)
device.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
device.configureDrainingFrequency(2)  # Draining: 2 Hz
device.configureConnectDisconnectTimeout(10)  # 10 sec
device.configureMQTTOperationTimeout(5)  # 5 sec
device.onOffline = offline

# Connect and subscribe to AWS IoT
try:
    print('AWS IoT connecting...')
    device.connect(1200)
Ejemplo n.º 33
0
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import json
import time

#Setup our MQTT client and security certificates
#Make sure your certificate names match what you downloaded from AWS IoT

#Function to encode a payload into JSON
def json_encode(string):
        return json.dumps(string)

#Creating last will message and encoding
lastWill = "Help I have disconnected"
lastWill = json_encode(lastWill)

mqttc = AWSIoTMQTTClient("1234")

#Make sure you use the correct region!
mqttc.configureEndpoint("data.iot.us-west-2.amazonaws.com",8883)
mqttc.configureCredentials("./rootCA.pem","./ratchet/ratchet.private.key","./ratchet/ratchet.cert.pem")
mqttc.configureLastWill("lwt", lastWill, 1)


mqttc.connect()
print("Connected")
print("Press Control + C to Crash")

# Loop forever
while True:
        pass
Ejemplo n.º 34
0
def AWS_MQTT_Initialize():
    global CA_CERTIFICATE
    global PRIVATE_KEY
    global DEVICE_CERTIFICATE
    try:
        subprocess.call('./copyCertificates.sh')
    except:
        CA_CERTIFICATE = "Certificates/root-CA.crt"
        PRIVATE_KEY = "Certificates/device-private.pem.key"
        DEVICE_CERTIFICATE = "Certificates/device-certificate.pem.crt"
    #AWS IoT certificate based connection---------------------------------------
    myMQTTClient = AWSIoTMQTTClient(CLIENT)  #this can be any arbitrary string
    myMQTTClient.configureEndpoint(AWS_SERVER, PORT)  #endpoint and port number
    myMQTTClient.configureCredentials(
        CA_CERTIFICATE, PRIVATE_KEY, DEVICE_CERTIFICATE
    )  #root ca and certificate used for secure connection

    myMQTTClient.configureOfflinePublishQueueing(
        -1)  # Infinite offline Publish queueing
    myMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
    myMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
    myMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

    #connect, subscribe and publish----------------------------------------------------------
    myMQTTClient.connect()
    AWS_MQTT_subscribe(myMQTTClient, None)
    myMQTTClient.publish(THING_NAME + "/info", "connected", 0)
    return myMQTTClient
Ejemplo n.º 35
0
from xbgw.reporting.device_cloud import wrap, id_to_stream, get_type
from xbgw.command.rci import RCICommandProcessor
from xbgw.settings import SettingsRegistry, SettingsMixin, Setting
from xbgw.debug.echo import EchoCommand

from ConfigParser import SafeConfigParser

try:
    from build import version
except ImportError:
    version = "None"

SETTINGS_FILE = "xbgw_settings.json"
PID_FILE = "xbgw.pid"

awsClient = AWSIoTMQTTClient("connectport")
awsClient.configureEndpoint("a2uxgca99ev3iu-ats.iot.us-west-2.amazonaws.com",
                            8883)
awsClient.configureCredentials(
    "/userfs/WEB/python/certs/AmazonRootCA1.pem",
    "/userfs/WEB/python/certs/965e2a8102-private.pem.key",
    "/userfs/WEB/python/certs/965e2a8102-certificate.pem.crt")
awsClient.configureOfflinePublishQueueing(
    -1)  # Infinite offline Publish queueing
awsClient.configureDrainingFrequency(2)  # Draining: 2 Hz
awsClient.configureConnectDisconnectTimeout(10)  # 10 sec
awsClient.configureMQTTOperationTimeout(5)  # 5 sec
awsClient.connect()

#ROUTER_ID_ARRAY = [("[0005]!"), ("[00:13:a2:00:41:93:b7:a8]!"), ("[00:13:a2:00:41:93:b8:88]!"), ("[00:13:a2:00:41:93:b8:81]!"), ("[00:13:a2:00:41:93:b8:96]!"), ("[00:13:a2:00:41:93:b8:c4]!"), ("[00:13:a2:00:41:93:b7:b7]!"), ("[00:13:a2:00:41:93:b7:a5]!"), ("[00:13:a2:00:41:93:b7:c0]!"), ("[00:13:a2:00:41:93:b8:db]!"), ("[00:13:a2:00:41:93:b9:23]!"), ("[00:13:a2:00:41:93:b7:a2]!"), ("[00:13:a2:00:41:93:b8:ed]!"), ("[00:13:a2:00:41:93:b7:84]!"), ("[00:13:a2:00:41:93:b8:74]!"), ("[00:13:a2:00:41:93:b7:9f]!")];
#ROOM_ID_ARRAY = [("Main"),("AWSTest10"),("AWSTest11"),("AWSTest12"),("AWSTest13"),("AWSTest14"),("AWSTest15"),("AWSTest16"),("AWSTest17"),("AWSTest18"),("AWSTest19"),("AWSTest20"), ("AWSTest21"), ("AWSTest22"), ("AWSTest23"), ("AWSTest24")];
Ejemplo n.º 36
0
 def create_iot_client(self):
     client = AWSIoTMQTTClient(self.vehicle_id)
     client.configureEndpoint(self.endpoint, 8883)
     client.configureCredentials(self.ca, self.private_key,
                                 self.certificate)
     client.configureOfflinePublishQueueing(
         -1)  # Infinite offline Publish queueing
     client.configureDrainingFrequency(2)  # Draining: 2 Hz
     client.configureConnectDisconnectTimeout(10)  # 10 sec
     client.configureAutoReconnectBackoffTime(1, 128, 20)
     client.configureMQTTOperationTimeout(5)  # 5 sec
     return client
Ejemplo n.º 37
0
    def subscribe(self):
        def response(self, params, packet):
            status = ''
            print('Received message from AWS IoT Core')
            print('Topic: '+packet.topic)
            print(packet.payload)
            data = json.loads(packet.payload)
            print('Payload: ', data['switch'])
            if data['switch'] == 1:
                status = 'close'
                GPIO.setup(pin, GPIO.LOW)
                print("low")
            if data['switch'] == 0:
                status = 'open'
                GPIO.setup(pin, GPIO.HIGH)
                print("high")
            print("done")

        def online(self, params, packet):
            print('Received message from React Native')
            print('Topic: '+packet.topic)
            print(packet.payload)
            myMQTTClient.publish(
                topic="smartbank/connection",
                QoS=0,
                payload='{"message":"Yes"}'
            )

        # For certificate based connection
        myMQTTClient = AWSIoTMQTTClient(CLIENT_ID)
        # For TLS mutual authentication
        myMQTTClient.configureEndpoint(ENDPOINT, 8883) #Provide your AWS IoT Core endpoint (Example: "abcdef12345-ats.iot.us-east-1.amazonaws.com")
        myMQTTClient.configureCredentials(PATH_TO_ROOT, PATH_TO_KEY, PATH_TO_CERT) #Set path for Root CA and provisioning claim credentials
        myMQTTClient.configureOfflinePublishQueueing(-1)
        myMQTTClient.configureDrainingFrequency(2)
        myMQTTClient.configureConnectDisconnectTimeout(10)
        myMQTTClient.configureMQTTOperationTimeout(5)
        GPIO.setup(pin, GPIO.HIGH)
        
        print('Connecting...')
        myMQTTClient.connect()
        print('Connected.')
        print('Listening...')
        myMQTTClient.subscribe('smartbank/check', 1, online)
        myMQTTClient.subscribe('smartbank/switch', 1, response)
# Configure logging
logger = None
if sys.version_info[0] == 3:
	logger = logging.getLogger("core")  # Python 3
else:
	logger = logging.getLogger("AWSIoTPythonSDK.core")  # Python 2
logger.setLevel(logging.DEBUG)
streamHandler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)

# Init AWSIoTMQTTClient
myAWSIoTMQTTClient = None
if useWebsocket:
	myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSub", useWebsocket=True)
	myAWSIoTMQTTClient.configureEndpoint(host, 443)
	myAWSIoTMQTTClient.configureCredentials(rootCAPath)
else:
	myAWSIoTMQTTClient = AWSIoTMQTTClient("basicPubSub")
	myAWSIoTMQTTClient.configureEndpoint(host, 8883)
	myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

# Connect and subscribe to AWS IoT
identityPoolID = cognitoIdentityPoolID
region = host.split('.')[2]
cognitoIdentityClient = boto3.client('cognito-identity', region_name=region)
# identityPoolInfo = cognitoIdentityClient.describe_identity_pool(IdentityPoolId=identityPoolID)
# print identityPoolInfo

temporaryIdentityId = cognitoIdentityClient.get_id(IdentityPoolId=identityPoolID)
identityID = temporaryIdentityId["IdentityId"]

temporaryCredentials = cognitoIdentityClient.get_credentials_for_identity(IdentityId=identityID)
AccessKeyId = temporaryCredentials["Credentials"]["AccessKeyId"]
SecretKey = temporaryCredentials["Credentials"]["SecretKey"]
SessionToken = temporaryCredentials["Credentials"]["SessionToken"]

# Init AWSIoTMQTTClient
myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True)

# AWSIoTMQTTClient configuration
myAWSIoTMQTTClient.configureEndpoint(host, 443)
myAWSIoTMQTTClient.configureCredentials(rootCAPath)
myAWSIoTMQTTClient.configureIAMCredentials(AccessKeyId, SecretKey, SessionToken)
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

# Connect and subscribe to AWS IoT
myAWSIoTMQTTClient.connect()
myAWSIoTMQTTClient.subscribe(topic, 1, customCallback)
time.sleep(2)
Ejemplo n.º 40
0
# -*- coding:utf8 -*-
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import os
import time

def customCallback(client, userdata, message):
    print('message: ')
    print(message.payload)
    print('topic: ')
    print(message.topic)
    print('--------------\n\n')

myMQTTClient = AWSIoTMQTTClient('python')
myMQTTClient.configureEndpoint(os.environ['AWSIOT_HOST'], 8883)
myMQTTClient.configureCredentials('keys/G5.pem', 'keys/private.pem.key', 'keys/certificate.pem.crt')
myMQTTClient.configureOfflinePublishQueueing(-1)
myMQTTClient.configureDrainingFrequency(2)
myMQTTClient.configureConnectDisconnectTimeout(10)
myMQTTClient.configureMQTTOperationTimeout(5)
myMQTTClient.connect()
while True:
    myMQTTClient.subscribe("test", 1, customCallback)
    time.sleep(1)

def initialize(device_name, config_file, root_ca, certificate, private_key,
               group_ca_path):
    # read the config file
    cfg = GroupConfigFile(config_file)

    ggd_name = cfg['devices'][device_name]['thing_name']
    iot_endpoint = cfg['misc']['iot_endpoint']
    # prep for discovery
    dip = DiscoveryInfoProvider()
    dip.configureEndpoint(iot_endpoint)
    dip.configureCredentials(
        caPath=pa.root_ca, certPath=pa.certificate, keyPath=pa.private_key
    )
    dip.configureTimeout(10)  # 10 sec
    logging.info("Discovery using CA:{0} cert:{1} prv_key:{2}".format(
        pa.root_ca, pa.certificate, pa.private_key
    ))
    discovered, discovery_info = utils.ggc_discovery(
        thing_name=ggd_name, discovery_info_provider=dip, max_groups=3
    )

    local, remote = _find_cores(cfg, discovery_info, iot_endpoint)
    # Save each group's CAs to use as a CA file later
    local_core_ca_file = utils.save_group_ca(
        local['ca'][0], group_ca_path, local['core'].groupId
    )
    for r in remote:
        remote[r]['ca_file'] = utils.save_group_ca(
            remote[r]['ca'][0], group_ca_path, remote[r]['core'].groupId
        )

    # create and connect MQTT client pointed toward the Master Greengrass Core
    mqttc_m = AWSIoTMQTTClient(ggd_name)
    log.info("[initialize] local gca_file:{0} cert:{1}".format(
        local_core_ca_file, certificate))
    mqttc_m.configureCredentials(
        local_core_ca_file, private_key, certificate
    )
    mqttc_m.configureOfflinePublishQueueing(10, DROP_OLDEST)

    log.info("[initialize] Starting connection to Master Core")
    if utils.mqtt_connect(mqtt_client=mqttc_m, core_info=local['core']):
        log.info("[initialize] Connected to Master Core")
    else:
        log.error("[initialize] could not connect to Master Core")

    # create and connect MQTT clients pointed toward the remote Greengrass Cores
    mqttc_list = list()
    for r in remote:
        remote_mqttc = AWSIoTMQTTClient(ggd_name)
        log.info("[initialize] local gca_file:{0} cert:{1}".format(
            r, certificate))
        remote_mqttc.configureCredentials(
            remote[r]['ca_file'], private_key, certificate)
        remote_mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)
        log.info("[initialize] Starting connection to Remote Core")
        if utils.mqtt_connect(mqtt_client=remote_mqttc,
                              core_info=remote[r]['core']):
            log.info("[initialize] Connected to Remote Core:{0}".format(
                remote[r]['core'].coreThingArn
            ))
            mqttc_list.append(remote_mqttc)
        else:
            log.error(
                "[initialize] could not connect to Remote Core:{0}".format(
                    remote[r]['core'].coreThingArn
            ))

    return mqttc_m, mqttc_list
Ejemplo n.º 42
0
        break
    except BaseException as e:
        print("Error in discovery!")
        print("Type: %s" % str(type(e)))
        print("Error message: %s" % e.message)
        retryCount -= 1
        print("\n%d/%d retries left\n" % (retryCount, MAX_DISCOVERY_RETRIES))
        print("Backing off...\n")
        backOffCore.backOff()

if not discovered:
    print("Discovery failed after %d retries. Exiting...\n" % (MAX_DISCOVERY_RETRIES))
    sys.exit(-1)

# Iterate through all connection options for the core and use the first successful one
myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
myAWSIoTMQTTClient.configureCredentials(groupCA, privateKeyPath, certificatePath)
myAWSIoTMQTTClient.onMessage = customOnMessage

connected = False
for connectivityInfo in coreInfo.connectivityInfoList:
    currentHost = connectivityInfo.host
    currentPort = connectivityInfo.port
    print("Trying to connect to core at %s:%d" % (currentHost, currentPort))
    myAWSIoTMQTTClient.configureEndpoint(currentHost, currentPort)
    try:
        myAWSIoTMQTTClient.connect()
        connected = True
        break
    except BaseException as e:
        print("Error in connect!")
Ejemplo n.º 43
0
def getMQTTClient(name=''):
	mqttClient = None
	
	config = getConfigAWS()
	if config:
		host = config['aws_iot_endpoint']
		rootCAPath = config['aws_iot_rootcapath']
		certificatePath = config['aws_iot_certificatepath']
		privateKeyPath = config['aws_iot_privatekeypath']
		
		mqttClient = AWSIoTMQTTClient(name)
		mqttClient.configureEndpoint(host, 8883)
		mqttClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)
		mqttClient.configureOfflinePublishQueueing(-1)
		mqttClient.configureDrainingFrequency(2)
		mqttClient.configureConnectDisconnectTimeout(10)
		mqttClient.configureMQTTOperationTimeout(5)
		
		try:
			mqttClient.connect()
		except Exception as e:
			print(e)
			raise ValueError('''
				Unable to connect to AWS.
			''')
	
	return mqttClient
Ejemplo n.º 44
0
class Client():
    def __init__(self, iot_client=None, iot_data_client=None, credentials=None, ca_path=None, privkey_path=None, cert_path=None):
        assert ca_path, "Certificate is required"
        if not iot_client:
            iot_client = boto3.client('iot')
        if not iot_data_client:
            iot_data_client = boto3.client('iot-data')
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client
        self.cert_path = cert_path
        self.privkey_path = privkey_path
        self.ca_path = ca_path
        self.credentials = credentials
        self.init_mqtt_client()

    def init_mqtt_client(self):
        endpoint = self.iot_client.describe_endpoint()
        use_websocket = True if self.credentials else False
        endpoint_port = 443 if use_websocket else 8883
        self.mqtt_client = AWSIoTMQTTClient("testo", useWebsocket=use_websocket)
        self.mqtt_client.configureEndpoint(endpoint['endpointAddress'], endpoint_port)
        self.mqtt_client.configureOfflinePublishQueueing(-1)
        self.mqtt_client.configureConnectDisconnectTimeout(10)
        self.mqtt_client.configureMQTTOperationTimeout(10)
        self.configure_credentials()
        log.debug("OpenSSL version {}".format(ssl.OPENSSL_VERSION))
        log.debug("Connecting MQTT client to {} on port {}...".format(endpoint['endpointAddress'], endpoint_port))
        try:
            self.mqtt_client.connect()
            log.debug("MQTT client connected")
        except connectTimeoutException:
            log.error("Failed to connect MQTT client - timeout (check policy)")
            self.mqtt_client = None

    def configure_credentials(self):
        if self.credentials:
            self.mqtt_client.configureIAMCredentials(*(self.credentials.values()))
            self.mqtt_client.configureCredentials(self.ca_path)
        elif self.privkey_path and self.cert_path:
            log.debug("Using %s %s %s", str(self.ca_path), str(self.privkey_path), str(self.cert_path))
            self.mqtt_client.configureCredentials(self.ca_path, self.privkey_path, self.cert_path)
        else:
            raise Exception("No credentials found")
def heartbeat(config_file, topic, frequency=3):
    # read the config file
    cfg = GroupConfigFile(config_file)

    # determine heartbeat device's thing name and orient MQTT client to GG Core
    heartbeat_name = cfg['devices']['GGD_heartbeat']['thing_name']
    mqttc = AWSIoTMQTTClient(heartbeat_name)
    mqttc.configureEndpoint(ggd_config.inv_arm_ip, ggd_config.inv_arm_port)
    mqttc.configureCredentials(
        CAFilePath=dir_path + "/" + ggd_ca_file_path,
        KeyPath=dir_path + "/certs/GGD_heartbeat.private.key",
        CertificatePath=dir_path + "/certs/GGD_heartbeat.certificate.pem.crt"
    )

    mqttc.configureOfflinePublishQueueing(10, DROP_OLDEST)

    if mqtt_connect(mqttc):
        # MQTT client has connected to GG Core, start heartbeat messages
        try:
            start = datetime.datetime.now()
            while True:
                hostname = socket.gethostname()

                now = datetime.datetime.now()
                msg = {
                    "version": "2017-07-05",  # YYYY-MM-DD
                    "ggd_id": heartbeat_name,
                    "hostname": hostname,
                    "data": [
                        {
                            "sensor_id": "heartbeat",
                            "ts": now.isoformat(),
                            "duration": str(now - start)
                        }
                    ]
                }
                print("[hb] publishing heartbeat msg: {0}".format(msg))
                mqttc.publish(topic, json.dumps(msg), 0)
                time.sleep(random.random() * 10)

        except KeyboardInterrupt:
            log.info(
                "[__main__] KeyboardInterrupt ... exiting heartbeat")
        mqttc.disconnect()
        time.sleep(2)
    else:
        print("[hb] could not connect successfully via mqtt.")
Ejemplo n.º 46
0
class Controller:
    def __init__(self, id_client, topic):
        self.id_client = id_client
        self.topic = topic
        self.stationList = []
        self.myMQTTClient = None

    # add the stations to a list
    def addStation(self, station):
        self.stationList.append(station)

    # connection to Aws Iot
    def awsConnect(self):
        # sensor_client -> id_client
        # data_read -> topic
        self.myMQTTClient = AWSIoTMQTTClient(self.id_client)
        # endpoint and port
        self.myMQTTClient.configureEndpoint(
            "a3hb251ijbp00t-ats.iot.eu-central-1.amazonaws.com", 8883)
        # certificates of thing
        self.myMQTTClient.configureCredentials(
            "cert/root-CA.crt", "cert/sensor/e7296f5b9d-private.pem.key",
            "cert/sensor/e7296f5b9d-certificate.pem.crt")
        self.myMQTTClient.configureOfflinePublishQueueing(-1)
        self.myMQTTClient.configureDrainingFrequency(2)
        self.myMQTTClient.configureConnectDisconnectTimeout(10)
        self.myMQTTClient.configureMQTTOperationTimeout(5)
        # connection
        self.myMQTTClient.connect()
        print("Connected to Aws!")

    # publication on the topic
    def publishSensorPythonToTopic(self):
        # scroll the list of stations
        for station in self.stationList:
            # update the station data
            station.updateData()
            data = station.getData()
            # publish the station data on the topic
            self.myMQTTClient.publish(self.topic, data, 0)
            print('Published topic -> %s: %s\n' % (self.topic, data))

    # publication on the topic
    def publishSensorRiotToTopic(self, data):
        # publish the message forwarded by broker
        self.myMQTTClient.publish(self.topic, data, 0)
        print('Published topic -> %s: %s\n' % (self.topic, data))
Ejemplo n.º 47
0
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient

SETTINGS = {
    "client_name": "PeopleCounter_cogni",
    "https_endpoint": "some-endpoint.iot.us-east-1.amazonaws.com",
    "port": 8883,
    "root_cert":
    "certs.awsiot/VeriSign-Class 3-Public-Primary-Certification-Authority-G5.pem",
    "private_key": "certs.awsiot/some-id-private.pem.key",
    "thing_cert": "certs.awsiot/some-id-certificate.pem.crt"
}

client = AWSIoTMQTTClient(SETTINGS["client_name"])
client.configureEndpoint(SETTINGS["https_endpoint"], SETTINGS["port"])
client.configureCredentials(SETTINGS["root_cert"], SETTINGS["private_key"],
                            SETTINGS["thing_cert"])
client.configureOfflinePublishQueueing(-1)
client.configureDrainingFrequency(2)
client.configureConnectDisconnectTimeout(10)
client.configureMQTTOperationTimeout(5)
client.connect()

print("Yay!")
Ejemplo n.º 48
0
def init_aws_iot_mqtt_client(args):
    # Init AWSIoTMQTTClient
    client = None
    port = args.port
    # Port defaults
    if args.useWebsocket and not args.port:  # When no port override for WebSocket, default to 443
        port = 443
    if not args.useWebsocket and not args.port:  # When no port override for non-WebSocket, default to 8883
        port = 8883
    #
    if args.useWebsocket:
        client = AWSIoTMQTTClient('', useWebsocket=True)
        client.configureEndpoint(args.host, port)
        client.configureCredentials(args.rootCAPath)
    else:
        client = AWSIoTMQTTClient('')
        client.configureEndpoint(args.host, port)
        client.configureCredentials(args.rootCAPath, args.privateKeyPath,
                                    args.certificatePath)
    # AWSIoTMQTTClient connection configuration
    client.configureAutoReconnectBackoffTime(1, 32, 20)
    client.configureOfflinePublishQueueing(
        -1)  # Infinite offline Publish queueing
    client.configureDrainingFrequency(2)  # Draining: 2 Hz
    client.configureConnectDisconnectTimeout(10)  # 10 sec
    client.configureMQTTOperationTimeout(5)  # 5 sec
    return client
Ejemplo n.º 49
0
    port = 443
if not args.useWebsocket and not args.port:  # When no port override for non-WebSocket, default to 8883
    port = 8883

# 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)

# Init AWSIoTMQTTClient
myAWSIoTMQTTClient = None
if useWebsocket:
    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId, useWebsocket=True)
    myAWSIoTMQTTClient.configureEndpoint(host, port)
    myAWSIoTMQTTClient.configureCredentials(rootCAPath)
else:
    myAWSIoTMQTTClient = AWSIoTMQTTClient(clientId)
    myAWSIoTMQTTClient.configureEndpoint(host, port)
    myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

# Connect and subscribe to AWS IoT
Ejemplo n.º 50
0
    path_iot = path.join(environ['localappdata'], "LTS AS", "iot")
else:
    path_iot = environ['HOMEPATH']+"/config/iot/"

with open(path.join(path_iot, 'conf.json'), "r") as f:
    config = json.loads(f.read())

host = config['host']
rootCAPath = path.join(path_iot, 'root-CA.crt')
certificatePath = path.join(path_iot, 'certificate.pem.crt')
privateKeyPath = path.join(path_iot, 'private.pem.key')
client_id = config['client_id']

# Init AWSIoTMQTTClient
myAWSIoTMQTTClient = None
myAWSIoTMQTTClient = AWSIoTMQTTClient(client_id)
myAWSIoTMQTTClient.configureEndpoint(host, 8883)
myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

# Connect and subscribe to AWS IoT
myAWSIoTMQTTClient.connect()
myAWSIoTMQTTClient.subscribe('$aws/things/no-lts-ws1/shadow/get/accepted', 1, customCallback)

# Publish to the same topic in a loop forever