IoTHubModuleClient Class

A synchronous module client that connects to an Azure IoT Hub or Azure IoT Edge instance.

Initializer for a IoTHubModuleClient.

This initializer should not be called directly. Instead, use one of the '>>create_from_<<' classmethods to instantiate

Inheritance
azure.iot.device.iothub.sync_clients.GenericIoTHubClient
IoTHubModuleClient
azure.iot.device.iothub.abstract_clients.AbstractIoTHubModuleClient
IoTHubModuleClient

Constructor

IoTHubModuleClient(mqtt_pipeline, http_pipeline)

Parameters

Name Description
mqtt_pipeline
Required
<xref:azure.iot.device.iothub.pipeline.MQTTPipeline>

The pipeline used to connect to the IoTHub endpoint.

http_pipeline
Required
<xref:azure.iot.device.iothub.pipeline.HTTPPipeline>

The pipeline used to connect to the IoTHub endpoint via HTTP.

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.

This is a synchronous call, meaning that this function will not return until the connection to the service has been completely established.

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 function when you are completely done with the your client instance.

This is a synchronous call, meaning that this function will not return until the connection to the service has been completely closed.

get_twin

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

This is a synchronous call, meaning that this function will not return until the twin has been retrieved from the 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.

This is a synchronous call, meaning that this function will not return until the patch has been sent to the service and acknowledged.

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.

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.

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.

This is a synchronous call, which means the following:

  1. If block=True, this function will block until one of the following happens:

    • a desired property patch is received from the Azure IoT Hub or Azure IoT Edge Hub.

    • the timeout period, if provided, elapses. If a timeout happens, this function will raise a InboxEmpty exception

  2. If block=False, this function will return any desired property patches which may have been received by the pipeline, but not yet returned to the application. If no desired property patches have been received by the pipeline, this function will raise an InboxEmpty exception

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.

This is a synchronous event, meaning that this function will not return until the event has been sent to the service and the service has acknowledged receipt of the event.

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

This is a synchronous event, meaning that this function will not return until the event has been sent to the service and the service has acknowledged receipt of the event.

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.

This is a synchronous event, meaning that this function will not return until the event has been sent to the service and the service has acknowledged receipt of the event.

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.

This is a synchronous call, meaning that this function will not return until the connection to the service has been completely established.

connect()

Exceptions

Type Description

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

Name Description
connection_string
Required
str

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

server_verification_cert
Required
str

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
Required

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

cipher
Required
str or list(str)

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
Required
str

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

proxy_options
Required

Options for sending traffic through proxy servers.

sastoken_ttl
Required
int

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

keep_alive
Required
int

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
Required

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

connection_retry
Required

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

connection_retry_interval
Required
int

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

ensure_desired_properties
Required

Ensure the most recent desired properties patch has been received upon re-connections (Default:True)

Returns

Type Description

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

Exceptions

Type Description
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

Name Description
websockets
Required

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

cipher
Required
str or list(str)

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
Required
str

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

proxy_options
Required

Options for sending traffic through proxy servers.

sastoken_ttl
Required
int

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

keep_alive
Required
int

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
Required

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

connection_retry
Required

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

connection_retry_interval
Required
int

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

Returns

Type Description

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

Exceptions

Type Description
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

Name Description
sastoken
Required
str

The SAS Token string

server_verification_cert
Required
str

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
Required
str

Configuration Option. The gateway hostname for the gateway device.

websockets
Required

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

cipher
Required
str or list(str)

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
Required
str

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

proxy_options
Required

Options for sending traffic through proxy servers.

keep_alive
Required
int

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
Required

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

connection_retry
Required

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

connection_retry_interval
Required
int

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

ensure_desired_properties
Required

Ensure the most recent desired properties patch has been received upon re-connections (Default:True)

Exceptions

Type Description
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

Name Description
hostname
Required
str

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

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
Required
str

The ID used to uniquely identify a device in the IoTHub

module_id
Required
str

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

server_verification_cert
Required
str

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
Required
str

Configuration Option. The gateway hostname for the gateway device.

websockets
Required

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

cipher
Required
str or list(str)

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
Required
str

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

proxy_options
Required

Options for sending traffic through proxy servers.

keep_alive
Required
int

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
Required

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

connection_retry
Required

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

connection_retry_interval
Required
int

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

ensure_desired_properties
Required

Ensure the most recent desired properties patch has been received upon re-connections (Default:True)

Returns

Type Description

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

Exceptions

Type Description
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 function when you are completely done with the your client instance.

This is a synchronous call, meaning that this function will not return until the connection to the service has been completely closed.

disconnect()

Exceptions

Type Description

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.

This is a synchronous call, meaning that this function will not return until the twin has been retrieved from the service.

get_twin()

Returns

Type Description

Complete Twin as a JSON dict

Exceptions

Type Description

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.

invoke_method(method_params, device_id, module_id=None)

Parameters

Name Description
method_params
Required

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

device_id
Required
str

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

module_id
str

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

Default value: None

Returns

Type Description

method_result should contain a status, and a payload

Exceptions

Type Description

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.

This is a synchronous call, meaning that this function will not return until the patch has been sent to the service and acknowledged.

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

patch_twin_reported_properties(reported_properties_patch)

Parameters

Name Description
reported_properties_patch
Required

Twin Reported Properties patch as a JSON dict

Exceptions

Type Description

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.

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, block=True, timeout=None)

Parameters

Name Description
input_name
Required
str

The input name to receive a message on.

block
Required

Indicates if the operation should block until a message is received.

timeout
Required
int

Optionally provide a number of seconds until blocking times out.

Returns

Type Description

Message that was sent to the specified input, or None if no method request has been received by the end of the blocking period.

Exceptions

Type Description

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.

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, block=True, timeout=None)

Parameters

Name Description
method_name
str

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 request to receive_method will be received.

Default value: None
block

Indicates if the operation should block until a request is received.

Default value: True
timeout
int

Optionally provide a number of seconds until blocking times out.

Default value: None

Returns

Type Description

MethodRequest object representing the received method request, or None if no method request has been received by the end of the blocking period.

Exceptions

Type Description

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.

This is a synchronous call, which means the following:

  1. If block=True, this function will block until one of the following happens:

    • a desired property patch is received from the Azure IoT Hub or Azure IoT Edge Hub.

    • the timeout period, if provided, elapses. If a timeout happens, this function will raise a InboxEmpty exception

  2. If block=False, this function will return any desired property patches which may have been received by the pipeline, but not yet returned to the application. If no desired property patches have been received by the pipeline, this function will raise an InboxEmpty exception

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(block=True, timeout=None)

Parameters

Name Description
block

Indicates if the operation should block until a request is received.

Default value: True
timeout
int

Optionally provide a number of seconds until blocking times out.

Default value: None

Returns

Type Description
dict,

Twin Desired Properties patch as a JSON dict, or None if no patch has been received by the end of the blocking period

Exceptions

Type Description

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.

This is a synchronous event, meaning that this function will not return until the event has been sent to the service and the service has acknowledged receipt of the event.

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(message)

Parameters

Name Description
message
Required

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

Exceptions

Type Description

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

This is a synchronous event, meaning that this function will not return until the event has been sent to the service and the service has acknowledged receipt of the event.

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(message, output_name)

Parameters

Name Description
message
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
Required
str

Name of the output to send the event to.

Exceptions

Type Description

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.

This is a synchronous event, meaning that this function will not return until the event has been sent to the service and the service has acknowledged receipt of the event.

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(method_response)

Parameters

Name Description
method_response
Required

The MethodResponse to send.

Exceptions

Type Description

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

shutdown()

Exceptions

Type Description

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.

update_sastoken(sastoken)

Parameters

Name Description
sastoken
Required
str

The new SAS Token string for the client to use

Exceptions

Type Description
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)