Exemplo n.º 1
0
def get_client():
    global client
    if client == None:
        AccessKeyId = os.environ.get('AWS_ACCESS_KEY_ID')
        SecretKey = os.environ.get('AWS_SECRET_ACCESS_KEY')
        SessionToken = os.environ.get('AWS_SESSION_TOKEN')
        Host = os.environ.get('OT_IOT_HOST')

        client = AWSIoTMQTTClient("sharedClient", useWebsocket=True)
        client.configureEndpoint(Host, 443)
        client.configureCredentials(
            "./certs/VeriSign-Class 3-Public-Primary-Certification-Authority-G5.pem"
        )
        client.configureIAMCredentials(AccessKeyId, SecretKey, SessionToken)
        client.configureAutoReconnectBackoffTime(1, 32, 20)
        client.configureOfflinePublishQueueing(
            -1)  # Infinite offline Publish queueing
        client.configureDrainingFrequency(2)  # Draining: 2 Hz
        client.configureConnectDisconnectTimeout(10)  # 10 sec
        client.configureOfflinePublishQueueing(
            0)  # No offline Publish queueing
        client.configureConnectDisconnectTimeout(5)  # 5 sec
        client.configureMQTTOperationTimeout(5)  # 5 sec
        client.connect()
    return client
Exemplo n.º 2
0
    def config(self):
        print('Configure MQTT')
        # Cognito auth
        identityPoolID = cognitoIdentityPoolID
        cognitoIdentityClient = boto3.client('cognito-identity',
                                             region_name=region)

        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"]

        # AWSIoTMQTTClient configuration
        AWSIoTMQTTClient.configureEndpoint(self, host, port)
        AWSIoTMQTTClient.configureCredentials(self, rootCAPath)
        AWSIoTMQTTClient.configureIAMCredentials(self, AccessKeyId, SecretKey,
                                                 SessionToken)
        AWSIoTMQTTClient.configureAutoReconnectBackoffTime(self, 1, 32, 20)
        AWSIoTMQTTClient.configureOfflinePublishQueueing(
            self, -1)  # Infinite offline Publish queueing
        AWSIoTMQTTClient.configureDrainingFrequency(self, 2)  # Draining: 2 Hz
        AWSIoTMQTTClient.configureConnectDisconnectTimeout(self, 10)  # 10 sec
        AWSIoTMQTTClient.configureMQTTOperationTimeout(self, 5)  # 5 sec
        print('Configure MQTT done')
        return self
Exemplo n.º 3
0
 def GetInstance():
     if (MqttClient.mqttclient == None):
         MqttClient.mutex.acquire()
         if (MqttClient.mqttclient == None):
             rootCAPath = r"/home/mqtt/cert/3-Public-Primary-Certification-Authority-G5.pem"
             host = r""
             obtainedAccessKeyID = ""
             obtainedSecretAccessKey = ""
             obtainedSessionToken = ""
             mqttclient = AWSIoTMQTTClient(str(uuid.uuid1()),
                                           useWebsocket=True)
             mqttclient.configureEndpoint(host, 443)
             mqttclient.configureCredentials(rootCAPath)
             mqttclient.configureAutoReconnectBackoffTime(1, 32, 20)
             mqttclient.configureOfflinePublishQueueing(
                 -1)  # Infinite offline Publish queueing
             mqttclient.configureDrainingFrequency(10)  # Draining: 2 Hz
             mqttclient.configureConnectDisconnectTimeout(10)  # 10 sec
             mqttclient.configureMQTTOperationTimeout(10)  # 10 sec
             mqttclient.configureIAMCredentials(obtainedAccessKeyID,
                                                obtainedSecretAccessKey,
                                                obtainedSessionToken)
             mqttclient._mqttCore._pahoClient.on_log = mylog
             MqttClient.mqttclient = mqttclient
             try:
                 mqttclient.connect()
             except Exception, e:
                 logging.error('mqttclient connect error')
                 logging.error(e)
         MqttClient.mutex.release()
Exemplo n.º 4
0
def force_disconnect(client_id):
    print 'Attempting to force disconnect on client {}'.format(client_id)
    endpoint, endpoint_port = registration_shared.get_endpoint_and_port('WEBSOCKET')

    print 'Using endpoint {}:{}'.format(endpoint, endpoint_port)

    iot_client = AWSIoTMQTTClient(client_id, useWebsocket=True)
    iot_client.configureEndpoint(endpoint, endpoint_port)
    iot_client.configureConnectDisconnectTimeout(20)
    iot_client.configureMQTTOperationTimeout(5)
    iot_client.configureCredentials('AWSIoTPythonSDK/certs/rootCA.pem')

    access_key = os.environ.get('AWS_ACCESS_KEY_ID')
    secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
    session_token = os.environ.get('AWS_SESSION_TOKEN')
    iot_client.configureIAMCredentials(AWSAccessKeyID=access_key, AWSSecretAccessKey=secret_key, AWSSessionToken=session_token)

    print 'Configured credentials, attempting connect...'
    response = iot_client.connect()

    print 'Connect returns {}'.format(response)

    if response:
        print 'Disconnecting..'
        iot_client.disconnect()
Exemplo n.º 5
0
def publish_mqtt(user_data, secret_details, auth_credentials):
    # Init AWSIoTMQTTClient.
    # MQTT client can only connect if MQTT client is same as unique identity ID.
    # Client can only write to CognitoIdentityPoolId/IdentityID/*
    cognitoIdentityPoolID = user_data['cognitoIdentityPoolID']
    mqtttopic = cognitoIdentityPoolID + "/" + \
        auth_credentials['identityID'] + "/" + user_data['topic']
    # only allow client with identity id to conenct
    myAWSIoTMQTTClient = AWSIoTMQTTClient(auth_credentials['identityID'],
                                          useWebsocket=True)
    # AWSIoTMQTTClient configuration
    myAWSIoTMQTTClient.configureEndpoint(secret_details['host'], 443)
    myAWSIoTMQTTClient.configureCredentials(user_data['rootCAPath'])
    myAWSIoTMQTTClient.configureIAMCredentials(
        auth_credentials['AccessKeyId'], auth_credentials['SecretKey'],
        auth_credentials['SessionToken'])
    myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
    # Infinite offline Publish queueing
    myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1)
    myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
    myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
    myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec
    # Connect and subscribe to AWS IoT
    print("I am here")
    print("client id is:" + auth_credentials['identityID'])
    myAWSIoTMQTTClient.connect()
    myAWSIoTMQTTClient.subscribe(mqtttopic, 1, customCallback)
    time.sleep(2)
    # Publish to the same topic in a loop forever
    loopCount = 0
    while True:
        message = {'Message from authenticated cognito identity': loopCount}
        myAWSIoTMQTTClient.publish(mqtttopic, json.dumps(message), 1)
        loopCount += 1
        time.sleep(1)
Exemplo n.º 6
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 main():
    mqttclient = AWSIoTMQTTClient(clientId, useWebsocket=True) # Websocket SigV4を利用
    mqttclient.configureIAMCredentials(accessId, secretKey)
    mqttclient.configureCredentials(rootCA) # ルート証明書の設定が必要
    mqttclient.configureEndpoint(endPoint, mqttport)
    mqttclient.configureAutoReconnectBackoffTime(1, 32, 20)
    mqttclient.configureOfflinePublishQueueing(-1)
    mqttclient.configureDrainingFrequency(2)
    mqttclient.configureConnectDisconnectTimeout(10)
    mqttclient.configureMQTTOperationTimeout(5)
    mqttclient.connect()
    print("onConnect")
    mqttclient.subscribe(topic, 1, onSubscribe)
    while True:
        time.sleep(5)
Exemplo n.º 8
0
def aws_initialize(USERNAME, host="", rootCAPath="", cognitoIdentityPoolID=""):
    # Missing configuration notification
    missingConfiguration = False
    if not host:
        print("Missing '-e' or '--endpoint'")
        missingConfiguration = True
    if not rootCAPath:
        print("Missing '-r' or '--rootCA'")
        missingConfiguration = True
    if not cognitoIdentityPoolID:
        print("Missing '-C' or '--CognitoIdentityPoolID'")
        missingConfiguration = True
    if missingConfiguration:
        exit(2)

    identityPoolID = cognitoIdentityPoolID
    region = host.split('.')[2]
    cognitoIdentityClient = boto3.client('cognito-identity',
                                         region_name=region)

    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
    clientID = USERNAME + " Monitor"
    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

    return myAWSIoTMQTTClient
Exemplo n.º 9
0
 def connect(self):
     port =  443 # Cognito経由の認証では、Websocketしか使用できない
     rootCA = self.rootCA # ルート証明書も必要
     accessId, secretKey, token = self._getAuthentication(self.identityPoolId)
     client = AWSIoTMQTTClient(self.clientId, useWebsocket=True)
     client.configureIAMCredentials(accessId, secretKey, token)
     client.configureCredentials(rootCA)
     client.configureEndpoint(self.endPoint, port)
     client.configureAutoReconnectBackoffTime(1, 32, 20)
     client.configureOfflinePublishQueueing(-1)
     client.configureDrainingFrequency(2)
     client.configureConnectDisconnectTimeout(10)
     client.configureMQTTOperationTimeout(5)
     client.connect()
     print("mqtt connect.")
     client.subscribe(self.topic, 1, self._onSubscribe)
     print("mqtt subscrib.")
Exemplo n.º 10
0
def get_client(credentials):
    print(credentials['client_id'])
    myMQTTClient = AWSIoTMQTTClient(credentials['client_id'],
                                    useWebsocket=True)
    myMQTTClient.configureEndpoint(iot_host, 443)
    myMQTTClient.configureCredentials(
        './certs/VeriSign-Class 3-Public-Primary-Certification-Authority-G5.pem'
    )
    myMQTTClient.configureIAMCredentials(credentials['access_key_id'],
                                         credentials['secret_access_key'],
                                         credentials['session_token'])
    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

    return myMQTTClient
Exemplo n.º 11
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")
Exemplo n.º 12
0
class aws_iot():
    def __init__(self):
        self.client = AWSIoTMQTTClient("myClientID", useWebsocket=True)

    def aws_connect(self):
        self.client.configureEndpoint("a247jnsfrl6hqw-ats.iot.ap-south-1.amazonaws.com", 443)
        # AWS IoT MQTT Client
        self.client.configureIAMCredentials('AKIAW4YHSL77QXB37PUS', 'jCCtCV6PLsZB8d9eU3SzQ4PVakVxc5+WUoRskJ4q')
        cwd = os.getcwd()
        crt_path = os.path.join(cwd,"root_ca.crt")
        print(crt_path)
        self.client.configureCredentials(crt_path)
        self.client.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
        self.client.configureDrainingFrequency(2)  # Draining: 2 Hz
        self.client.configureConnectDisconnectTimeout(10)  # 10 sec
        self.client.configureMQTTOperationTimeout(5)  # 5 sec
        return self.client.connect()

    def aws_publish(self, data):
        return self.client.publish("skc", data, 1)
Exemplo n.º 13
0
def Setup():
    # Cleanup
    signal.signal(signal.SIGTERM, Cleanup)

    # Stat
    activeLed.on()

    # MQTT
    cognitoIdentityClient = boto3.client('cognito-identity',
                                         region_name=region)
    temporaryIdentityId = cognitoIdentityClient.get_id(IdentityPoolId=poolId)
    identityId = temporaryIdentityId["IdentityId"]

    temporaryCredentials = cognitoIdentityClient.get_credentials_for_identity(
        IdentityId=identityId)
    accessKeyId = temporaryCredentials["Credentials"]["AccessKeyId"]
    secretKey = temporaryCredentials["Credentials"]["SecretKey"]
    sessionToken = temporaryCredentials["Credentials"]["SessionToken"]

    mqttClient = AWSIoTMQTTClient(clientId, useWebsocket=True)
    mqttClient.configureEndpoint(endpoint, port)
    mqttClient.configureCredentials(rootCaPath)
    mqttClient.configureIAMCredentials(accessKeyId, secretKey, sessionToken)

    # Base back off(s), max back off(s), stable time(s)
    mqttClient.configureAutoReconnectBackoffTime(1, 32, 20)

    # 0: disabled, -1: infinite queueing
    mqttClient.configureOfflinePublishQueueing(-1)

    # Frequency of draining in seconds when connection is established
    mqttClient.configureDrainingFrequency(2)

    # Time in seconds to wait for CONNACK or disconnect
    mqttClient.configureConnectDisconnectTimeout(10)

    # General timeout in seconds for MQTT operations
    mqttClient.configureMQTTOperationTimeout(5)

    mqttClient.connect()
    mqttClient.subscribe(topic, 1, MessageReceived)
    def __init__(self, host, rootCAPath, cognitoIdentityPoolID):

        self.host = host
        self.rootCAPath = rootCAPath
        self.cognitoIdentityPoolID = cognitoIdentityPoolID

        # Cognito auth
        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)
        self.accesskeyid = temporaryCredentials["Credentials"]["AccessKeyId"]
        self.secretkeyid = temporaryCredentials["Credentials"]["SecretKey"]
        self.sessiontoken = temporaryCredentials["Credentials"]["SessionToken"]

        # Init AWSIoTMQTTClient
        myAWSIoTMQTTClient = AWSIoTMQTTClient("healthmonitoriot",
                                              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
Exemplo n.º 15
0
def setup():
    root_ca_file = "root-ca.pem"

    # Get the CA cert if we need it
    if not path.exists(root_ca_file):
        request = requests.get(
            'https://www.amazontrust.com/repository/AmazonRootCA1.pem',
            allow_redirects=True)
        open(root_ca_file, 'wb').write(request.content)

    # Get the hostname for the customer's ATS endpoint in this region
    iot_client = boto3.client('iot')
    iot_data = iot_client.describe_endpoint(endpointType='iot:Data-ATS')
    host = iot_data['endpointAddress']

    # Get temporary credentials
    sts_client = boto3.client('sts')
    sts_data = sts_client.get_session_token()

    # Extract the temporary credential values
    credentials = sts_data['Credentials']
    access_key_id = credentials['AccessKeyId']
    secret_access_key = credentials['SecretAccessKey']
    session_token = credentials['SessionToken']

    # Create an MQTT client with a random client ID that uses WebSockets
    mqtt_client = AWSIoTMQTTClient(str(uuid.uuid4()), useWebsocket=True)
    # Use port 443 + ALPN on the customer's ATS endpoint
    mqtt_client.configureEndpoint(host, 443)
    # Explicitly enable the root CA we downloaded
    mqtt_client.configureCredentials(root_ca_file)

    # Configure the library to use the specified credentials instead of using another provider to fetch them
    AWSIoTMQTTClient.configureIAMCredentials(mqtt_client, access_key_id,
                                             secret_access_key, session_token)

    return mqtt_client
Exemplo n.º 16
0
# 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)
    myAWSIoTMQTTClient.configureIAMCredentials(clientId, keyId)
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
myAWSIoTMQTTClient.connect()
if args.mode == 'both' or args.mode == 'subscribe':
Exemplo n.º 17
0
def awsSimulationWS():
    from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
    import logging
    import time
    import argparse
    import json
    import random

    deviceName = "awsDevice"
    frequency = 5
    timeInterval = 10
    minRange = 10
    maxRange = 100
    topic = "sdk/test/Python"
    obtainedSessionToken = "FQoGZXIvYXdzELH//////////wEaDB4pvTJDS5l4fphjniKYAXKoJCbvQSsAwk23qFdIzESPpKcts38dSpTgyoZtsPLZg/aDL3NR1Vj1LXJpL36z8f3Syt/F7gdNIDME6ZdpH1G/xCAWT10YHM5GL6FKkoJLHiFL3vHAmQU5Tqgqfko+gy4PRJ5yijhQcg/FiR4IYcHVAox9Kl/5d0M59RusolYfGiBygprF9HXn914lZO4A962qS7kEs9R/KP7q8OwF"
    # For certificate based connection
    # myMQTTClient = AWSIoTMQTTClient("basicPubSub")
    # For Websocket connection
    myMQTTClient = AWSIoTMQTTClient("myClientID", useWebsocket=True)
    # Configurations
    # For TLS mutual authentication
    # myMQTTClient.configureEndpoint("a2on3hwushji1e-ats.iot.us-east-2.amazonaws.com", 8883)
    # For Websocket
    myMQTTClient.configureEndpoint(
        "a2on3hwushji1e-ats.iot.us-east-2.amazonaws.com", 443)

    myMQTTClient.configureIAMCredentials(
        "ASIA6FC44LEDBU2CLYC7", "/I7X+ieIAv20k0UGxq3hi0CpIdKQw3Sy4kb3+PGC",
        obtainedSessionToken)
    # AWS IoT MQTT Shadow Client
    # For TLS mutual authentication with TLS ALPN extension
    # myMQTTClient.configureEndpoint("a2on3hwushji1e-ats.iot.us-east-2.amazonaws.com", 443)
    # myMQTTClient.configureCredentials("../static/certificates/awsDevice/root-CA.crt","../static/certificates/awsDevice/testDevice.private.key", "../static/certificates/awsDevice/testDevice.cert.pem")
    # For Websocket, we only need to configure the root CA
    myMQTTClient.configureCredentials(
        "../static/certificates/awsDevice/root-CA.crt")
    # Infinite offline Publish queueing
    myMQTTClient.configureOfflinePublishQueueing(-1)
    myMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
    myMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
    myMQTTClient.configureMQTTOperationTimeout(5)  # 5 sec

    myMQTTClient.connect()
    print(
        "done=================================================================="
    )

    # myMQTTClient.publish("sdk/test/Python", "myPayload", 0)
    # #myMQTTClient.subscribe("sdk/test/Python", 1, customCallback)
    # # myMQTTClient.unsubscribe("sdk/test/Python")
    # myMQTTClient.disconnect()

    def valueGen():
        a = random.randint(minRange, maxRange)
        return a

    loopCount = 0
    while loopCount < frequency:

        message = {}
        value = valueGen()
        message['value'] = value
        messageJson = json.dumps(message)
        myMQTTClient.publish(topic, messageJson, 1)
        print('Published topic %s: %s\n' % (topic, messageJson))
        loopCount += 1
        time.sleep(timeInterval)
# 認証情報取得
clientId = mqtt_dict['CLIENT_ID']
endPoint = mqtt_dict['ENDPOINT']
port = mqtt_dict['PORT']  # Cognito経由の認証では、Websocket SigV4 しか使用できない
rootCA = mqtt_dict['ROOT_CA']
accessId = mqtt_dict['ACCESS_ID']
secretKey = mqtt_dict['SECRET_KEY']

# TOPIC
SUB_TOPIC = "#"
PUB_TOPIC_1 = clientId + "/test"
PUB_TOPIC_2 = clientId + "/alert/fromServer"

client = AWSIoTMQTTClient(clientId, useWebsocket=True)  # Websocket SigV4を利用
client.configureIAMCredentials(accessId, secretKey)
client.configureCredentials(rootCA)  # ルート証明書の設定が必要
client.configureEndpoint(endPoint, port)
client.configureAutoReconnectBackoffTime(1, 32, 20)
client.configureOfflinePublishQueueing(-1)
client.configureDrainingFrequency(2)
client.configureConnectDisconnectTimeout(10)
client.configureMQTTOperationTimeout(5)


# Subscribe したときに呼び出される
def onSubscribe(client, userdata, message):
    print("= Subscribe ========================")
    print("message:{} topic:{}".format(message.payload, message.topic))
    print("topic: " + message.topic)
    print("payload: " + str(message.payload.decode('utf-8')))
class SimonGame:
    def __init__(self, deviceId):
        self.deviceId = deviceId
        self.gamerunning = False
        self.currentGame = None
        self.accesstimer = None
        self.gameMQTTClient = None
        self.requestRemoteAccess()

    def startGame(self, client, userdata, gamedata):
        if self.gamerunning:
            return
        self.gamerunning = True
        print("start game")
        #print(gamedata.payload.decode("utf-8"))
        self.currentGame = json.loads(gamedata.payload.decode("utf-8"))
        print(self.currentGame)
        self.gametimer = Timer(45, self.submitGameResults)
        self.gametimer.start()
        self.playSound()

    def downloadSoundClip(self, key):
        print("download sound clip")
        r = requests.get(STATICFILES + "/music/" + key, stream=True)
        if r.status_code == 200:
            with open("/tmp/" + key, "wb") as f:
                r.raw.decode_content = True
                shutil.copyfileobj(r.raw, f)

    def playSound(self):
        soundclip = self.currentGame["name"]
        if self.currentGame["simonsays"]:
            soundclip += "_simon.mp3"
        else:
            soundclip += ".mp3"

        if not os.path.isfile('/tmp/' + soundclip):
            print("Need to download file: " + soundclip)
            self.downloadSoundClip(soundclip)

        try:
            mixer.init()
            mixer.music.load('/tmp/' + soundclip)
            mixer.music.play()
        except Exception as e:
            msg = "Test failed: " + str(e)
            print msg

    def submitGameResults(self):
        self.gamerunning = False
        if self.gametimer is not None:
            self.gametimer.cancel()
        print("Submit Game Results")

    # Join the global MQTT Simon Game Service
    def requestRemoteAccess(self):
        if self.accesstimer is not None:
            self.accesstimer.cancel()

        if self.gameMQTTClient is not None:
            self.gameMQTTClient.disconnect()

        print("Request Access")
        req = requests.get(APISERVER + '/prod/activate',
                           {"deviceId": self.deviceId},
                           headers={"x-api-key": APIKEY})
        cred = req.json()

        self.gameMQTTClient = AWSIoTMQTTClient(self.deviceId,
                                               useWebsocket=True)
        self.gameMQTTClient.configureCredentials("./caroot.pem")
        self.gameMQTTClient.configureEndpoint(cred['iotEndpoint'], 443)
        self.gameMQTTClient.configureIAMCredentials(cred["accessKey"],
                                                    cred["secretKey"],
                                                    cred["sessionToken"])
        if self.gameMQTTClient.connect():
            print("connected to global MQTT service")
        if self.gameMQTTClient.subscribe("simongame", 0, self.startGame):
            print("subscribed to simon game channel")

        self.accesstimer = Timer(60 * 45, self.requestRemoteAccess)

    def getCurrentGame(self):
        return self.currentGame
# For Websocket connection
myMQTTClient = AWSIoTMQTTClient("myClientID", useWebsocket=True)
# Configurations
# For TLS mutual authentication
# For Websocket
myMQTTClient.configureEndpoint("a1zetnmz2w4vck.iot.us-east-2.amazonaws.com",
                               443)
# For TLS mutual authentication with TLS ALPN extension
# myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443)

# For Websocket, we only need to configure the root CA
myMQTTClient.configureCredentials("./certificate/aws-iot-rootCA.crt")
# AWS IoT MQTT Client
# myMQTTClient.configureIAMCredentials(obtainedAccessKeyID, obtainedSecretAccessKey, obtainedSessionToken)
# https://console.aws.amazon.com/iam/ --> users --> create access key
myMQTTClient.configureIAMCredentials(
    "AKIAIMPUZ4N6PLLCB2VA", "sXWou67p1ZJSKMua3kaOZ7r2BThOonLTkKNA5xQu", "")

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


def customCallback(client, userdata, message):
    print("Received a new message: ")
    print(client)
    print(userdata)
    print("from topic: ")
    print(message.topic)
    print(message.payload)
Exemplo n.º 21
0
            message['message'] = json.dumps({"source":device_name, "data":private_data})
            message['sequence'] = pri_loopCount
            messageJson = json.dumps(message)
            myAWSIoTMQTTClient.publish(private_topic, messageJson, 1)
            pri_loopCount += 1
            time.sleep(2)
    except:
        sys.exit()

if __name__ == '__main__':
    # Init AWSIoTMQTTClient
    myAWSIoTMQTTClient = None
    myAWSIoTMQTTClient = AWSIoTMQTTClient(device_name, useWebsocket=True)
    myAWSIoTMQTTClient.configureEndpoint(endpoint, port)
    myAWSIoTMQTTClient.configureCredentials(server_root_ca_file)
    myAWSIoTMQTTClient.configureIAMCredentials(access_key_id, 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(5)  # 5 sec

    # Connect and subscribe to AWS IoT
    myAWSIoTMQTTClient.connect()
    myAWSIoTMQTTClient.subscribe(private_topic, 1, customCallback)
    time.sleep(2)

    pub_msg()
Exemplo n.º 22
0
class AWSIoTOperation:
    '''
    AWS IoT Core Error Code and Error Message
    400: Bad Request - .Invalid JSON
                       .Missing required node: state
                       .State node must be an object
                       .Desired node must be an object
                       .Reported node must be an object
                       .Invalid version
                       .Invalid clientToken
                       .JSON contains too many levels of nesting; maximum is 6
                       .State contains an invalid node
    401: Unauthorized
    403: Forbidden
    404: Not Found
    409: Conflict
    410: Limit Exceeded
    413: Payload Too Large - The payload exceeds the maximum size allowed
    415: Unsupported Media Type - Unsupported documented encoding; supported encoding is UTF-8
    422: Failed to Process Request
    429: Too Many Requests - The Device Shadow service will generate this error message when there are more than 10 in-flight requests
    500: Internal Server Error
    503: Service Unavailable
    '''
    def __init__(self, setting=None):
        self.setting = setting
        self.fleet_indexing = False
        if 'fleet_indexing' in self.setting:
            if self.setting['fleet_indexing'] == 'true':
                self.fleet_indexing = True
        # login by cli for update "~/.aws/credentials"
        if os.path.exists("~/.aws/credentials") == False:
            os.system("mkdir -p ~/.aws")
            os.system("echo \"{}\" > ~/.aws/credentials".format("""[default]
aws_access_key_id={}
aws_secret_access_key={}""".format(self.setting['access_key_id'],
                                   self.setting['secret_access_key'])))

        # os.system("AWS_ACCESS_KEY_ID={} AWS_SECRET_ACCESS_KEY={} aws ecr get-login --no-include-email --region {}".format(
        #         self.setting['access_key_id'],
        #         self.setting['secret_access_key'],
        #         self.setting['region_name']))

        self.iot = boto3.client(
            'iot',
            region_name=self.setting['region_name'],
            aws_access_key_id=self.setting['access_key_id'],
            aws_secret_access_key=self.setting['secret_access_key'])

        self.shadow = boto3.client('iot-data',
                                   region_name=self.setting['region_name'])
        self.account_id = boto3.client('sts').get_caller_identity()['Account']
        self.things_content = []
        self.myAWSIoTMQTTClient = None

    def search_devices(self):
        if self.fleet_indexing == True:
            response = self.iot.search_index(indexName='AWS_Things',
                                             queryString='thingName: *',
                                             maxResults=250,
                                             queryVersion='2017-09-30')
        else:
            response = self.iot.list_things()

        devices = []
        for device in response['things']:
            new_dev = {
                'name': device['thingName'],
                'desired': {},
                'reported': {},
                'timestamp': 0,
                'connected': False,
            }

            if 'connectivity' in device:
                new_dev['connected'] = device['connectivity']['connected']
                new_dev['timestamp'] = device['connectivity']['timestamp']

            if 'shadow' not in device:
                devices.append(new_dev)
                continue

            shadow = json.loads(device['shadow'])
            if 'desired' in shadow:
                new_dev['desired'] = shadow['desired']
            if 'reported' in shadow:
                new_dev['reported'] = shadow['reported']

            devices.append(new_dev)
        self.things_content = devices
        return self.things_content

    def search_device(self, name):
        stream_body = self.shadow.get_thing_shadow(thingName=name)["payload"]
        shadows_data = json.loads(stream_body.read())
        response = {
            'things': [
                {
                    'thingName': name,
                    'connectivity': {
                        'connected': False
                    },
                    'shadow': json.dumps(shadows_data['state']),
                },
            ]
        }

        if self.fleet_indexing == True:
            index = self.iot.search_index(indexName='AWS_Things',
                                          queryString='thingName: ' + name,
                                          maxResults=250,
                                          queryVersion='2017-09-30')
            if len(index) > 0:
                response['things'][0]['connectivity']['connected'] = index[
                    'things'][0]['connectivity']['connected']
                response['things'][0]['connectivity']['timestamp'] = index[
                    'things'][0]['connectivity']['timestamp']

        devices = []
        for device in response['things']:
            new_dev = {
                'name': device['thingName'],
                'desired': {},
                'reported': {},
                'timestamp': 0,
                'connected': device['connectivity']['connected'],
            }
            if 'shadow' not in device:
                devices.append(new_dev)
                continue

            shadow = json.loads(device['shadow'])
            if 'desired' in shadow:
                new_dev['desired'] = shadow['desired']
            if 'reported' in shadow:
                new_dev['reported'] = shadow['reported']
            if 'timestamp' in device['connectivity']:
                new_dev['timestamp'] = device['connectivity']['timestamp']
            devices.append(new_dev)
        return devices

    def get_properties(self, name):
        for device in self.things_content:
            if device['name'] == name:
                return {
                    'desired': device['desired'],
                    'reported': device['reported']
                }
        return {'desired': {}, 'reported': {}}

    def desired(self, device_name, desired_payload):
        desired_dict = json.loads(desired_payload)
        data = {"state": {"desired": desired_dict}}
        response = self.shadow.update_thing_shadow(
            thingName=device_name, payload=json.dumps(data).encode("utf-8"))
        return response['ResponseMetadata']['HTTPStatusCode']

    def message_callback(self, client, userdata, message):
        print(message.topic)
        print(message.payload.decode('utf-8'))
        self.callback(message.topic, message.payload.decode('utf-8'))

    def unsubscribe_messages(self, topic):
        if self.myAWSIoTMQTTClient == None:
            return
        self.myAWSIoTMQTTClient.unsubscribe(topic)
        self.myAWSIoTMQTTClient.disconnect()

    def subscribe_messages(self, callback, topic='#', second=-1):
        self.callback = callback
        self.myAWSIoTMQTTClient = None
        self.myAWSIoTMQTTClient = AWSIoTMQTTClient('', useWebsocket=True)
        self.myAWSIoTMQTTClient.configureIAMCredentials(
            self.setting['access_key_id'], self.setting['secret_access_key'])
        self.myAWSIoTMQTTClient.configureEndpoint(self.setting['host'], 443)
        self.myAWSIoTMQTTClient.configureCredentials(
            self.setting['root_ca_path'])
        if self.myAWSIoTMQTTClient.connect() == False:
            print('connect failed')
            self.myAWSIoTMQTTClient = None
            return

        print('connect:ok, subscribe topic[%s] %d sec\n' % (topic, second))

        self.myAWSIoTMQTTClient.subscribe(topic, 1, self.message_callback)
        if second <= 0:
            return

        time.sleep(second)
        self.myAWSIoTMQTTClient.unsubscribe(topic)
        self.myAWSIoTMQTTClient.disconnect()
        self.myAWSIoTMQTTClient = None

    def open_tunnel(self, device_id, service, port):
        p = subprocess.Popen([
            'aws', 'iotsecuretunneling', 'open-tunnel', '--destination-config',
            'thingName={},services={}'.format(device_id, service),
            '--timeout-config', 'maxLifetimeTimeoutMinutes=30', '--region',
            self.setting['region_name']
        ],
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        output, err = p.communicate()
        rc = p.returncode
        if rc != 0:
            return err

        token = json.loads(output)['sourceAccessToken']
        # setup tunnel conf
        os.system("mkdir -p /data")
        os.system("echo \"{}\" > /data/.aws_tunnel.ini".format("""region = {}
source-listen-port = {}
access-token = {}""".format(self.setting['region_name'], port, token)))
        # start tunnel service
        # os.system("docker kill aws-tunnel 2> /dev/null")
        # os.system("docker rm -f aws-tunnel 2> /dev/null")
        # os.system(
        #     'docker run -d --network host -v /tmp/:/tmp/ --name aws-tunnel bibbylong/aws-localproxy-cli:1.0.1-amd64 sh -c "localproxy --config /tmp/.aws_tunnel.ini"')
        return ''

    def command(self, device_id, name, payload, retry_time=10):
        job_id = "{}_{}".format(
            device_id,
            datetime.datetime.now().strftime('%Y%m%d%H%M%S%f'))
        status, response = self.create_jobs([device_id], name, payload, job_id)
        if status < 200 or status > 299:
            return status, {'error': 'create command failed'}

        for i in range(retry_time):
            try:
                job_info = self.get_job_exec_status(device_id, job_id)
                if job_info['status'] != 'IN_PROGRESS' and job_info[
                        'status'] != 'QUEUED':
                    break
                time.sleep(1)
            except:
                time.sleep(1)

        if job_info['status'] == 'IN_PROGRESS' or job_info[
                'status'] == 'QUEUED':
            return 400, {'error': 'command panding'}
        elif job_info['status'] == 'SUCCEEDED':
            try:
                json_object = json.loads(
                    job_info['statusDetails']['detailsMap']['data'])
                return 200, json_object
            except ValueError as e:
                return 200, {
                    'data': job_info['statusDetails']['detailsMap']['data']
                }
        else:
            return 400, {'error': 'process command failed'}

    def get_shadow(self, device_id):
        response = self.shadow.get_thing_shadow(thingName=device_id)
        status = response['ResponseMetadata']['HTTPStatusCode']
        result = json.loads(response['payload'].read().decode('utf-8'))
        result.pop('metadata', None)
        return status, result

    def update_shadow(self, device_id, data):
        # data format example:
        # data = {'state': {'desired': {'general': {'description': 'new name'}}}}
        try:
            response = self.shadow.update_thing_shadow(
                thingName=device_id, payload=json.dumps(data).encode('utf-8'))
            status = response['ResponseMetadata']['HTTPStatusCode']
            result = json.loads(response['payload'].read().decode('utf-8'))
        except botocore.exceptions.ClientError as err:
            status = err.response['ResponseMetadata']['HTTPStatusCode']
            result = err.response
        return status, result

    def get_application_list(self, device_id):
        status, shadow = self.get_shadow(device_id)
        list = []
        if 'state' in shadow and 'reported' in shadow['state']:
            reported = shadow['state']['reported']
            if 'applications' in reported and 'list' in reported[
                    'applications']:
                list = reported['applications']['list']
        return status, list

    def install_application(self, device_id, app_url):
        params = json.dumps({'url': app_url})
        status, response = self.create_jobs(
            [device_id], 'thingspro-applications-installation', params,
            datetime.datetime.now().strftime('%Y%m%d%H%M%S%f'))
        return status, response

    def application_control(self, device_id, app_name, action):
        if action in ['start', 'stop', 'restart']:
            params = json.dumps({'appName': app_name, 'command': action})
            status, response = self.create_jobs(
                [device_id], 'thingspro-applications-control', params,
                datetime.datetime.now().strftime('%Y%m%d%H%M%S%f'))
            return status, response
        else:
            return 400, None

    def create_jobs(self, device_id_list, method, params, job_id):
        body = json.dumps({'name': method, 'payload': params})
        target_list = []
        for device_id in device_id_list:
            target_string = 'arn:aws:iot:%s:%s:thing/%s' % (
                self.setting['region_name'], self.account_id, device_id)
            target_list.append(target_string)
        try:
            response = self.iot.create_job(jobId=job_id,
                                           targets=target_list,
                                           document=body,
                                           description='create a new job',
                                           targetSelection='SNAPSHOT')
            status = response['ResponseMetadata']['HTTPStatusCode']
        except botocore.exceptions.ClientError as err:
            print(err)
            status = err.response['ResponseMetadata']['HTTPStatusCode']
            response = err.response
        return status, response

    def reboot(self, device_id_list):
        status, response = self.create_jobs(
            device_id_list, 'system-reboot', '{}',
            datetime.datetime.now().strftime('%Y%m%d%H%M%S%f'))
        return status, response

    def get_all_jobs(self, count):
        if count > 250:
            count = 250
        response = self.iot.list_jobs(maxResults=count)
        return response['jobs']

    def get_device_jobs(self, device_id, count=250):
        if count > 250:
            count = 250
        response = self.iot.list_job_executions_for_thing(thingName=device_id,
                                                          maxResults=count)
        return response['executionSummaries']

    def get_job(self, job_id):
        response = self.iot.describe_job(jobId=job_id)
        return response['job']

    def get_job_exec_status(self, device_id, job_id):
        response = self.iot.describe_job_execution(
            jobId=job_id,
            thingName=device_id,
        )
        return response['execution']

    def get_job_payload(self, job_id):
        response = self.iot.get_job_document(jobId=job_id)
        return response['document']
Exemplo n.º 23
0
class AwsIotMessageHubClient(AbstractMessageHubClient):
    def __init__(self,
                 host,
                 port,
                 access_key,
                 secret_key,
                 cert_path,
                 client_id,
                 osc_client=None):
        """
        :param str host:
        :param int port:
        :param str cert_path:                  The path to the aws root ca file
                                               that allows this client access to
                                               the Aws Iot service.
        :param str client_id:                  A string (name) that identifies
                                               this client within the Aws Iot
                                               message broker (this should be
                                               unique per client).
        :param str access_key:                 The AWS access key for the IoT
                                               platform.
        :param str secret_key:                 The AWS secret key for the IoT
                                               platform.
        :param OscMessageHubClient osc_client: An OscMessageHubClient object
                                               that is optional in case it is
                                               needed for a message callback.
        """
        super(AwsIotMessageHubClient, self).__init__(host, port)
        self.cert_path = cert_path
        self.client_id = client_id
        self.osc_client = osc_client
        self._access_key = access_key
        self._secret_key = secret_key

    def connect(self):
        try:
            self._client = AWSIoTMQTTClient(self.client_id, useWebsocket=True)
            self._client.configureEndpoint(self.host, self.port)
            self._client.configureIAMCredentials(self._access_key,
                                                 self._secret_key)
            self._client.configureCredentials(self.cert_path)

            self._client.configureAutoReconnectBackoffTime(1, 32, 20)
            self._client.configureOfflinePublishQueueing(-1)
            self._client.configureDrainingFrequency(2)
            self._client.configureConnectDisconnectTimeout(10)
            self._client.configureMQTTOperationTimeout(5)

            self._client.connect()
        except (OSError, ValueError,
                AWSIoTExceptions.connectTimeoutException) as err:
            raise MessageHubConnectionError(err) from None

    def disconnect(self):
        if not self._client.disconnect():
            raise MessageHubConnectionError(
                "AwsIotPythonSDK disconnect error!")

    def publish(self, channel, message):
        if not self._client.publish(channel, message, 1):
            raise MessageHubSubscribeError("AwsIotPythonSDK publish error!")

    def subscribe(self, channels):
        for channel in channels:
            if not self._client.subscribe(channel, 1, self._message_callback):
                raise MessageHubSubscribeError(
                    "AwsIotPythonSDK subscribe error!")

    def _message_callback(self, client, user_data, message):
        if self.osc_client is not None:
            self.osc_client.publish(message.topic, message.payload)
Exemplo n.º 24
0
                     headers={'Authorization': op_auth})
    creds = json.loads(r.data.decode())['data']
    # print(json.dumps(creds, indent=2))
    print('fetched credentials')

    client = AWSIoTMQTTClient(creds['clientId'], useWebsocket=True)
    print('created client')

    client.configureEndpoint(creds['atsEndpoint'], 443)
    print('configured endpoint')

    client.configureCredentials('./AmazonRootCA1.pem')
    print('configured root CA')

    client.configureIAMCredentials(creds['accessKeyId'],
                                   creds['secretAccessKey'],
                                   creds['sessionToken'])
    print('configured IAM credentials')

    client.connect()
    print('connected')

    for topic in creds['subscribeTopics']:
        client.subscribe(topic, 1, messageHandler)
        print('subscribed', topic)

    r = sess.request('POST',
                     '%s/orgs/%s/acus/%s/refreshShadow' %
                     (api_base, org_id, acu_id),
                     headers={'Authorization': op_auth})
    print('requested shadow refresh')
Exemplo n.º 25
0
def main():
    logger = logging.getLogger("AWSIoTPythonSDK.core")
    logger.setLevel(logging.DEBUG)
    stream_handler = logging.StreamHandler()
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    )
    stream_handler.setFormatter(formatter)
    logger.addHandler(stream_handler)

    args = parse_args()

    if args.region:
        region_name = args.region
    else:
        region_name = get_region()

    if args.domain:
        domain_name = args.domain
    else:
        domain_name = "prod"

    if args.cp_endpoint_url:
        cp_endpoint_url = args.cp_endpoint_url
    else:
        cp_endpoint_url = get_cp_endpoint_url(domain=domain_name, region=region_name)

    session = boto3.session.Session(region_name=region_name)

    if args.name:
        client_id = args.name
    else:
        client_id = (
            get_client_id()
        )  # This will set the client-id based on the ec2 instance id

    if not client_id:
        logging.info("Failed to determine client_id, quitting")
        exit(1)

    logging.info(
        "Running agent with domain: {}, region: {}, clientId: {}, cp_endpoint_url: {}".format(
            domain_name, region_name, client_id, cp_endpoint_url
        )
    )

    ca_cert_file = get_root_ca()

    if args.mqtt_endpoint:
        mqtt_endpoint = args.mqtt_endpoint
    else:
        logging.info("Attempting to retrieve Mqtt endpoint")
        mqtt_endpoint = get_mqtt_endpoint(session, cp_endpoint_url)

    logging.info("Using Mqtt endpoint: {}".format(mqtt_endpoint))

    iot_client = AWSIoTMQTTClient(client_id, useWebsocket=True)
    iot_client.configureEndpoint(mqtt_endpoint, 443, region_name)
    credentials = session.get_credentials()
    iot_client.configureCredentials(ca_cert_file.name)
    iot_client.configureIAMCredentials(
        credentials.access_key, credentials.secret_key, credentials.token
    )

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

    # Connect and subscribe to AWS IoT
    iot_client.connect()
    sleep(2)
    topic = "$aws/things/{}/defender/metrics/{}".format(client_id, "json")
    # Subscribe to the accepted/rejected topics to indicate status of published metrics reports
    # topic=subscribe_to_topic, callback=callback, QoS=1,
    iot_client.subscribe(
        topic="{}/accepted".format(topic), callback=ack_callback, QoS=1
    )
    iot_client.subscribe(
        topic="{}/rejected".format(topic), callback=ack_callback, QoS=1
    )

    start_metrics_collection(
        region_name=region_name,
        cp_endpoint_url=cp_endpoint_url,
        client_id=client_id,
        iot_client=iot_client,
        topic=topic,
        sample_rate=300,
    )

    ca_cert_file.close()
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)

# Publish to the same topic in a loop forever
loopCount = 0
while True:
    myAWSIoTMQTTClient.publish(topic, "New Message " + str(loopCount), 1)

# Change Repoted Value
def report_status(name, val):
    obj = {'state': {'reported': {name: val}}}
    client.publish(aws_topic_shadow, json.dumps(obj), 0)


# GPIO Initialization
pig = pigpio.pi()
pig.set_mode(17, pigpio.OUTPUT)
pig.write(17, 0)
print('GPIO Initialization Finished !')

# Connect AWS IoT Core
client = AWSIoTMQTTClient('', useWebsocket=True)
client.configureIAMCredentials(aws_iam_key, aws_iam_secret_key)
client.configureCredentials(aws_root_ca_path)
client.configureEndpoint(aws_endpoint, aws_port)
client.connect()
#client.subscribe(aws_topic_shadow_delta, 1, callback)
client.subscribe(aws_topic_shadow, 1, callback)

print('AWS IoT Core Connection & Subscription Established !')

try:
    while True:
        time.sleep(5)
except KeyboardInterrupt:
    pig.stop()
shadow_client.connect()

device_shadow_handler = shadow_client.createShadowHandlerWithName(
    THING_NAME, True)

device_shadow_handler.shadowRegisterDeltaCallback(delta_callback)
current_state = {**DEFAULT_STATE, 'door_is_closed': check_door_is_closed()}
mqtt_connection = shadow_client.getMQTTConnection()
mqtt_connection.subscribe(current_state['request_door_state_topic'], 0,
                          on_request_door_state)

device_shadow_handler.shadowUpdate(make_shadow_json(current_state),
                                   update_callback, 5)

c = AWSIoTMQTTClient()
c.configureIAMCredentials()

# Main loop
is_closed = None
while True:
    time.sleep(1)

    old_is_closed = is_closed
    is_closed = check_door_is_closed()
    if is_closed != old_is_closed:
        print('Space is occupied!' if is_closed else 'Space is unoccupied!')
        current_state['door_is_closed'] = is_closed
        device_shadow_handler.shadowUpdate(make_shadow_json(current_state),
                                           update_callback, 5)
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)

# Publish to the same topic in a loop forever
loopCount = 0
while True:
    myAWSIoTMQTTClient.publish(topic, "New Message " + str(loopCount), 1)
Exemplo n.º 30
0
def event_loop(event_queue, ui=None):
    gs = game_state.GameState()
    ignore_period = None

    # for certificate based connection
    myMQTTClient = AWSIoTMQTTClient("pi", useWebsocket=True)
    # For Websocket connection
    # myMQTTClient = AWSIoTMQTTClient("myClientID", useWebsocket=True)
    # Configurations
    # For TLS mutual authentication
    myMQTTClient.configureEndpoint("a1h19cgwtbfelq-ats.iot.us-west-2.amazonaws.com", 443)
    # For Websocket
    # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443)
    # For TLS mutual authentication with TLS ALPN extension
    # myMQTTClient.configureEndpoint("YOUR.ENDPOINT", 443)
    myMQTTClient.configureIAMCredentials("insert here", "insert here")
    myMQTTClient.configureCredentials("ca.pem")
    # 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()
    print('connected')
    myMQTTClient.subscribe('golf/switchPlayer', 0, functools.partial(aws_switch_player, event_queue))
    myMQTTClient.subscribe('golf/ping', 0, functools.partial(aws_ping, event_queue))
    myMQTTClient.subscribe('golf/quit', 0, functools.partial(aws_quit, event_queue))
    print('subscribed')
    while True:
        print('event: event_queue waiting')
        event = event_queue.get()
        if event is None:
            return  # Poison pill
        elif event[0] == EventTypes.IGNORE_PERIOD:
            print('event:ignore period')
            ignore_period = event[1]
        elif event[0] == EventTypes.USB_MOTION0 and (ignore_period is None or event[1] - ignore_period > datetime.timedelta(seconds=4)):
            print('event:start motion')
            remaining_time = datetime.timedelta(seconds=3.75)
            deferred_events = []
            while True:
                try:
                    next_event = event_queue.get(timeout=remaining_time.total_seconds())
                    if next_event[0] == EventTypes.USB_MOTION0:
                        pass
                    elif next_event[0] != EventTypes.USB_MOTION1 and next_event[0] != EventTypes.PICAM_MOTION:
                        deferred_events.append(event)
                    else:
                        remaining_time -= next_event[1] - event[1]
                        if next_event is None:
                            return # More poison ppill
                        elif remaining_time.total_seconds() < 0 or next_event[0] == EventTypes.PICAM_MOTION:
                            raise queue.Empty()
                        elif next_event[0] == EventTypes.USB_MOTION1:
                            print('event: made shot!')
                            gs.add_shot(event[1], True)
                            myMQTTClient.publish('golf/update', json.dumps(get_message_dict(gs, True)), 0)
                            break
                except queue.Empty as e:
                    print('event: missed shot! empty queue')
                    gs.add_shot(event[1], False)
                    myMQTTClient.publish('golf/update', json.dumps(get_message_dict(gs, False)), 0)
                    break
            [event_queue.put(e) for e in deferred_events]
            if ui is not None:
                ui.refresh(gs)
        elif event[0] == EventTypes.SWITCH_PLAYER:
            player_switched_to, is_new_player = switch_player(gs, event[1])
            if ui is not None:
                ui.refresh(gs, is_new_player, player_switched_to)
        elif event[0] == EventTypes.RFID_SCAN:
            uid = event[1]
            player = gs.get_player_from_uid(uid)
            if player is None:
                if gs.get_uid_for_player() == '':
                    print('event: setting id {} for current player'.format(uid))
                    gs.set_uid_for_player(uid)
                else:
                    print('event: RFID UID not recognized')
            else:
                print('event: switch to {} from rfid'.format(player))
                event_queue.put((EventTypes.SWITCH_PLAYER, player))

        if event[0] in (EventTypes.SWITCH_PLAYER, EventTypes.PING):
            myMQTTClient.publish('golf/update', json.dumps(get_message_dict(gs)), 0)