AWSIoTPythonSDK

SDK for connecting to AWS IoT from a device using Python.

MQTT Modules

class AWSIoTPythonSDK.MQTTLib.AWSIoTMQTTClient(clientID, protocolType=4, useWebsocket=False, cleanSession=True)

Bases: object

The client class that connects to and accesses AWS IoT over MQTT v3.1/3.1.1.

The following connection types are available:

  • TLSv1.2 Mutual Authentication

X.509 certificate-based secured MQTT connection to AWS IoT

  • Websocket SigV4

IAM credential-based secured MQTT connection over Websocket to AWS IoT

It provides basic synchronous MQTT operations in the classic MQTT publish-subscribe model, along with configurations of on-top features:

  • Auto reconnect/resubscribe
  • Progressive reconnect backoff
  • Offline publish requests queueing with draining

Syntax

import AWSIoTPythonSDK.MQTTLib as AWSIoTPyMQTT

# Create an AWS IoT MQTT Client using TLSv1.2 Mutual Authentication
myAWSIoTMQTTClient = AWSIoTPyMQTT.AWSIoTMQTTClient("testIoTPySDK")
# Create an AWS IoT MQTT Client using Websocket SigV4
myAWSIoTMQTTClient = AWSIoTPyMQTT.AWSIoTMQTTClient("testIoTPySDK", useWebsocket=True)

Parameters

clientID - String that denotes the client identifier used to connect to AWS IoT. If empty string were provided, client id for this connection will be randomly generated n server side.

protocolType - MQTT version in use for this connection. Could be AWSIoTPythonSDK.MQTTLib.MQTTv3_1 or AWSIoTPythonSDK.MQTTLib.MQTTv3_1_1

useWebsocket - Boolean that denotes enabling MQTT over Websocket SigV4 or not.

Returns

AWSIoTPythonSDK.MQTTLib.AWSIoTMQTTClient object

configureLastWill(topic, payload, QoS, retain=False)

Description

Used to configure the last will topic, payload and QoS of the client. Should be called before connect.

Syntax

myAWSIoTMQTTClient.configureLastWill("last/Will/Topic", "lastWillPayload", 0)

Parameters

topic - Topic name that last will publishes to.

payload - Payload to publish for last will.

QoS - Quality of Service. Could be 0 or 1.

Returns

None

clearLastWill()

Description

Used to clear the last will configuration that is previously set through configureLastWill.

Syntax

myAWSIoTMQTTClient.clearLastWill()

Parameter

None

Returns

None

configureEndpoint(hostName, portNumber)

Description

Used to configure the host name and port number the client tries to connect to. Should be called before connect.

Syntax

myAWSIoTMQTTClient.configureEndpoint("random.iot.region.amazonaws.com", 8883)

Parameters

hostName - String that denotes the host name of the user-specific AWS IoT endpoint.

portNumber - Integer that denotes the port number to connect to. Could be 8883 for TLSv1.2 Mutual Authentication or 443 for Websocket SigV4 and TLSv1.2 Mutual Authentication with ALPN extension.

Returns

None

configureIAMCredentials(AWSAccessKeyID, AWSSecretAccessKey, AWSSessionToken='')

Description

Used to configure/update the custom IAM credentials for Websocket SigV4 connection to AWS IoT. Should be called before connect.

Syntax

myAWSIoTMQTTClient.configureIAMCredentials(obtainedAccessKeyID, obtainedSecretAccessKey, obtainedSessionToken)

Note

Hard-coding credentials into custom script is NOT recommended. Please use AWS Cognito identity service or other credential provider.

Parameters

AWSAccessKeyID - AWS Access Key Id from user-specific IAM credentials.

AWSSecretAccessKey - AWS Secret Access Key from user-specific IAM credentials.

AWSSessionToken - AWS Session Token for temporary authentication from STS.

Returns

None

configureCredentials(CAFilePath, KeyPath='', CertificatePath='')

Description

Used to configure the rootCA, private key and certificate files. Should be called before connect.

Syntax

myAWSIoTMQTTClient.configureCredentials("PATH/TO/ROOT_CA", "PATH/TO/PRIVATE_KEY", "PATH/TO/CERTIFICATE")

Parameters

CAFilePath - Path to read the root CA file. Required for all connection types.

KeyPath - Path to read the private key. Required for X.509 certificate based connection.

CertificatePath - Path to read the certificate. Required for X.509 certificate based connection.

Returns

None

configureAutoReconnectBackoffTime(baseReconnectQuietTimeSecond, maxReconnectQuietTimeSecond, stableConnectionTimeSecond)

Description

Used to configure the auto-reconnect backoff timing. Should be called before connect.

Syntax

# Configure the auto-reconnect backoff to start with 1 second and use 128 seconds as a maximum back off time.
# Connection over 20 seconds is considered stable and will reset the back off time back to its base.
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 128, 20)

Parameters

baseReconnectQuietTimeSecond - The initial back off time to start with, in seconds. Should be less than the stableConnectionTime.

maxReconnectQuietTimeSecond - The maximum back off time, in seconds.

stableConnectionTimeSecond - The number of seconds for a connection to last to be considered as stable. Back off time will be reset to base once the connection is stable.

Returns

None

configureOfflinePublishQueueing(queueSize, dropBehavior=1)

Description

Used to configure the queue size and drop behavior for the offline requests queueing. Should be called before connect. Queueable offline requests include publish, subscribe and unsubscribe.

Syntax

import AWSIoTPythonSDK.MQTTLib as AWSIoTPyMQTT

# Configure the offline queue for publish requests to be 20 in size and drop the oldest
 request when the queue is full.
myAWSIoTMQTTClient.configureOfflinePublishQueueing(20, AWSIoTPyMQTT.DROP_OLDEST)

Parameters

queueSize - Size of the queue for offline publish requests queueing.
If set to 0, the queue is disabled. If set to -1, the queue size is set to be infinite.
dropBehavior - the type of drop behavior when the queue is full.
Could be AWSIoTPythonSDK.core.util.enums.DropBehaviorTypes.DROP_OLDEST or AWSIoTPythonSDK.core.util.enums.DropBehaviorTypes.DROP_NEWEST.

Returns

None

configureDrainingFrequency(frequencyInHz)

Description

Used to configure the draining speed to clear up the queued requests when the connection is back. Should be called before connect.

Syntax

# Configure the draining speed to be 2 requests/second
myAWSIoTMQTTClient.configureDrainingFrequency(2)

Note

Make sure the draining speed is fast enough and faster than the publish rate. Slow draining could result in inifinite draining process.

Parameters

frequencyInHz - The draining speed to clear the queued requests, in requests/second.

Returns

None

configureConnectDisconnectTimeout(timeoutSecond)

Description

Used to configure the time in seconds to wait for a CONNACK or a disconnect to complete. Should be called before connect.

Syntax

# Configure connect/disconnect timeout to be 10 seconds
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)

Parameters

timeoutSecond - Time in seconds to wait for a CONNACK or a disconnect to complete.

Returns

None

configureMQTTOperationTimeout(timeoutSecond)

Description

Used to configure the timeout in seconds for MQTT QoS 1 publish, subscribe and unsubscribe. Should be called before connect.

Syntax

# Configure MQTT operation timeout to be 5 seconds
myAWSIoTMQTTClient.configureMQTTOperationTimeout(5)

Parameters

timeoutSecond - Time in seconds to wait for a PUBACK/SUBACK/UNSUBACK.

Returns

None

configureUsernamePassword(username, password=None)

Description

Used to configure the username and password used in CONNECT packet.

Syntax

# Configure user name and password
myAWSIoTMQTTClient.configureUsernamePassword("myUsername", "myPassword")

Parameters

username - Username used in the username field of CONNECT packet.

password - Password used in the password field of CONNECT packet.

Returns

None

configureSocketFactory(socket_factory)

Description

Configure a socket factory to custom configure a different socket type for mqtt connection. Creating a custom socket allows for configuration of a proxy

Syntax

# Configure socket factory
custom_args = {"arg1": "val1", "arg2": "val2"}
socket_factory = lambda: custom.create_connection((host, port), **custom_args)
myAWSIoTMQTTClient.configureSocketFactory(socket_factory)

Parameters

socket_factory - Anonymous function which creates a custom socket to spec.

Returns

None

enableMetricsCollection()

Description

Used to enable SDK metrics collection. Username field in CONNECT packet will be used to append the SDK name and SDK version in use and communicate to AWS IoT cloud. This metrics collection is enabled by default.

Syntax

myAWSIoTMQTTClient.enableMetricsCollection()

Parameters

None

Returns

None

disableMetricsCollection()

Description

Used to disable SDK metrics collection.

Syntax

myAWSIoTMQTTClient.disableMetricsCollection()

Parameters

None

Returns

None

connect(keepAliveIntervalSecond=600)

Description

Connect to AWS IoT, with user-specific keepalive interval configuration.

Syntax

# Connect to AWS IoT with default keepalive set to 600 seconds
myAWSIoTMQTTClient.connect()
# Connect to AWS IoT with keepalive interval set to 1200 seconds
myAWSIoTMQTTClient.connect(1200)

Parameters

keepAliveIntervalSecond - Time in seconds for interval of sending MQTT ping request. A shorter keep-alive interval allows the client to detect disconnects more quickly. Default set to 600 seconds.

Returns

True if the connect attempt succeeded. False if failed.

connectAsync(keepAliveIntervalSecond=600, ackCallback=None)

Description

Connect asynchronously to AWS IoT, with user-specific keepalive interval configuration and CONNACK callback.

Syntax

# Connect to AWS IoT with default keepalive set to 600 seconds and a custom CONNACK callback
myAWSIoTMQTTClient.connectAsync(ackCallback=my_connack_callback)
# Connect to AWS IoT with default keepalive set to 1200 seconds and a custom CONNACK callback
myAWSIoTMQTTClient.connectAsync(keepAliveInternvalSecond=1200, ackCallback=myConnackCallback)

Parameters

keepAliveIntervalSecond - Time in seconds for interval of sending MQTT ping request. Default set to 600 seconds.

ackCallback - Callback to be invoked when the client receives a CONNACK. Should be in form customCallback(mid, data), where mid is the packet id for the connect request and data is the connect result code.

Returns

Connect request packet id, for tracking purpose in the corresponding callback.

disconnect()

Description

Disconnect from AWS IoT.

Syntax

myAWSIoTMQTTClient.disconnect()

Parameters

None

Returns

True if the disconnect attempt succeeded. False if failed.

disconnectAsync(ackCallback=None)

Description

Disconnect asynchronously to AWS IoT.

Syntax

myAWSIoTMQTTClient.disconnectAsync(ackCallback=myDisconnectCallback)

Parameters

ackCallback - Callback to be invoked when the client finishes sending disconnect and internal clean-up. Should be in form customCallback(mid, data), where mid is the packet id for the disconnect request and data is the disconnect result code.

Returns

Disconnect request packet id, for tracking purpose in the corresponding callback.

publish(topic, payload, QoS)

Description

Publish a new message to the desired topic with QoS.

Syntax

# Publish a QoS0 message "myPayload" to topic "myTopic"
myAWSIoTMQTTClient.publish("myTopic", "myPayload", 0)
# Publish a QoS1 message "myPayloadWithQos1" to topic "myTopic/sub"
myAWSIoTMQTTClient.publish("myTopic/sub", "myPayloadWithQos1", 1)

Parameters

topic - Topic name to publish to.

payload - Payload to publish.

QoS - Quality of Service. Could be 0 or 1.

Returns

True if the publish request has been sent to paho. False if the request did not reach paho.

publishAsync(topic, payload, QoS, ackCallback=None)

Description

Publish a new message asynchronously to the desired topic with QoS and PUBACK callback. Note that the ack callback configuration for a QoS0 publish request will be ignored as there are no PUBACK reception.

Syntax

# Publish a QoS0 message "myPayload" to topic "myTopic"
myAWSIoTMQTTClient.publishAsync("myTopic", "myPayload", 0)
# Publish a QoS1 message "myPayloadWithQos1" to topic "myTopic/sub", with custom PUBACK callback
myAWSIoTMQTTClient.publishAsync("myTopic/sub", "myPayloadWithQos1", 1, ackCallback=myPubackCallback)

Parameters

topic - Topic name to publish to.

payload - Payload to publish.

QoS - Quality of Service. Could be 0 or 1.

ackCallback - Callback to be invoked when the client receives a PUBACK. Should be in form customCallback(mid), where mid is the packet id for the disconnect request.

Returns

Publish request packet id, for tracking purpose in the corresponding callback.

subscribe(topic, QoS, callback)

Description

Subscribe to the desired topic and register a callback.

Syntax

# Subscribe to "myTopic" with QoS0 and register a callback
myAWSIoTMQTTClient.subscribe("myTopic", 0, customCallback)
# Subscribe to "myTopic/#" with QoS1 and register a callback
myAWSIoTMQTTClient.subscribe("myTopic/#", 1, customCallback)

Parameters

topic - Topic name or filter to subscribe to.

QoS - Quality of Service. Could be 0 or 1.

callback - Function to be called when a new message for the subscribed topic comes in. Should be in form customCallback(client, userdata, message), where message contains topic and payload. Note that client and userdata are here just to be aligned with the underneath Paho callback function signature. These fields are pending to be deprecated and should not be depended on.

Returns

True if the subscribe attempt succeeded. False if failed.

subscribeAsync(topic, QoS, ackCallback=None, messageCallback=None)

Description

Subscribe to the desired topic and register a message callback with SUBACK callback.

Syntax

# Subscribe to "myTopic" with QoS0, custom SUBACK callback and a message callback
myAWSIoTMQTTClient.subscribe("myTopic", 0, ackCallback=mySubackCallback, messageCallback=customMessageCallback)
# Subscribe to "myTopic/#" with QoS1, custom SUBACK callback and a message callback
myAWSIoTMQTTClient.subscribe("myTopic/#", 1, ackCallback=mySubackCallback, messageCallback=customMessageCallback)

Parameters

topic - Topic name or filter to subscribe to.

QoS - Quality of Service. Could be 0 or 1.

ackCallback - Callback to be invoked when the client receives a SUBACK. Should be in form customCallback(mid, data), where mid is the packet id for the disconnect request and data is the granted QoS for this subscription.

messageCallback - Function to be called when a new message for the subscribed topic comes in. Should be in form customCallback(client, userdata, message), where message contains topic and payload. Note that client and userdata are here just to be aligned with the underneath Paho callback function signature. These fields are pending to be deprecated and should not be depended on.

Returns

Subscribe request packet id, for tracking purpose in the corresponding callback.

unsubscribe(topic)

Description

Unsubscribe to the desired topic.

Syntax

myAWSIoTMQTTClient.unsubscribe("myTopic")

Parameters

topic - Topic name or filter to unsubscribe to.

Returns

True if the unsubscribe attempt succeeded. False if failed.

unsubscribeAsync(topic, ackCallback=None)

Description

Unsubscribe to the desired topic with UNSUBACK callback.

Syntax

myAWSIoTMQTTClient.unsubscribe("myTopic", ackCallback=myUnsubackCallback)

Parameters

topic - Topic name or filter to unsubscribe to.

ackCallback - Callback to be invoked when the client receives a UNSUBACK. Should be in form customCallback(mid), where mid is the packet id for the disconnect request.

Returns

Unsubscribe request packet id, for tracking purpose in the corresponding callback.

onOnline()

Description

Callback that gets called when the client is online. The callback registration should happen before calling connect/connectAsync.

Syntax

# Register an onOnline callback
myAWSIoTMQTTClient.onOnline = myOnOnlineCallback

Parameters

None

Returns

None

onOffline()

Description

Callback that gets called when the client is offline. The callback registration should happen before calling connect/connectAsync.

Syntax

# Register an onOffline callback
myAWSIoTMQTTClient.onOffline = myOnOfflineCallback

Parameters

None

Returns

None

onMessage(message)

Description

Callback that gets called when the client receives a new message. The callback registration should happen before calling connect/connectAsync. This callback, if present, will always be triggered regardless of whether there is any message callback registered upon subscribe API call. It is for the purpose to aggregating the processing of received messages in one function.

Syntax

# Register an onMessage callback
myAWSIoTMQTTClient.onMessage = myOnMessageCallback

Parameters

message - Received MQTT message. It contains the source topic as message.topic, and the payload as message.payload.

Returns

None

class AWSIoTPythonSDK.MQTTLib._AWSIoTMQTTDelegatingClient(clientID, protocolType=4, useWebsocket=False, cleanSession=True, awsIoTMQTTClient=None)

Bases: object

This class is used internally by the SDK and should not be instantiated directly.

It delegates to a provided AWS IoT MQTT Client or creates a new one given the configuration parameters and exposes core operations for subclasses provide convenience methods

Syntax

None

Parameters

clientID - String that denotes the client identifier used to connect to AWS IoT. If empty string were provided, client id for this connection will be randomly generated n server side.

protocolType - MQTT version in use for this connection. Could be AWSIoTPythonSDK.MQTTLib.MQTTv3_1 or AWSIoTPythonSDK.MQTTLib.MQTTv3_1_1

useWebsocket - Boolean that denotes enabling MQTT over Websocket SigV4 or not.

Returns

AWSIoTPythonSDK.MQTTLib._AWSIoTMQTTDelegatingClient object

configureLastWill(topic, payload, QoS)

Description

Used to configure the last will topic, payload and QoS of the client. Should be called before connect. This is a public facing API inherited by application level public clients.

Syntax

myShadowClient.configureLastWill("last/Will/Topic", "lastWillPayload", 0)
myJobsClient.configureLastWill("last/Will/Topic", "lastWillPayload", 0)

Parameters

topic - Topic name that last will publishes to.

payload - Payload to publish for last will.

QoS - Quality of Service. Could be 0 or 1.

Returns

None

clearLastWill()

Description

Used to clear the last will configuration that is previously set through configureLastWill. This is a public facing API inherited by application level public clients.

Syntax

myShadowClient.clearLastWill()
myJobsClient.clearLastWill()

Parameter

None

Returns

None

configureEndpoint(hostName, portNumber)

Description

Used to configure the host name and port number the underneath AWS IoT MQTT Client tries to connect to. Should be called before connect. This is a public facing API inherited by application level public clients.

Syntax

myShadowClient.clearLastWill("random.iot.region.amazonaws.com", 8883)
myJobsClient.clearLastWill("random.iot.region.amazonaws.com", 8883)

Parameters

hostName - String that denotes the host name of the user-specific AWS IoT endpoint.

portNumber - Integer that denotes the port number to connect to. Could be 8883 for TLSv1.2 Mutual Authentication or 443 for Websocket SigV4 and TLSv1.2 Mutual Authentication with ALPN extension.

Returns

None

configureIAMCredentials(AWSAccessKeyID, AWSSecretAccessKey, AWSSTSToken='')

Description

Used to configure/update the custom IAM credentials for the underneath AWS IoT MQTT Client for Websocket SigV4 connection to AWS IoT. Should be called before connect. This is a public facing API inherited by application level public clients.

Syntax

myShadowClient.clearLastWill(obtainedAccessKeyID, obtainedSecretAccessKey, obtainedSessionToken)
myJobsClient.clearLastWill(obtainedAccessKeyID, obtainedSecretAccessKey, obtainedSessionToken)

Note

Hard-coding credentials into custom script is NOT recommended. Please use AWS Cognito identity service or other credential provider.

Parameters

AWSAccessKeyID - AWS Access Key Id from user-specific IAM credentials.

AWSSecretAccessKey - AWS Secret Access Key from user-specific IAM credentials.

AWSSessionToken - AWS Session Token for temporary authentication from STS.

Returns

None

configureCredentials(CAFilePath, KeyPath='', CertificatePath='')

Description

Used to configure the rootCA, private key and certificate files. Should be called before connect. This is a public facing API inherited by application level public clients.

Syntax

myShadowClient.clearLastWill("PATH/TO/ROOT_CA", "PATH/TO/PRIVATE_KEY", "PATH/TO/CERTIFICATE")
myJobsClient.clearLastWill("PATH/TO/ROOT_CA", "PATH/TO/PRIVATE_KEY", "PATH/TO/CERTIFICATE")

Parameters

CAFilePath - Path to read the root CA file. Required for all connection types.

KeyPath - Path to read the private key. Required for X.509 certificate based connection.

CertificatePath - Path to read the certificate. Required for X.509 certificate based connection.

Returns

None

configureAutoReconnectBackoffTime(baseReconnectQuietTimeSecond, maxReconnectQuietTimeSecond, stableConnectionTimeSecond)

Description

Used to configure the auto-reconnect backoff timing. Should be called before connect. This is a public facing API inherited by application level public clients.

Syntax

# Configure the auto-reconnect backoff to start with 1 second and use 128 seconds as a maximum back off time.
# Connection over 20 seconds is considered stable and will reset the back off time back to its base.
myShadowClient.clearLastWill(1, 128, 20)
myJobsClient.clearLastWill(1, 128, 20)

Parameters

baseReconnectQuietTimeSecond - The initial back off time to start with, in seconds. Should be less than the stableConnectionTime.

maxReconnectQuietTimeSecond - The maximum back off time, in seconds.

stableConnectionTimeSecond - The number of seconds for a connection to last to be considered as stable. Back off time will be reset to base once the connection is stable.

Returns

None

configureConnectDisconnectTimeout(timeoutSecond)

Description

Used to configure the time in seconds to wait for a CONNACK or a disconnect to complete. Should be called before connect. This is a public facing API inherited by application level public clients.

Syntax

# Configure connect/disconnect timeout to be 10 seconds
myShadowClient.configureConnectDisconnectTimeout(10)
myJobsClient.configureConnectDisconnectTimeout(10)

Parameters

timeoutSecond - Time in seconds to wait for a CONNACK or a disconnect to complete.

Returns

None

configureMQTTOperationTimeout(timeoutSecond)

Description

Used to configure the timeout in seconds for MQTT QoS 1 publish, subscribe and unsubscribe. Should be called before connect. This is a public facing API inherited by application level public clients.

Syntax

# Configure MQTT operation timeout to be 5 seconds
myShadowClient.configureMQTTOperationTimeout(5)
myJobsClient.configureMQTTOperationTimeout(5)

Parameters

timeoutSecond - Time in seconds to wait for a PUBACK/SUBACK/UNSUBACK.

Returns

None

configureUsernamePassword(username, password=None)

Description

Used to configure the username and password used in CONNECT packet. This is a public facing API inherited by application level public clients.

Syntax

# Configure user name and password
myShadowClient.configureUsernamePassword("myUsername", "myPassword")
myJobsClient.configureUsernamePassword("myUsername", "myPassword")

Parameters

username - Username used in the username field of CONNECT packet.

password - Password used in the password field of CONNECT packet.

Returns

None

configureSocketFactory(socket_factory)

Description

Configure a socket factory to custom configure a different socket type for mqtt connection. Creating a custom socket allows for configuration of a proxy

Syntax

# Configure socket factory
custom_args = {"arg1": "val1", "arg2": "val2"}
socket_factory = lambda: custom.create_connection((host, port), **custom_args)
myAWSIoTMQTTClient.configureSocketFactory(socket_factory)

Parameters

socket_factory - Anonymous function which creates a custom socket to spec.

Returns

None

enableMetricsCollection()

Description

Used to enable SDK metrics collection. Username field in CONNECT packet will be used to append the SDK name and SDK version in use and communicate to AWS IoT cloud. This metrics collection is enabled by default. This is a public facing API inherited by application level public clients.

Syntax

myShadowClient.enableMetricsCollection()
myJobsClient.enableMetricsCollection()

Parameters

None

Returns

None

disableMetricsCollection()

Description

Used to disable SDK metrics collection. This is a public facing API inherited by application level public clients.

Syntax

myShadowClient.disableMetricsCollection()
myJobsClient.disableMetricsCollection()

Parameters

None

Returns

None

connect(keepAliveIntervalSecond=600)

Description

Connect to AWS IoT, with user-specific keepalive interval configuration. This is a public facing API inherited by application level public clients.

Syntax

# Connect to AWS IoT with default keepalive set to 600 seconds
myShadowClient.connect()
myJobsClient.connect()
# Connect to AWS IoT with keepalive interval set to 1200 seconds
myShadowClient.connect(1200)
myJobsClient.connect(1200)

Parameters

keepAliveIntervalSecond - Time in seconds for interval of sending MQTT ping request. Default set to 30 seconds.

Returns

True if the connect attempt succeeded. False if failed.

disconnect()

Description

Disconnect from AWS IoT. This is a public facing API inherited by application level public clients.

Syntax

myShadowClient.disconnect()
myJobsClient.disconnect()

Parameters

None

Returns

True if the disconnect attempt succeeded. False if failed.

getMQTTConnection()

Description

Retrieve the AWS IoT MQTT Client used underneath, making it possible to perform plain MQTT operations along with specialized operations using the same single connection. This is a public facing API inherited by application level public clients.

Syntax

# Retrieve the AWS IoT MQTT Client used in the AWS IoT MQTT Delegating Client
thisAWSIoTMQTTClient = myShadowClient.getMQTTConnection()
thisAWSIoTMQTTClient = myJobsClient.getMQTTConnection()
# Perform plain MQTT operations using the same connection
thisAWSIoTMQTTClient.publish("Topic", "Payload", 1)
...

Parameters

None

Returns

AWSIoTPythonSDK.MQTTLib.AWSIoTMQTTClient object

onOnline()

Description

Callback that gets called when the client is online. The callback registration should happen before calling connect. This is a public facing API inherited by application level public clients.

Syntax

# Register an onOnline callback
myShadowClient.onOnline = myOnOnlineCallback
myJobsClient.onOnline = myOnOnlineCallback

Parameters

None

Returns

None

onOffline()

Description

Callback that gets called when the client is offline. The callback registration should happen before calling connect. This is a public facing API inherited by application level public clients.

Syntax

# Register an onOffline callback
myShadowClient.onOffline = myOnOfflineCallback
myJobsClient.onOffline = myOnOfflineCallback

Parameters

None

Returns

None

class AWSIoTPythonSDK.MQTTLib.AWSIoTMQTTShadowClient(clientID, protocolType=4, useWebsocket=False, cleanSession=True, awsIoTMQTTClient=None)

Bases: AWSIoTPythonSDK.MQTTLib._AWSIoTMQTTDelegatingClient

The client class that manages device shadow and accesses its functionality in AWS IoT over MQTT v3.1/3.1.1.

It delegates to the AWS IoT MQTT Client and exposes devive shadow related operations. It shares the same connection types, synchronous MQTT operations and partial on-top features with the AWS IoT MQTT Client:

  • Auto reconnect/resubscribe

Same as AWS IoT MQTT Client.

  • Progressive reconnect backoff

Same as AWS IoT MQTT Client.

  • Offline publish requests queueing with draining

Disabled by default. Queueing is not allowed for time-sensitive shadow requests/messages.

Syntax

import AWSIoTPythonSDK.MQTTLib as AWSIoTPyMQTT

# Create an AWS IoT MQTT Shadow Client using TLSv1.2 Mutual Authentication
myAWSIoTMQTTShadowClient = AWSIoTPyMQTT.AWSIoTMQTTShadowClient("testIoTPySDK")
# Create an AWS IoT MQTT Shadow Client using Websocket SigV4
myAWSIoTMQTTShadowClient = AWSIoTPyMQTT.AWSIoTMQTTShadowClient("testIoTPySDK",  useWebsocket=True)

Parameters

clientID - String that denotes the client identifier used to connect to AWS IoT. If empty string were provided, client id for this connection will be randomly generated n server side.

protocolType - MQTT version in use for this connection. Could be AWSIoTPythonSDK.MQTTLib.MQTTv3_1 or AWSIoTPythonSDK.MQTTLib.MQTTv3_1_1

useWebsocket - Boolean that denotes enabling MQTT over Websocket SigV4 or not.

Returns

AWSIoTPythonSDK.MQTTLib.AWSIoTMQTTShadowClient object

createShadowHandlerWithName(shadowName, isPersistentSubscribe)

Description

Create a device shadow handler using the specified shadow name and isPersistentSubscribe.

Syntax

# Create a device shadow handler for shadow named "Bot1", using persistent subscription
Bot1Shadow = myAWSIoTMQTTShadowClient.createShadowHandlerWithName("Bot1", True)
# Create a device shadow handler for shadow named "Bot2", using non-persistent subscription
Bot2Shadow = myAWSIoTMQTTShadowClient.createShadowHandlerWithName("Bot2", False)

Parameters

shadowName - Name of the device shadow.

isPersistentSubscribe - Whether to unsubscribe from shadow response (accepted/rejected) topics when there is a response. Will subscribe at the first time the shadow request is made and will not unsubscribe if isPersistentSubscribe is set.

Returns

AWSIoTPythonSDK.core.shadow.deviceShadow.deviceShadow object, which exposes the device shadow interface.

class AWSIoTPythonSDK.MQTTLib.AWSIoTMQTTThingJobsClient(clientID, thingName, QoS=0, protocolType=4, useWebsocket=False, cleanSession=True, awsIoTMQTTClient=None)

Bases: AWSIoTPythonSDK.MQTTLib._AWSIoTMQTTDelegatingClient

The client class that specializes in handling jobs messages and accesses its functionality in AWS IoT over MQTT v3.1/3.1.1.

It delegates to the AWS IoT MQTT Client and exposes jobs related operations. It shares the same connection types, synchronous MQTT operations and partial on-top features with the AWS IoT MQTT Client:

  • Auto reconnect/resubscribe

Same as AWS IoT MQTT Client.

  • Progressive reconnect backoff

Same as AWS IoT MQTT Client.

  • Offline publish requests queueing with draining

Same as AWS IoT MQTT Client

Syntax

import AWSIoTPythonSDK.MQTTLib as AWSIoTPyMQTT

# Create an AWS IoT MQTT Jobs Client using TLSv1.2 Mutual Authentication
myAWSIoTMQTTJobsClient = AWSIoTPyMQTT.AWSIoTMQTTThingJobsClient("testIoTPySDK")
# Create an AWS IoT MQTT Jobs Client using Websocket SigV4
myAWSIoTMQTTJobsClient = AWSIoTPyMQTT.AWSIoTMQTTThingJobsClient("testIoTPySDK",  useWebsocket=True)

Parameters

clientID - String that denotes the client identifier and client token for jobs requests If empty string is provided, client id for this connection will be randomly generated on server side. If an awsIotMQTTClient is specified, this will not override the client ID for the existing MQTT connection and only impact the client token for jobs request payloads

thingName - String that represents the thingName used to send requests to proper topics and subscribe to proper topics.

QoS - QoS used for all requests sent through this client

awsIoTMQTTClient - An instance of AWSIoTMQTTClient to use if not None. If not None, clientID, protocolType, useWebSocket, and cleanSession parameters are not used. Caller is expected to invoke connect() prior to calling the pub/sub methods on this client.

protocolType - MQTT version in use for this connection. Could be AWSIoTPythonSDK.MQTTLib.MQTTv3_1 or AWSIoTPythonSDK.MQTTLib.MQTTv3_1_1

useWebsocket - Boolean that denotes enabling MQTT over Websocket SigV4 or not.

Returns

AWSIoTPythonSDK.MQTTLib.AWSIoTMQTTJobsClient object

createJobSubscription(callback, jobExecutionType=(7, False, '+'), jobReplyType=(1, ''), jobId=None)

Description

Synchronously creates an MQTT subscription to a jobs related topic based on the provided arguments

Syntax

#Subscribe to notify-next topic to monitor change in job referred to by $next
myAWSIoTMQTTJobsClient.createJobSubscription(callback, jobExecutionTopicType.JOB_NOTIFY_NEXT_TOPIC)
#Subscribe to notify topic to monitor changes to jobs in pending list
myAWSIoTMQTTJobsClient.createJobSubscription(callback, jobExecutionTopicType.JOB_NOTIFY_TOPIC)
#Subscribe to receive messages for job execution updates
myAWSIoTMQTTJobsClient.createJobSubscription(callback, jobExecutionTopicType.JOB_UPDATE_TOPIC, jobExecutionTopicReplyType.JOB_ACCEPTED_REPLY_TYPE)
#Subscribe to receive messages for describing a job execution
myAWSIoTMQTTJobsClient.createJobSubscription(callback, jobExecutionTopicType.JOB_DESCRIBE_TOPIC, jobExecutionTopicReplyType.JOB_ACCEPTED_REPLY_TYPE, jobId)

Parameters

callback - Function to be called when a new message for the subscribed job topic comes in. Should be in form customCallback(client, userdata, message), where message contains topic and payload. Note that client and userdata are here just to be aligned with the underneath Paho callback function signature. These fields are pending to be deprecated and should not be depended on.

jobExecutionType - Member of the jobExecutionTopicType class specifying the jobs topic to subscribe to Defaults to jobExecutionTopicType.JOB_WILDCARD_TOPIC

jobReplyType - Member of the jobExecutionTopicReplyType class specifying the (optional) reply sub-topic to subscribe to Defaults to jobExecutionTopicReplyType.JOB_REQUEST_TYPE which indicates the subscription isn’t intended for a jobs reply topic

jobId - JobId string if the topic type requires one. Defaults to None

Returns

True if the subscribe attempt succeeded. False if failed.

createJobSubscriptionAsync(ackCallback, callback, jobExecutionType=(7, False, '+'), jobReplyType=(1, ''), jobId=None)

Description

Asynchronously creates an MQTT subscription to a jobs related topic based on the provided arguments

Syntax

#Subscribe to notify-next topic to monitor change in job referred to by $next
myAWSIoTMQTTJobsClient.createJobSubscriptionAsync(callback, jobExecutionTopicType.JOB_NOTIFY_NEXT_TOPIC)
#Subscribe to notify topic to monitor changes to jobs in pending list
myAWSIoTMQTTJobsClient.createJobSubscriptionAsync(callback, jobExecutionTopicType.JOB_NOTIFY_TOPIC)
#Subscribe to receive messages for job execution updates
myAWSIoTMQTTJobsClient.createJobSubscriptionAsync(callback, jobExecutionTopicType.JOB_UPDATE_TOPIC, jobExecutionTopicReplyType.JOB_ACCEPTED_REPLY_TYPE)
#Subscribe to receive messages for describing a job execution
myAWSIoTMQTTJobsClient.createJobSubscriptionAsync(callback, jobExecutionTopicType.JOB_DESCRIBE_TOPIC, jobExecutionTopicReplyType.JOB_ACCEPTED_REPLY_TYPE, jobId)

Parameters

ackCallback - Callback to be invoked when the client receives a SUBACK. Should be in form customCallback(mid, data), where mid is the packet id for the disconnect request and data is the granted QoS for this subscription.

callback - Function to be called when a new message for the subscribed job topic comes in. Should be in form customCallback(client, userdata, message), where message contains topic and payload. Note that client and userdata are here just to be aligned with the underneath Paho callback function signature. These fields are pending to be deprecated and should not be depended on.

jobExecutionType - Member of the jobExecutionTopicType class specifying the jobs topic to subscribe to Defaults to jobExecutionTopicType.JOB_WILDCARD_TOPIC

jobReplyType - Member of the jobExecutionTopicReplyType class specifying the (optional) reply sub-topic to subscribe to Defaults to jobExecutionTopicReplyType.JOB_REQUEST_TYPE which indicates the subscription isn’t intended for a jobs reply topic

jobId - JobId of the topic if the topic type requires one. Defaults to None

Returns

Subscribe request packet id, for tracking purpose in the corresponding callback.

sendJobsQuery(jobExecTopicType, jobId=None)

Description

Publishes an MQTT jobs related request for a potentially specific jobId (or wildcard)

Syntax

#send a request to describe the next job
myAWSIoTMQTTJobsClient.sendJobsQuery(jobExecutionTopicType.JOB_DESCRIBE_TOPIC, '$next')
#send a request to get list of pending jobs
myAWSIoTMQTTJobsClient.sendJobsQuery(jobExecutionTopicType.JOB_GET_PENDING_TOPIC)

Parameters

jobExecutionType - Member of the jobExecutionTopicType class that correlates the jobs topic to publish to

jobId - JobId string if the topic type requires one. Defaults to None

Returns

True if the publish request has been sent to paho. False if the request did not reach paho.

sendJobsStartNext(statusDetails=None, stepTimeoutInMinutes=None)

Description

Publishes an MQTT message to the StartNextJobExecution topic. This will attempt to get the next pending job execution and change its status to IN_PROGRESS.

Syntax

#Start next job (set status to IN_PROGRESS) and update with optional statusDetails
myAWSIoTMQTTJobsClient.sendJobsStartNext({'StartedBy': 'myClientId'})

Parameters

statusDetails - Dictionary containing the key value pairs to use for the status details of the job execution

*stepTimeoutInMinutes - Specifies the amount of time this device has to finish execution of this job.

Returns

True if the publish request has been sent to paho. False if the request did not reach paho.

sendJobsUpdate(jobId, status, statusDetails=None, expectedVersion=0, executionNumber=0, includeJobExecutionState=False, includeJobDocument=False, stepTimeoutInMinutes=None)

Description

Publishes an MQTT message to a corresponding job execution specific topic to update its status according to the parameters. Can be used to change a job from QUEUED to IN_PROGRESS to SUCEEDED or FAILED.

Syntax

#Update job with id 'jobId123' to succeeded state, specifying new status details, with expectedVersion=1, executionNumber=2.
#For the response, include job execution state and not the job document
myAWSIoTMQTTJobsClient.sendJobsUpdate('jobId123', jobExecutionStatus.JOB_EXECUTION_SUCCEEDED, statusDetailsMap, 1, 2, True, False)


#Update job with id 'jobId456' to failed state
myAWSIoTMQTTJobsClient.sendJobsUpdate('jobId456', jobExecutionStatus.JOB_EXECUTION_FAILED)

Parameters

jobId - JobID String of the execution to update the status of

status - job execution status to change the job execution to. Member of jobExecutionStatus

statusDetails - new status details to set on the job execution

expectedVersion - The expected current version of the job execution. IoT jobs increments expectedVersion each time you update the job execution. If the version of the job execution stored in Jobs does not match, the update is rejected with a VersionMismatch error, and an ErrorResponse that contains the current job execution status data is returned. (This makes it unnecessary to perform a separate DescribeJobExecution request n order to obtain the job execution status data.)

executionNumber - A number that identifies a particular job execution on a particular device. If not specified, the latest job execution is used.

includeJobExecutionState - When included and set to True, the response contains the JobExecutionState field. The default is False.

includeJobDocument - When included and set to True, the response contains the JobDocument. The default is False.

*stepTimeoutInMinutes - Specifies the amount of time this device has to finish execution of this job.

Returns

True if the publish request has been sent to paho. False if the request did not reach paho.

sendJobsDescribe(jobId, executionNumber=0, includeJobDocument=True)

Description

Publishes a method to the describe topic for a particular job.

Syntax

#Describe job with id 'jobId1' of any executionNumber, job document will be included in response
myAWSIoTMQTTJobsClient.sendJobsDescribe('jobId1')

#Describe job with id 'jobId2', with execution number of 2, and includeJobDocument in the response
myAWSIoTMQTTJobsClient.sendJobsDescribe('jobId2', 2, True)

Parameters

jobId - jobID to describe. This is allowed to be a wildcard such as ‘$next’

executionNumber - A number that identifies a particular job execution on a particular device. If not specified, the latest job execution is used.

includeJobDocument - When included and set to True, the response contains the JobDocument.

Returns

True if the publish request has been sent to paho. False if the request did not reach paho.

Device Shadow Modules

class AWSIoTPythonSDK.core.shadow.deviceShadow.deviceShadow(srcShadowName, srcIsPersistentSubscribe, srcShadowManager)

Bases: object

The class that denotes a local/client-side device shadow instance.

Users can perform shadow operations on this instance to retrieve and modify the corresponding shadow JSON document in AWS IoT Cloud. The following shadow operations are available:

  • Get
  • Update
  • Delete
  • Listen on delta
  • Cancel listening on delta

This is returned from AWSIoTPythonSDK.MQTTLib.AWSIoTMQTTShadowClient.createShadowWithName function call. No need to call directly from user scripts.

shadowGet(srcCallback, srcTimeout)

Description

Retrieve the device shadow JSON document from AWS IoT by publishing an empty JSON document to the corresponding shadow topics. Shadow response topics will be subscribed to receive responses from AWS IoT regarding the result of the get operation. Retrieved shadow JSON document will be available in the registered callback. If no response is received within the provided timeout, a timeout notification will be passed into the registered callback.

Syntax

# Retrieve the shadow JSON document from AWS IoT, with a timeout set to 5 seconds
BotShadow.shadowGet(customCallback, 5)

Parameters

srcCallback - Function to be called when the response for this shadow request comes back. Should be in form customCallback(payload, responseStatus, token), where payload is the JSON document returned, responseStatus indicates whether the request has been accepted, rejected or is a delta message, token is the token used for tracing in this request.

srcTimeout - Timeout to determine whether the request is invalid. When a request gets timeout, a timeout notification will be generated and put into the registered callback to notify users.

Returns

The token used for tracing in this shadow request.

shadowDelete(srcCallback, srcTimeout)

Description

Delete the device shadow from AWS IoT by publishing an empty JSON document to the corresponding shadow topics. Shadow response topics will be subscribed to receive responses from AWS IoT regarding the result of the get operation. Responses will be available in the registered callback. If no response is received within the provided timeout, a timeout notification will be passed into the registered callback.

Syntax

# Delete the device shadow from AWS IoT, with a timeout set to 5 seconds
BotShadow.shadowDelete(customCallback, 5)

Parameters

srcCallback - Function to be called when the response for this shadow request comes back. Should be in form customCallback(payload, responseStatus, token), where payload is the JSON document returned, responseStatus indicates whether the request has been accepted, rejected or is a delta message, token is the token used for tracing in this request.

srcTimeout - Timeout to determine whether the request is invalid. When a request gets timeout, a timeout notification will be generated and put into the registered callback to notify users.

Returns

The token used for tracing in this shadow request.

shadowUpdate(srcJSONPayload, srcCallback, srcTimeout)

Description

Update the device shadow JSON document string from AWS IoT by publishing the provided JSON document to the corresponding shadow topics. Shadow response topics will be subscribed to receive responses from AWS IoT regarding the result of the get operation. Response will be available in the registered callback. If no response is received within the provided timeout, a timeout notification will be passed into the registered callback.

Syntax

# Update the shadow JSON document from AWS IoT, with a timeout set to 5 seconds
BotShadow.shadowUpdate(newShadowJSONDocumentString, customCallback, 5)

Parameters

srcJSONPayload - JSON document string used to update shadow JSON document in AWS IoT.

srcCallback - Function to be called when the response for this shadow request comes back. Should be in form customCallback(payload, responseStatus, token), where payload is the JSON document returned, responseStatus indicates whether the request has been accepted, rejected or is a delta message, token is the token used for tracing in this request.

srcTimeout - Timeout to determine whether the request is invalid. When a request gets timeout, a timeout notification will be generated and put into the registered callback to notify users.

Returns

The token used for tracing in this shadow request.

shadowRegisterDeltaCallback(srcCallback)

Description

Listen on delta topics for this device shadow by subscribing to delta topics. Whenever there is a difference between the desired and reported state, the registered callback will be called and the delta payload will be available in the callback.

Syntax

# Listen on delta topics for BotShadow
BotShadow.shadowRegisterDeltaCallback(customCallback)

Parameters

srcCallback - Function to be called when the response for this shadow request comes back. Should be in form customCallback(payload, responseStatus, token), where payload is the JSON document returned, responseStatus indicates whether the request has been accepted, rejected or is a delta message, token is the token used for tracing in this request.

Returns

None

shadowUnregisterDeltaCallback()

Description

Cancel listening on delta topics for this device shadow by unsubscribing to delta topics. There will be no delta messages received after this API call even though there is a difference between the desired and reported state.

Syntax

# Cancel listening on delta topics for BotShadow
BotShadow.shadowUnregisterDeltaCallback()

Parameters

None

Returns

None

Greengrass Modules

class AWSIoTPythonSDK.core.greengrass.discovery.providers.DiscoveryInfoProvider(caPath='', certPath='', keyPath='', host='', port=8443, timeoutSec=120)

Bases: object

The class that provides functionality to perform a Greengrass discovery process to the cloud.

Users can perform Greengrass discovery process for a specific Greengrass aware device to retrieve connectivity/identity information of Greengrass cores within the same group.

Syntax

from AWSIoTPythonSDK.core.greengrass.discovery.providers import DiscoveryInfoProvider

# Create a discovery information provider
myDiscoveryInfoProvider = DiscoveryInfoProvider()
# Create a discovery information provider with custom configuration
myDiscoveryInfoProvider = DiscoveryInfoProvider(caPath=myCAPath, certPath=myCertPath, keyPath=myKeyPath, host=myHost, timeoutSec=myTimeoutSec)

Parameters

caPath - Path to read the root CA file.

certPath - Path to read the certificate file.

keyPath - Path to read the private key file.

host - String that denotes the host name of the user-specific AWS IoT endpoint.

port - Integer that denotes the port number to connect to. For discovery purpose, it is 8443 by default.

timeoutSec - Time out configuration in seconds to consider a discovery request sending/response waiting has been timed out.

Returns

AWSIoTPythonSDK.core.greengrass.discovery.providers.DiscoveryInfoProvider object

HOST_PREFIX = 'Host: '
HOST_SUFFIX = '\r\n\r\n'
configureEndpoint(host, port=8443)

Description

Used to configure the host address and port number for the discovery request to hit. Should be called before the discovery request happens.

Syntax

# Using default port configuration, 8443
myDiscoveryInfoProvider.configureEndpoint(host="prefix.iot.us-east-1.amazonaws.com")
# Customize port configuration
myDiscoveryInfoProvider.configureEndpoint(host="prefix.iot.us-east-1.amazonaws.com", port=8888)

Parameters

host - String that denotes the host name of the user-specific AWS IoT endpoint.

port - Integer that denotes the port number to connect to. For discovery purpose, it is 8443 by default.

Returns

None

configureCredentials(caPath, certPath, keyPath)

Description

Used to configure the credentials for discovery request. Should be called before the discovery request happens.

Syntax

myDiscoveryInfoProvider.configureCredentials("my/ca/path", "my/cert/path", "my/key/path")

Parameters

caPath - Path to read the root CA file.

certPath - Path to read the certificate file.

keyPath - Path to read the private key file.

Returns

None

configureTimeout(timeoutSec)

Description

Used to configure the time out in seconds for discovery request sending/response waiting. Should be called before the discovery request happens.

Syntax

# Configure the time out for discovery to be 10 seconds
myDiscoveryInfoProvider.configureTimeout(10)

Parameters

timeoutSec - Time out configuration in seconds to consider a discovery request sending/response waiting has been timed out.

Returns

None

discover(thingName)

Description

Perform the discovery request for the given Greengrass aware device thing name.

Syntax

myDiscoveryInfoProvider.discover(thingName="myGGAD")

Parameters

thingName - Greengrass aware device thing name.

Returns

AWSIoTPythonSDK.core.greengrass.discovery.models.DiscoveryInfo object.

class AWSIoTPythonSDK.core.greengrass.discovery.models.ConnectivityInfo(id, host, port, metadata)

Bases: object

Class the stores one set of the connectivity information. This is the data model for easy access to the discovery information from the discovery request function call. No need to call directly from user scripts.

id

Connectivity Information Id.

host

Host address.

port

Port number.

metadata

Metadata string.

class AWSIoTPythonSDK.core.greengrass.discovery.models.CoreConnectivityInfo(coreThingArn, groupId)

Bases: object

Class that stores the connectivity information for a Greengrass core. This is the data model for easy access to the discovery information from the discovery request function call. No need to call directly from user scripts.

coreThingArn

Thing arn for this Greengrass core.

groupId

Greengrass group id that this Greengrass core belongs to.

connectivityInfoList

The list of connectivity information that this Greengrass core has.

getConnectivityInfo(id)

Description

Used for quickly accessing a certain set of connectivity information by id.

Syntax

myCoreConnectivityInfo.getConnectivityInfo("CoolId")

Parameters

id - The id for the desired connectivity information.

Return

AWSIoTPythonSDK.core.greengrass.discovery.models.ConnectivityInfo object.

appendConnectivityInfo(connectivityInfo)

Description

Used for adding a new set of connectivity information to the list for this Greengrass core. This is used by the SDK internally. No need to call directly from user scripts.

Syntax

myCoreConnectivityInfo.appendConnectivityInfo(newInfo)

Parameters

connectivityInfo - AWSIoTPythonSDK.core.greengrass.discovery.models.ConnectivityInfo object.

Returns

None

class AWSIoTPythonSDK.core.greengrass.discovery.models.GroupConnectivityInfo(groupId)

Bases: object

Class that stores the connectivity information for a specific Greengrass group. This is the data model for easy access to the discovery information from the discovery request function call. No need to call directly from user scripts.

groupId

Id for this Greengrass group.

coreConnectivityInfoList

A list of Greengrass cores (AWSIoTPythonSDK.core.greengrass.discovery.models.CoreConnectivityInfo object) that belong to this Greengrass group.

caList

A list of CA content strings for this Greengrass group.

getCoreConnectivityInfo(coreThingArn)

Description

Used to retrieve the corresponding AWSIoTPythonSDK.core.greengrass.discovery.models.CoreConnectivityInfo object by core thing arn.

Syntax

myGroupConnectivityInfo.getCoreConnectivityInfo("YourOwnArnString")

Parameters

coreThingArn - Thing arn for the desired Greengrass core.

Returns

AWSIoTPythonSDK.core.greengrass.discovery.CoreConnectivityInfo object.

appendCoreConnectivityInfo(coreConnectivityInfo)

Description

Used to append new core connectivity information to this group connectivity information. This is used by the SDK internally. No need to call directly from user scripts.

Syntax

myGroupConnectivityInfo.appendCoreConnectivityInfo(newCoreConnectivityInfo)

Parameters

coreConnectivityInfo - AWSIoTPythonSDK.core.greengrass.discovery.models.CoreConnectivityInfo object.

Returns

None

appendCa(ca)

Description

Used to append new CA content string to this group connectivity information. This is used by the SDK internally. No need to call directly from user scripts.

Syntax

myGroupConnectivityInfo.appendCa("CaContentString")

Parameters

ca - Group CA content string.

Returns

None

class AWSIoTPythonSDK.core.greengrass.discovery.models.DiscoveryInfo(rawJson)

Bases: object

Class that stores the discovery information coming back from the discovery request. This is the data model for easy access to the discovery information from the discovery request function call. No need to call directly from user scripts.

rawJson

JSON response string that contains the discovery information. This is reserved in case users want to do some process by themselves.

getAllCores()

Description

Used to retrieve the list of AWSIoTPythonSDK.core.greengrass.discovery.models.CoreConnectivityInfo object for this discovery information. The retrieved cores could be from different Greengrass groups. This is designed for uses who want to iterate through all available cores at the same time, regardless of which group those cores are in.

Syntax

myDiscoveryInfo.getAllCores()

Parameters

None

Returns

List of AWSIoTPythonSDK.core.greengrass.discovery.models.CoreConnectivtyInfo object.

getAllCas()

Description

Used to retrieve the list of (groupId, caContent) pair for this discovery information. The retrieved pairs could be from different Greengrass groups. This is designed for users who want to iterate through all available cores/groups/CAs at the same time, regardless of which group those CAs belong to.

Syntax

myDiscoveryInfo.getAllCas()

Parameters

None

Returns

List of (groupId, caContent) string pair, where caContent is the CA content string and groupId is the group id that this CA belongs to.

getAllGroups()

Description

Used to retrieve the list of AWSIoTPythonSDK.core.greengrass.discovery.models.GroupConnectivityInfo object for this discovery information. This is designed for users who want to iterate through all available groups that this Greengrass aware device (GGAD) belongs to.

Syntax

myDiscoveryInfo.getAllGroups()

Parameters

None

Returns

List of AWSIoTPythonSDK.core.greengrass.discovery.models.GroupConnectivityInfo object.

toObjectAtGroupLevel()

Description

Used to get a dictionary of Greengrass group discovery information, with group id string as key and the corresponding AWSIoTPythonSDK.core.greengrass.discovery.models.GroupConnectivityInfo object as the value. This is designed for users who know exactly which group, which core and which set of connectivity info they want to use for the Greengrass aware device to connect.

Syntax

# Get to the targeted connectivity information for a specific core in a specific group
groupLevelDiscoveryInfoObj = myDiscoveryInfo.toObjectAtGroupLevel()
groupConnectivityInfoObj = groupLevelDiscoveryInfoObj.toObjectAtGroupLevel("IKnowMyGroupId")
coreConnectivityInfoObj = groupConnectivityInfoObj.getCoreConnectivityInfo("IKnowMyCoreThingArn")
connectivityInfo = coreConnectivityInfoObj.getConnectivityInfo("IKnowMyConnectivityInfoSetId")
# Now retrieve the detailed information
caList = groupConnectivityInfoObj.caList
host = connectivityInfo.host
port = connectivityInfo.port
metadata = connectivityInfo.metadata
# Actual connecting logic follows...

Indices and tables