Azure IoT Hub

The Azure IoT Hub library provides an API to connect to an Azure IoT Hub instance and interact with it. It connects to Azure IoT Hub using MQTT over TLS.

Optionally, the library supports Azure IoT Hub Device Provisioning Service (DPS). DPS can be enabled at compile time to make use of the device provisioning services for onboarding of devices to Azure IoT Hub. When the device provisioning is complete, the library automatically connects to the assigned Azure IoT Hub.

The library also has integrated support for a proprietary FOTA solution. For more information on Azure FOTA, see the documentation on Azure FOTA library and nRF9160: Azure FOTA sample.

The library uses Azure SDK for Embedded C for message processing and other operations. For more information on how Azure SDK for Embedded C is integrated in this library, see Azure SDK for Embedded C IoT client libraries.

Important

If the server sends a device-bound message when the device is unavailable for a period of time, for instance while in LTE Power Saving Mode, the server will most likely terminate the TCP connection. This will result in additional data traffic as the device has to reconnect to the server, which in turn requires a new TLS handshake and MQTT connection establishment.

Prerequisites for connecting to Azure IoT Hub

In order to connect to Azure IoT Hub, an Azure account and an Azure IoT Hub instance must first be created and configured. See Creating an Azure IoT Hub instance using the Azure portal for more information.

Note

If you do not use DPS to provision devices to your IoT Hub, make sure that you select X.509 CA Signed as the Authentication type while Registering the device with Azure IoT Hub.

The connection to Azure IoT Hub with MQTT is secured using TLS. For testing purposes, see Creating Azure IoT Hub certificates for the steps to create certificates and a private key for the leaf device, and to register the generated test root certificate to be used with an IoT hub.

The Azure IoT Hub library requires provisioning of the following certificates and a private key for a successful TLS connection:

  1. Baltimore CyberTrust Root Certificate - Server certificate, used to verify the server’s certificate while connecting.

  2. Public device certificate - generated by the procedures described in Creating Azure IoT Hub certificates , used by Azure IoT Hub to authenticate the device.

  3. Private key of the device.

Important

Azure has started the process of migrating their IoT Hub and DPS server certificates from Baltimore CyberTrust Root Certificate to DigiCert Global Root G2. Azure advises to have both Baltimore CyberTrust Root and DigiCert Global Root G2 certificates for all devices to avoid disruption of service during the transition. Refer to Azure IoT TLS: Critical changes for updated information and timeline. Due to this, it is recommended to provision the DigiCert Root G2 certificate to a secondary security tag set by the CONFIG_AZURE_IOT_HUB_SEC_TAG option. This ensures that the device can connect after the transition.

Note

The location and name of the generated public device certificate and private key files vary depending on the method you use for the credential generation. For PowerShell scripts, the device certificate is called mydevice-public.pem and the private key is mydevice-private.pem. These files are located in the working directory with the other generated files.

For bash scripts, the public device certificate is called new-device.cert.pem and is located in a directory called certs within the script directory. The private key is called new-device.key.pem and located in a directory called private within the script directory.

The file and directory names may change if Azure changes their scripts.

Provisioning of the certificates

To provision the certificates and the private key to the nRF9160 modem, complete the following steps:

  1. Download nRF Connect for Desktop.

  2. Update the modem firmware on the onboard modem of the nRF9160-based device to the latest version by following the steps in Updating the modem firmware.

  3. Build and program the nRF9160: AT Client sample to the nRF9160-based device as explained in Building and programming an application.

  4. Launch the LTE Link Monitor application, which is part of nRF Connect for Desktop.

  5. Click CERTIFICATE MANAGER located at the upper right corner.

  6. Copy the server root certificate into the CA certificate entry.

  7. Copy and paste the device certificate and the private key into the respective entries (Client certificate, Private key).

  8. Select a desired security tag (any positive integer in the range of 0 to 2147483647) and click Update certificates.

Important

The default security tag set by the CERTIFICATE MANAGER 16842753 is reserved for communications with nRF Cloud. Overwriting this security tag entry will require you to flash new certificates if you want to establish a connection to the nRF Cloud.

Note

The chosen security tag while provisioning the certificates must be same as the security tag configured by the CONFIG_AZURE_IOT_HUB_SEC_TAG option.

Note

If more than one root server certificate is used, the second one can be provisioned to a different security tag and configured in the application using the CONFIG_AZURE_IOT_HUB_SECONDARY_SEC_TAG Kconfig option. The modem will check both security tags if necessary when verifying the server’s certificate.

Configuring the library

You can configure the library to connect to Azure IoT Hub with or without using DPS.

Configuration without using DPS

To connect to Azure IoT Hub without using DPS, complete the following minimum required configuration:

  1. In the Azure Portal, navigate to IoT Hub and select the desired IoT hub.

  2. In the overview page, locate and copy the Hostname and configure CONFIG_AZURE_IOT_HUB_HOSTNAME to this address.

    The hostname can also be set at run time.

  3. Set the option CONFIG_AZURE_IOT_HUB_DEVICE_ID to the device ID.

    The device ID must match with the one used while creating the certificates. You can also set the device ID at run time by populating the device_id member of the azure_iot_hub_config structure passed to the azure_iot_hub_connect() function when connecting. If the device_id.size buffer size is zero, the compile-time option CONFIG_AZURE_IOT_HUB_DEVICE_ID` is used.

  4. Make sure that the device is already registered with your Azure IoT Hub, or follow the instructions in Registering the device with Azure IoT Hub.

  5. Set the CONFIG_AZURE_IOT_HUB_SEC_TAG option to the security tag used in Provisioning of the certificates.

    Optionally, set the CONFIG_AZURE_IOT_HUB_SEC_TAG option if multiple server certificates are provisioned.

Configuration using DPS

To connect to Azure IoT Hub using DPS, complete the following steps:

  1. Set up an Azure IoT Hub Device Provisioning Service (DPS) instance and obtain the ID scope.

  2. Add certificates to the DPS instance.

  3. Create an enrollment group as described in Device enrollments with Azure Portal and link it to your IoT hub. Select the certificate added in the previous step as the Primary certificate​​​​​​​.

  4. Enable CONFIG_AZURE_IOT_HUB_DPS.

  5. In the Azure Portal, click Device Provisioning Services and select the DPS instance to use.

  6. In the overview page, locate and copy the ID Scope and set the CONFIG_AZURE_IOT_HUB_DPS_ID_SCOPE option to this string.

    Alternatively, you can set the registration ID at run time.

  7. Set the CONFIG_AZURE_IOT_HUB_DPS_REG_ID option to the registration ID.

    You can also set the registration ID at run time.

  8. Set CONFIG_AZURE_IOT_HUB_SEC_TAG to the security tag used while Provisioning of the certificates. Optionally, set the CONFIG_AZURE_IOT_HUB_SEC_TAG option if multiple server certificates are provisioned.

Application integration

Initializing the library

The library is initialized by calling the azure_iot_hub_init() function. The initialization must be successful to make the other APIs in the library available for the application. An event handler is passed as the only argument to the azure_iot_hub_init() function. The library calls this function with data associated to the application, such as incoming data and other events. For an exhaustive list of event types and associated data, see azure_iot_hub_evt_type.

Using the Device Provisioning Service

You can use the Azure IoT Hub Device Provisioning Service to provision the device to an IoT Hub. When the registration process has completed successfully, the device receives its assigned hostname and device ID to use when connecting to Azure IoT Hub. The assigned hostname and device ID are stored to the non-volatile memory on the device and are available also after a reset and power outage.

This code example shows how to configure and use DPS:

static void dps_handler(enum azure_iot_hub_dps_reg_status state)
{
   switch (state) {
   case AZURE_IOT_HUB_DPS_REG_STATUS_NOT_STARTED:
      LOG_INF("AZURE_IOT_HUB_DPS_REG_STATUS_NOT_STARTED");
      break;
   case AZURE_IOT_HUB_DPS_REG_STATUS_ASSIGNING:
      LOG_INF("AZURE_IOT_HUB_DPS_REG_STATUS_ASSIGNING");
      break;
   case AZURE_IOT_HUB_DPS_REG_STATUS_ASSIGNED:
      LOG_INF("AZURE_IOT_HUB_DPS_REG_STATUS_ASSIGNED");

      /* Act on assignment */
      k_sem_give(&dps_assigned_sem);
      break;
   case AZURE_IOT_HUB_DPS_REG_STATUS_FAILED:
      LOG_INF("ZURE_IOT_HUB_DPS_REG_STATUS_FAILED");

      /* Act on registration failure */
      k_sem_give(&dps_registration_failed_sem);
      break;
   default:
      LOG_WRN("Unhandled DPS registration status: %d", state);
      break;
   }
}

...

int err;
struct azure_iot_hub_buf assigned_hostname;
struct azure_iot_hub_buf assigned_device_id;
     struct azure_iot_hub_dps_config dps_cfg = {
             .handler = dps_handler,

   /* Can be left out to use CONFIG_AZURE_IOT_HUB_DPS_REG_ID instead. */
             .reg_id = {
                     .ptr = device_id_buf,
                     .size = device_id_len,
             },

   /* Can be left out to use CONFIG_AZURE_IOT_HUB_DPS_ID_SCOPE instead. */
   .id_scope = {
                     .ptr = id_scope_buf,
                     .size = id_scope_len,
             },
     };

     err = azure_iot_hub_dps_init(&dps_cfg);
/* Error handling */

err = azure_iot_hub_dps_start();
     if (err == 0) {
             LOG_INF("The DPS process has started");

   /* Wait for the registration process to complete. */
   err = k_sem_take(&dps_done_sem, K_SECONDS(SOME_TIMEOUT));
   /* Error handling */
     } else if (err == -EALREADY) {
             LOG_INF("Already assigned to an IoT hub, skipping DPS");
     } else {
   /* Error handling */
     }
     err = azure_iot_hub_dps_hostname_get(assigned_hostname);
/* Error handling */

     err = azure_iot_hub_dps_device_id_get(assigned_device_id);
/* Error handling */

/* Use the hostname and device ID to connect to IoT Hub. */

After successfully registering the device, the application can proceed to connect to the assigned IoT Hub using the obtained device ID.

When a device has been assigned to an IoT Hub and the information is stored to the non-volatile memory, the DPS APIs always return the stored information and do not trigger a new registration. To delete the stored assignment information, call the azure_iot_hub_dps_reset() function. Alternatively, you can call the functions azure_iot_hub_dps_hostname_delete() or azure_iot_hub_dps_device_id_delete() to delete specific information. After calling the azure_iot_hub_dps_reset() function, the library must be initialized again. After the initialization, a new registration with the DPS can be started by calling the azure_iot_hub_dps_start() function.

The DPS APIs are documented in the Azure IoT Hub DPS API section.

Connecting to Azure IoT Hub

After the initialization, calling the azure_iot_hub_connect() function connects the device to the configured IoT hub or DPS instance, depending on the configuration. The initial TLS handshake takes a few seconds to complete, depending on the network conditions and the TLS cipher suite used. During the TLS handshake, the azure_iot_hub_connect() function blocks. Consider this when deciding the context from which the API is called. Optionally, DPS registration can be run automatically as part of the call to the azure_iot_hub_connect() function. Note that the azure_iot_hub_connect() function blocks when DPS registration is pending. Running DPS as part of the azure_iot_hub_connect() function also limits the DPS configuration options as follows:

Use the DPS APIs directly if you need more control over the DPS registration process.

When using the azure_iot_hub_connect() function, you can choose to provide the hostname to the IoT Hub and device ID at run time, or let the library use Kconfig options.

Here is an example for setting the hostname and device ID at run time:

struct azure_iot_hub_config cfg = {
   .hostname = {
      .ptr = hostname_buffer,
      .size = hostname_length,
   },
   .device_id = {
      .ptr = device_id_buffer,
      .size = device_id_length,
   },
   .use_dps = false,
};

err = azure_iot_hub_connect(&cfg);
/* Error handling */

You can pass NULL or a zeroed out configuration to the azure_iot_hub_connect() function. The library uses the values for hostname and device ID from the Kconfig options CONFIG_AZURE_IOT_HUB_HOSTNAME and CONFIG_AZURE_IOT_HUB_DEVICE_ID, respectively.

This code example uses a Kconfig value for the device ID (and by extension DPS registration ID) and runs DPS to acquire the assigned IoT Hub hostname and assigned device ID.

struct azure_iot_hub_config cfg = {
   .use_dps = true,
};

err = azure_iot_hub_connect(&cfg);
/* Error handling */

After a successful connection, the library automatically subscribes to the following standard Azure IoT Hub MQTT topics (See Azure IoT Hub MQTT protocol support for details):

  • devices/<device ID>/messages/devicebound/# (cloud-to-device messages)

  • $iothub/twin/PATCH/properties/desired/# (desired properties update notifications)

  • $iothub/twin/res/# (operation responses)

  • $iothub/methods/POST/# (direct method requests)

Currently, the library does not support persistent MQTT sessions. Hence subscriptions are requested for each connection to the IoT hub.

For more information about the available APIs, see the Azure IoT Hub API section.

Configuration

To use the Azure IoT Hub library, you must enable the CONFIG_AZURE_IOT_HUB Kconfig option.

You can configure the following options when using this library:

DPS-specific configuration:

API documentation

Azure IoT Hub API

Header file: include/net/azure_iot_hub.h
Source files: subsys/net/lib/azure_iot_hub/src/azure_iot_hub.c

Azure IoT Hub DPS API

Header file: include/net/azure_iot_hub_dps.h
Source files: subsys/net/lib/azure_iot_hub/src/azure_iot_hub_dps.c
group azure_iot_hub

Library to connect a device to Azure IoT Hub.

Typedefs

typedef void (*azure_iot_hub_evt_handler_t)(struct azure_iot_hub_evt *evt)

Azure IoT Hub library event handler.

Param evt

Pointer to event structure.

Enums

enum azure_iot_hub_evt_type

Azure IoT Hub notification events used to notify the user.

Values:

enumerator AZURE_IOT_HUB_EVT_CONNECTING

Connecting to Azure IoT Hub. The event has no associated data.

enumerator AZURE_IOT_HUB_EVT_CONNECTED

Connected to Azure IoT Hub. The event has no associated data.

enumerator AZURE_IOT_HUB_EVT_CONNECTION_FAILED

Connection attempt failed. The reported error code from the IoT Hub is available in the data.err member in the event structure. The error codes correspond to return codes in MQTT CONNACK messages.

enumerator AZURE_IOT_HUB_EVT_READY

Azure IoT Hub connection established and ready to receive data. The event has no associated data.

enumerator AZURE_IOT_HUB_EVT_DISCONNECTED

Disconnected from Azure IoT Hub. The event has no associated data.

enumerator AZURE_IOT_HUB_EVT_DATA_RECEIVED

Device-bound data received from Azure IoT Hub. The event contains the received data in the data.msg member, and the topic it was received on in the topic member, including message properties in topic.properties.

enumerator AZURE_IOT_HUB_EVT_PUBACK

Acknowledgment for data sent to Azure IoT Hub. The acknowledged message ID is in data.message_id.

enumerator AZURE_IOT_HUB_EVT_PINGRESP

Acknowledgment for ping request message sent to Azure IoT Hub. The event has no associated data.

enumerator AZURE_IOT_HUB_EVT_TWIN_RECEIVED

Device twin has been received. The event contains the received data in the data.msg member, and the topic it was received on in the topic member, including message properties in topic.properties.

enumerator AZURE_IOT_HUB_EVT_TWIN_DESIRED_RECEIVED

Device twin has received a desired property update. The event contains the received data in the data.msg member, and the topic it was received on in the topic member, including message properties in topic.properties.

enumerator AZURE_IOT_HUB_EVT_TWIN_RESULT_SUCCESS

Device twin update successful. The request ID and status are contained in the data.result member of the event structure. The received payload is in the data.msg member, and the topic it was received on is in the topic member.

enumerator AZURE_IOT_HUB_EVT_TWIN_RESULT_FAIL

Device twin update failed. The request ID and status are contained in the data.result member of the event structure.

enumerator AZURE_IOT_HUB_EVT_DIRECT_METHOD

Direct method invoked from the cloud side.

    The event contains the method data in the ``data.method`` member, and the topic it was
    received on in the ``topic`` member.

    @note After a direct method has been executed, @a azure_iot_hub_method_respond must be
      called to report back the result of the method invocation.

enumerator AZURE_IOT_HUB_EVT_FOTA_START

FOTA download starting. The event has no associated data.

enumerator AZURE_IOT_HUB_EVT_FOTA_DONE

FOTA update done, reboot required to apply update. The event has no associated data.

enumerator AZURE_IOT_HUB_EVT_FOTA_ERASE_PENDING

FOTA erase pending. On nRF9160-based devices this is typically caused by an active LTE connection preventing erase operation. The event has no associated data.

enumerator AZURE_IOT_HUB_EVT_FOTA_ERASE_DONE

FOTA erase done. The event has no associated data.

enumerator AZURE_IOT_HUB_EVT_FOTA_ERROR

FOTA failed. The event has no associated data.

enumerator AZURE_IOT_HUB_EVT_ERROR_MSG_SIZE

A received message is too large for the payload buffer and can not be processed. The event has no associated data.

enumerator AZURE_IOT_HUB_EVT_ERROR

Internal library error. The event has no associated data.

enum azure_iot_hub_topic_type

Azure IoT Hub topic type, used to route messages to the correct destination.

Values:

enumerator AZURE_IOT_HUB_TOPIC_DEVICEBOUND

Data received on the devicebound topic.

enumerator AZURE_IOT_HUB_TOPIC_DIRECT_METHOD

Data received on the direct method topic.

enumerator AZURE_IOT_HUB_TOPIC_TWIN_DESIRED

Received “desired” properties from the device twin.

enumerator AZURE_IOT_HUB_TOPIC_TWIN_REQUEST_RESULT

Topic to receive twin request result messages. Both success and error messages are received on the same topic.

enumerator AZURE_IOT_HUB_TOPIC_DPS

Topic to receive Device Provisioning Service (DPS) messages.

enumerator AZURE_IOT_HUB_TOPIC_EVENT

Event topic used to send event data to Azure IoT Hub.

enumerator AZURE_IOT_HUB_TOPIC_TWIN_REPORTED

Send updates to the “reported” properties in the device twin.

enumerator AZURE_IOT_HUB_TOPIC_TWIN_REQUEST

Topic to request to receive the device twin.

enumerator AZURE_IOT_HUB_TOPIC_UNKNOWN

Indicates that the message was received on an unknown topic.

Functions

int azure_iot_hub_init(azure_iot_hub_evt_handler_t event_handler)

Initialize the module.

Note

This API must be called exactly once, and it must return successfully for subsequent calls to this library to succeed.

Parameters
  • event_handler[in] Pointer to event handler function.

Return values
  • 0 – If successful.

  • -EALREADY – if the library has already been initialized and is in a state where it can not be re-initialized.

  • -EINVAL – in invalid argument was provided.

int azure_iot_hub_connect(const struct azure_iot_hub_config *config)

Establish connection to Azure IoT Hub. The function blocks until a connection to the hub is established on the transport level. Subsequent calls to other library function should await AZURE_IOT_HUB_EVT_CONNECTED and AZURE_IOT_HUB_EVT_READY events.

Parameters
  • config[in] Pointer to struct containing connection parameters. If NULL, values from Kconfig will be used instead.

Return values
  • 0 – If successful.

  • -EALREADY – if the device is already connected to an IoT Hub.

  • -EINPROGRESS – if an connection attempt is already in progress.

  • -ENOENT – if the library is not in disconnected state.

  • -EINVAL – if the provided configuration is invalid.

  • -EMSGSIZE – if the provided device ID is larger than the internal buffer size.

  • -EFAULT – if there was an internal error in the library.

int azure_iot_hub_disconnect(void)

Disconnect from Azure IoT Hub. Calling this function initiates the disconnection procedure, and the event AZURE_IOT_HUB_EVT_DISCONNECTED is received when it is completed.

Return values
  • 0 – If successful.

  • -ENOTCONN – if the device is not connected to an IoT Hub.

  • -ENXIO – if the MQTT library reported an error.

int azure_iot_hub_send(const struct azure_iot_hub_msg *const tx_data)

Send data to Azure IoT Hub.

Parameters
  • tx_data[in] Pointer to struct containing data to be transmitted to Azure IoT Hub.

Return values
  • 0 – If successful.

  • -EINVAL – if a NULL pointer was provided.

  • -ENOMSG – if the provided message topic was invalid.

  • -EMSGSIZE – an internal buffer is too small to hold the topic data. This can for instance happen if message properties are in use, as they are appended to the topic.

  • -ENOTCONN – if the device is not connected to an IoT Hub.

  • -ENOMEM – if the request ID buffer was insufficient to create the ID.

  • -EFAULT – if there was an internal error in the library.

int azure_iot_hub_method_respond(struct azure_iot_hub_result *result)

Send response to a direct method invoked from the cloud.

Parameters
  • result[in] Structure containing result data from the direct method execution.

Return values
  • 0 – If successful.

  • -EINVAL – if a NULL pointer was provided.

  • -ENOTCONN – if there was no iot hub connection.

  • -EFAULT – if there was an error when creating the response message.

  • -ENXIO – if the MQTT library reported an error when publishing the response.

struct azure_iot_hub_buf
#include <azure_iot_hub.h>

Buffer to store data together with buffer size.

struct azure_iot_hub_property
#include <azure_iot_hub.h>

Property bag structure for key/value string pairs. Per Azure IoT Hub documentation, the key must be defined, while the value can be a string or empty.

Note

If value is provided as a string, it’s the equivalent to “key=value”. If the value is empty, it’s the equivalent of “key=” or “key”.

Public Members

struct azure_iot_hub_buf key

Property key.

struct azure_iot_hub_buf value

Property value.

struct azure_iot_hub_topic_data
#include <azure_iot_hub.h>

Azure IoT Hub topic data.

Public Members

enum azure_iot_hub_topic_type type

Topic type.

char *ptr

Pointer to topic name.

size_t size

Size of topic name.

struct azure_iot_hub_msg
#include <azure_iot_hub.h>

Azure IoT Hub transmission data.

Public Members

struct azure_iot_hub_topic_data topic

Topic data is sent/received on.

struct azure_iot_hub_buf payload

Pointer to the payload sent/received from Azure IoT Hub.

struct azure_iot_hub_buf request_id

Request ID that can be populated if relevcant for the message type.

enum mqtt_qos qos

Quality of Service for the message.

uint16_t message_id

Message id used for the message, used to match acknowledgments.

uint8_t dup_flag

Duplicate flag. 1 indicates the message is a retransmission, Usually triggered by missing publication acknowledgment.

uint8_t retain_flag

Retain flag. 1 indicates to the IoT hub that the message should be stored persistently.

struct azure_iot_hub_method
#include <azure_iot_hub.h>

Azure IoT Hub direct method data.

Public Members

struct azure_iot_hub_buf name

Method name.

struct azure_iot_hub_buf request_id

Method request ID.

struct azure_iot_hub_buf payload

Method payload.

struct azure_iot_hub_result
#include <azure_iot_hub.h>

Azure IoT Hub result structure.

Used to signal result of direct method execution from device to cloud, and to receive result of device twin updates (twin updates sent from the device will receive a result message back from the cloud with success or failure).

Public Members

struct azure_iot_hub_buf request_id

Request ID to which the result belongs.

uint32_t status

Status code.

struct azure_iot_hub_buf payload

Result payload.

struct azure_iot_hub_evt
#include <azure_iot_hub.h>

Struct with data received from Azure IoT Hub.

Public Members

enum azure_iot_hub_evt_type type

Type of event.

struct azure_iot_hub_config
#include <azure_iot_hub.h>

Structure for Azure IoT Hub connection parameters.

Public Members

struct azure_iot_hub_buf hostname

Hostname to IoT Hub to connect to. If the buffer size is zero, the device ID provided by CONFIG_AZURE_IOT_HUB_HOSTNAME is used. If DPS is enabled and use_dps is set to true, the provided hostname is ignored.

struct azure_iot_hub_buf device_id

Device id for the Azure IoT Hub connection. If the buffer size is zero, the device ID provided by Kconfig is used.

bool use_dps

Use DPS to obtain hostname and device ID if true. Using DPS requires that CONFIG_AZURE_IOT_HUB_DPS is enabled and DPS configured accordingly. If a hostname and device ID have already been obtained previously, the stored values will be used. To re-run DPS, the DPS information must be reset first. Note that using this option will use the device ID as DPS registration ID and the ID cope from CONFIG_AZURE_IOT_HUB_DPS_ID_SCOPE . For more fine-grained control over DPS, use the azure_iot_hub_dps APIs directly insted.