Sending the data to Azure – Part 3 of 3

There are several patterns to send the data to Azure from an IoT Edge device. The most common route in the patterns is sending data from a device to IoT Hub.
There are various ways to authenticate a device against the hub. For the demo, the authentication is done using its connection string. Here are the steps to create an IoT Hub and send the data to it using Python.

Prerequisites

  1. Install Azure CLI.
  2. To monitor IoT Hub using the Az CLI, install an extension in it with the following command:
    az extension add --name azure-cli-iot-ext
  3. Create an account on Azure

Steps

  • Create an Azure IoT Hub as described here.
  • Make sure that you register a device in it with Symmetric Key and note it’s device name and connection string.

Here is how to modify the existing program to send data to Azure IoT Hub.

Azure Python SDK provides a class to access IoTHub. Import it as follows:

#import IoTHub client from azure.iot.device.aio

import IoTHubDeviceClient

Define a method to initialize it.

async def InitIoTHubClient():
# Fetch the connection string from an environment variable
conn_str = "HostName=<your hostname>.azure-devices.net;DeviceId=<Your device id>;SharedAccessKey=<your access key>"
# Create instance of the device client using the authentication provider
global device_client
device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)
# Connect the device client.
await device_client.connect()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s