IoTHubDeviceClient Class

A synchronous device client that connects to an Azure IoT Hub instance.

Initializer for a IoTHubDeviceClient.

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
IoTHubDeviceClient
azure.iot.device.iothub.abstract_clients.AbstractIoTHubDeviceClient
IoTHubDeviceClient

Constructor

IoTHubDeviceClient(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

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_sastoken

Instantiate the client from a pre-created SAS Token string

create_from_symmetric_key

Instantiate a client using symmetric key authentication.

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_storage_info_for_blob

Sends a POST request over HTTP to an IoTHub endpoint that will return information for uploading via the Azure Storage Account linked to the IoTHub your device is connected to.

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.

notify_blob_upload_status

When the upload is complete, the device sends a POST request to the IoT Hub endpoint with information on the status of an upload to blob attempt. This is used by IoT Hub to notify listening clients.

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

Receive a message that has been sent from the Azure IoT Hub.

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_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_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_symmetric_key

Instantiate a client using symmetric key authentication.

create_from_symmetric_key(symmetric_key, hostname, device_id, **kwargs)

Parameters

Name Description
symmetric_key
Required

The symmetric key.

hostname
Required
str

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

device_id
Required

The device ID

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.

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 symmetric key for authentication.

Exceptions

Type Description
TypeError if given an unsupported parameter.
ValueError if the provided parameters are invalid.

create_from_x509_certificate

Instantiate a client using X509 certificate authentication.

create_from_x509_certificate(x509, hostname, device_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

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_storage_info_for_blob

Sends a POST request over HTTP to an IoTHub endpoint that will return information for uploading via the Azure Storage Account linked to the IoTHub your device is connected to.

get_storage_info_for_blob(blob_name)

Parameters

Name Description
blob_name
Required
str

The name in string format of the blob that will be uploaded using the storage API. This name will be used to generate the proper credentials for Storage, and needs to match what will be used with the Azure Storage SDK to perform the blob upload.

Returns

Type Description

A JSON-like (dictionary) object from IoT Hub that will contain relevant information including: correlationId, hostName, containerName, blobName, sasToken.

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.

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.

notify_blob_upload_status

When the upload is complete, the device sends a POST request to the IoT Hub endpoint with information on the status of an upload to blob attempt. This is used by IoT Hub to notify listening clients.

notify_blob_upload_status(correlation_id, is_success, status_code, status_description)

Parameters

Name Description
correlation_id
Required
str

Provided by IoT Hub on get_storage_info_for_blob request.

is_success
Required

A boolean that indicates whether the file was uploaded successfully.

status_code
Required
int

A numeric status code that is the status for the upload of the file to storage.

status_description
Required
str

A description that corresponds to the status_code.

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

Receive a message that has been sent from the Azure IoT Hub.

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

receive_message(block=True, timeout=None)

Parameters

Name Description
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 from the Azure IoT Hub, 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_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 a message is received.

The function or coroutine definition 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)