IoTHubModuleClient Class

An asynchronous module client that connects to an Azure IoT Hub or Azure IoT Edge instance.

Inheritance
azure.iot.device.iothub.aio.async_clients.GenericIoTHubClient
IoTHubModuleClient
azure.iot.device.iothub.abstract_clients.AbstractIoTHubModuleClient
IoTHubModuleClient

Constructor

IoTHubModuleClient(mqtt_pipeline, http_pipeline)

Parameters

mqtt_pipeline
http_pipeline

Methods

connect

Connects the client to an Azure IoT Hub or Azure IoT Edge Hub instance.

The destination is chosen based on the credentials passed via the auth_provider parameter that was provided when this object was initialized.

create_from_connection_string

Instantiate the client from a IoTHub device or module connection string.

create_from_edge_environment

Instantiate the client from the IoT Edge environment.

This method can only be run from inside an IoT Edge container, or in a debugging environment configured for Edge development (e.g. Visual Studio, Visual Studio Code)

create_from_sastoken

Instantiate the client from a pre-created SAS Token string

create_from_x509_certificate

Instantiate a client using X509 certificate authentication.

disconnect

Disconnect the client from the Azure IoT Hub or Azure IoT Edge Hub instance.

It is recommended that you make sure to call this coroutine when you are completely done with the your client instance.

get_twin

Gets the device or module twin from the Azure IoT Hub or Azure IoT Edge Hub service.

invoke_method

Invoke a method from your client onto a device or module client, and receive the response to the method call.

patch_twin_reported_properties

Update reported properties with the Azure IoT Hub or Azure IoT Edge Hub service.

If the service returns an error on the patch operation, this function will raise the appropriate error.

receive_message_on_input

Receive an input message that has been sent from another Module to a specific input.

If no message is yet available, will wait until an item is available.

Deprecated since version 2.3.0: We recommend that you use the .on_message_received property to set a handler instead

receive_method_request

Receive a method request via the Azure IoT Hub or Azure IoT Edge Hub.

If no method request is yet available, will wait until it is available.

Deprecated since version 2.3.0: We recommend that you use the .on_method_request_received property to set a handler instead

receive_twin_desired_properties_patch

Receive a desired property patch via the Azure IoT Hub or Azure IoT Edge Hub.

If no method request is yet available, will wait until it is available.

Deprecated since version 2.3.0: We recommend that you use the .on_twin_desired_properties_patch_received property to set a handler instead

send_message

Sends a message to the default events endpoint on the Azure IoT Hub or Azure IoT Edge Hub instance.

If the connection to the service has not previously been opened by a call to connect, this function will open the connection before sending the event.

send_message_to_output

Sends an event/message to the given module output.

These are outgoing events and are meant to be "output events"

If the connection to the service has not previously been opened by a call to connect, this function will open the connection before sending the event.

send_method_response

Send a response to a method request via the Azure IoT Hub or Azure IoT Edge Hub.

If the connection to the service has not previously been opened by a call to connect, this function will open the connection before sending the event.

shutdown

Shut down the client for graceful exit.

Once this method is called, any attempts at further client calls will result in a ClientError being raised

update_sastoken

Update the client's SAS Token used for authentication, then reauthorizes the connection.

This API can only be used if the client was initially created with a SAS Token.

connect

Connects the client to an Azure IoT Hub or Azure IoT Edge Hub instance.

The destination is chosen based on the credentials passed via the auth_provider parameter that was provided when this object was initialized.

async connect()

Exceptions

if credentials are invalid and a connection cannot be established.

if a establishing a connection results in failure.

if connection is lost during execution.

if the connection times out.

if there is an unexpected failure during execution.

create_from_connection_string

Instantiate the client from a IoTHub device or module connection string.

create_from_connection_string(connection_string, **kwargs)

Parameters

connection_string
str
Required

The connection string for the IoTHub you wish to connect to.

server_verification_cert
str
Required

Configuration Option. The trusted certificate chain. Necessary when using connecting to an endpoint which has a non-standard root of trust, such as a protocol gateway.

websockets
bool
Required

Configuration Option. Default is False. Set to true if using MQTT over websockets.

cipher
str or list(str)
Required

Configuration Option. Cipher suite(s) for TLS/SSL, as a string in "OpenSSL cipher list format" or as a list of cipher suite strings.

product_info
str
Required

Configuration Option. Default is empty string. The string contains arbitrary product info which is appended to the user agent string.

proxy_options
ProxyOptions
Required

Options for sending traffic through proxy servers.

sastoken_ttl
int
Required

The time to live (in seconds) for the created SasToken used for authentication. Default is 3600 seconds (1 hour).

keep_alive
int
Required

Maximum period in seconds between communications with the broker. If no other messages are being exchanged, this controls the rate at which the client will send ping messages to the broker. If not provided default value of 60 secs will be used.

auto_connect
bool
Required

Automatically connect the client to IoTHub when a method is invoked which requires a connection to be established. (Default: True)

connection_retry
bool
Required

Attempt to re-establish a dropped connection (Default: True)

connection_retry_interval
int
Required

Interval, in seconds, between attempts to re-establish a dropped connection (Default: 10)

Returns

An instance of an IoTHub client that uses a connection string for authentication.

Exceptions

ValueError if given an invalid connection_string.
TypeError if given an unsupported parameter.

create_from_edge_environment

Instantiate the client from the IoT Edge environment.

This method can only be run from inside an IoT Edge container, or in a debugging environment configured for Edge development (e.g. Visual Studio, Visual Studio Code)

create_from_edge_environment(**kwargs)

Parameters

websockets
bool
Required

Configuration Option. Default is False. Set to true if using MQTT over websockets.

cipher
str or list(str)
Required

Configuration Option. Cipher suite(s) for TLS/SSL, as a string in "OpenSSL cipher list format" or as a list of cipher suite strings.

product_info
str
Required

Configuration Option. Default is empty string. The string contains arbitrary product info which is appended to the user agent string.

proxy_options
ProxyOptions
Required

Options for sending traffic through proxy servers.

sastoken_ttl
int
Required

The time to live (in seconds) for the created SasToken used for authentication. Default is 3600 seconds (1 hour)

keep_alive
int
Required

Maximum period in seconds between communications with the broker. If no other messages are being exchanged, this controls the rate at which the client will send ping messages to the broker. If not provided default value of 60 secs will be used.

auto_connect
bool
Required

Automatically connect the client to IoTHub when a method is invoked which requires a connection to be established. (Default: True)

connection_retry
bool
Required

Attempt to re-establish a dropped connection (Default: True)

connection_retry_interval
int
Required

Interval, in seconds, between attempts to re-establish a dropped connection (Default: 10)

Returns

An instance of an IoTHub client that uses the IoT Edge environment for authentication.

Exceptions

OSError if the IoT Edge container is not configured correctly.
ValueError if debug variables are invalid.
TypeError if given an unsupported parameter.

create_from_sastoken

Instantiate the client from a pre-created SAS Token string

create_from_sastoken(sastoken, **kwargs)

Parameters

sastoken
str
Required

The SAS Token string

server_verification_cert
str
Required

Configuration Option. The trusted certificate chain. Necessary when using connecting to an endpoint which has a non-standard root of trust, such as a protocol gateway.

gateway_hostname
str
Required

Configuration Option. The gateway hostname for the gateway device.

websockets
bool
Required

Configuration Option. Default is False. Set to true if using MQTT over websockets.

cipher
str or list(str)
Required

Configuration Option. Cipher suite(s) for TLS/SSL, as a string in "OpenSSL cipher list format" or as a list of cipher suite strings.

product_info
str
Required

Configuration Option. Default is empty string. The string contains arbitrary product info which is appended to the user agent string.

proxy_options
ProxyOptions
Required

Options for sending traffic through proxy servers.

keep_alive
int
Required

Maximum period in seconds between communications with the broker. If no other messages are being exchanged, this controls the rate at which the client will send ping messages to the broker. If not provided default value of 60 secs will be used.

auto_connect
bool
Required

Automatically connect the client to IoTHub when a method is invoked which requires a connection to be established. (Default: True)

connection_retry
bool
Required

Attempt to re-establish a dropped connection (Default: True)

connection_retry_interval
int
Required

Interval, in seconds, between attempts to re-establish a dropped connection (Default: 10)

Exceptions

TypeError if given an unsupported parameter.
ValueError if the sastoken parameter is invalid.

create_from_x509_certificate

Instantiate a client using X509 certificate authentication.

create_from_x509_certificate(x509, hostname, device_id, module_id, **kwargs)

Parameters

hostname
str
Required

Host running the IotHub. Can be found in the Azure portal in the Overview tab as the string hostname.

x509
X509
Required

The complete x509 certificate object. To use the certificate the enrollment object needs to contain cert (either the root certificate or one of the intermediate CA certificates). If the cert comes from a CER file, it needs to be base64 encoded.

device_id
str
Required

The ID used to uniquely identify a device in the IoTHub

module_id
str
Required

The ID used to uniquely identify a module on a device on the IoTHub.

server_verification_cert
str
Required

Configuration Option. The trusted certificate chain. Necessary when using connecting to an endpoint which has a non-standard root of trust, such as a protocol gateway.

gateway_hostname
str
Required

Configuration Option. The gateway hostname for the gateway device.

websockets
bool
Required

Configuration Option. Default is False. Set to true if using MQTT over websockets.

cipher
str or list(str)
Required

Configuration Option. Cipher suite(s) for TLS/SSL, as a string in "OpenSSL cipher list format" or as a list of cipher suite strings.

product_info
str
Required

Configuration Option. Default is empty string. The string contains arbitrary product info which is appended to the user agent string.

proxy_options
ProxyOptions
Required

Options for sending traffic through proxy servers.

keep_alive
int
Required

Maximum period in seconds between communications with the broker. If no other messages are being exchanged, this controls the rate at which the client will send ping messages to the broker. If not provided default value of 60 secs will be used.

auto_connect
bool
Required

Automatically connect the client to IoTHub when a method is invoked which requires a connection to be established. (Default: True)

connection_retry
bool
Required

Attempt to re-establish a dropped connection (Default: True)

connection_retry_interval
int
Required

Interval, in seconds, between attempts to re-establish a dropped connection (Default: 10)

Returns

An instance of an IoTHub client that uses an X509 certificate for authentication.

Exceptions

TypeError if given an unsupported parameter.

disconnect

Disconnect the client from the Azure IoT Hub or Azure IoT Edge Hub instance.

It is recommended that you make sure to call this coroutine when you are completely done with the your client instance.

async disconnect()

Exceptions

if there is an unexpected failure during execution.

get_twin

Gets the device or module twin from the Azure IoT Hub or Azure IoT Edge Hub service.

async get_twin()

Returns

Complete Twin as a JSON dict

Return type

Exceptions

if credentials are invalid and a connection cannot be established.

if a establishing a connection results in failure.

if connection is lost during execution.

if connection attempt times out

if the client is not connected (and there is no auto-connect enabled)

if there is an unexpected failure during execution.

invoke_method

Invoke a method from your client onto a device or module client, and receive the response to the method call.

async invoke_method(method_params, device_id, module_id=None)

Parameters

method_params
dict
Required

Should contain a methodName (str), payload (str), connectTimeoutInSeconds (int), responseTimeoutInSeconds (int).

device_id
str
Required

Device ID of the target device where the method will be invoked.

module_id
str
default value: None

Module ID of the target module where the method will be invoked. (Optional)

Returns

method_result should contain a status, and a payload

Return type

Exceptions

if credentials are invalid and a connection cannot be established.

if a establishing a connection results in failure.

if connection is lost during execution.

if the connection times out.

if there is an unexpected failure during execution.

patch_twin_reported_properties

Update reported properties with the Azure IoT Hub or Azure IoT Edge Hub service.

If the service returns an error on the patch operation, this function will raise the appropriate error.

async patch_twin_reported_properties(reported_properties_patch)

Parameters

reported_properties_patch
dict
Required

Twin Reported Properties patch as a JSON dict

Exceptions

if credentials are invalid and a connection cannot be established.

if a establishing a connection results in failure.

if connection is lost during execution.

if connection attempt times out

if the client is not connected (and there is no auto-connect enabled)

if there is an unexpected failure during execution.

receive_message_on_input

Receive an input message that has been sent from another Module to a specific input.

If no message is yet available, will wait until an item is available.

Deprecated since version 2.3.0: We recommend that you use the .on_message_received property to set a handler instead

receive_message_on_input(input_name)

Parameters

input_name
str
Required

The input name to receive a message on.

Returns

Message that was sent to the specified input.

Return type

Exceptions

if credentials are invalid and a connection cannot be established.

if a establishing a connection results in failure.

if connection is lost during execution.

if the connection times out.

if there is an unexpected failure during execution.

receive_method_request

Receive a method request via the Azure IoT Hub or Azure IoT Edge Hub.

If no method request is yet available, will wait until it is available.

Deprecated since version 2.3.0: We recommend that you use the .on_method_request_received property to set a handler instead

receive_method_request(method_name=None)

Parameters

method_name
str
default value: None

Optionally provide the name of the method to receive requests for. If this parameter is not given, all methods not already being specifically targeted by a different call to receive_method will be received.

Returns

MethodRequest object representing the received method request.

Return type

Exceptions

if credentials are invalid and a connection cannot be established.

if a establishing a connection results in failure.

if connection is lost during execution.

if the connection times out.

if there is an unexpected failure during execution.

receive_twin_desired_properties_patch

Receive a desired property patch via the Azure IoT Hub or Azure IoT Edge Hub.

If no method request is yet available, will wait until it is available.

Deprecated since version 2.3.0: We recommend that you use the .on_twin_desired_properties_patch_received property to set a handler instead

receive_twin_desired_properties_patch()

Returns

Twin Desired Properties patch as a JSON dict

Return type

Exceptions

if credentials are invalid and a connection cannot be established.

if a establishing a connection results in failure.

if connection is lost during execution.

if the connection times out.

if there is an unexpected failure during execution.

send_message

Sends a message to the default events endpoint on the Azure IoT Hub or Azure IoT Edge Hub instance.

If the connection to the service has not previously been opened by a call to connect, this function will open the connection before sending the event.

async send_message(message)

Parameters

message
Message or str
Required

The actual message to send. Anything passed that is not an instance of the Message class will be converted to Message object.

Exceptions

if credentials are invalid and a connection cannot be established.

if a establishing a connection results in failure.

if connection is lost during execution.

if connection attempt times out

if the client is not connected (and there is no auto-connect enabled)

if there is an unexpected failure during execution.

ValueError if the message fails size validation.

send_message_to_output

Sends an event/message to the given module output.

These are outgoing events and are meant to be "output events"

If the connection to the service has not previously been opened by a call to connect, this function will open the connection before sending the event.

async send_message_to_output(message, output_name)

Parameters

message
Message or str
Required

Message to send to the given output. Anything passed that is not an instance of the Message class will be converted to Message object.

output_name
str
Required

Name of the output to send the event to.

Exceptions

if credentials are invalid and a connection cannot be established.

if a establishing a connection results in failure.

if connection is lost during execution.

if connection attempt times out

if the client is not connected (and there is no auto-connect enabled)

if there is an unexpected failure during execution.

ValueError if the message fails size validation.

send_method_response

Send a response to a method request via the Azure IoT Hub or Azure IoT Edge Hub.

If the connection to the service has not previously been opened by a call to connect, this function will open the connection before sending the event.

async send_method_response(method_response)

Parameters

method_response
MethodResponse
Required

The MethodResponse to send

Exceptions

if credentials are invalid and a connection cannot be established.

if a establishing a connection results in failure.

if connection is lost during execution.

if connection attempt times out

if the client is not connected (and there is no auto-connect enabled)

if there is an unexpected failure during execution.

shutdown

Shut down the client for graceful exit.

Once this method is called, any attempts at further client calls will result in a ClientError being raised

async shutdown()

Exceptions

if there is an unexpected failure during execution.

update_sastoken

Update the client's SAS Token used for authentication, then reauthorizes the connection.

This API can only be used if the client was initially created with a SAS Token.

async update_sastoken(sastoken)

Parameters

sastoken
str
Required

The new SAS Token string for the client to use

Exceptions

ValueError if the sastoken parameter is invalid

if credentials are invalid and a connection cannot be re-established.

if a re-establishing the connection results in failure.

if connection is lost during execution.

if the reauthorization attempt times out.

if the client was not initially created with a SAS token.

if there is an unexpected failure during execution.

Attributes

connected

Read-only property to indicate if the transport is connected or not.

on_background_exception

The handler function or coroutine will be called when a background exception occurs.

The function or coroutine definition should take one positional argument (the exception object)

on_connection_state_change

The handler function or coroutine that will be called when the connection state changes.

The function or coroutine definition should take no positional arguments.

on_message_received

The handler function or coroutine that will be called when an input message is received.

The function definition or coroutine should take one positional argument (the Message object)

on_method_request_received

The handler function or coroutine that will be called when a method request is received.

Remember to acknowledge the method request in your function or coroutine via use of the client's .send_method_response() method.

The function or coroutine definition should take one positional argument (the MethodRequest object)

on_new_sastoken_required

The handler function or coroutine that will be called when the client requires a new SAS token. This will happen approximately 2 minutes before the SAS Token expires. On Windows platforms, if the lifespan exceeds approximately 49 days, a new token will be required after those 49 days regardless of how long the SAS lifespan is.

Note that this handler is ONLY necessary when using a client created via the .create_from_sastoken() method.

The new token can be provided in your function or coroutine via use of the client's .update_sastoken() method.

The function or coroutine definition should take no positional arguments.

on_twin_desired_properties_patch_received

The handler function or coroutine that will be called when a twin desired properties patch is received.

The function or coroutine definition should take one positional argument (the twin patch in the form of a JSON dictionary object)