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

Here is the complete code

# import for async

import asyncio

# import library for GPIO

import RPi.GPIO as GPIO

# time library

import time

# Port of PIR i.e. GPIO14

pir_port = 14

# import for environment variable

import os

#import IoTHub client

from azure.iot.device.aio import IoTHubDeviceClient

# function to init GPIO of the Pi

def InitGPIO():

    # print GPIO info (not needed for initialization. Just to ensure that it works)

    print(GPIO.RPI_INFO)

    # Setup GPIO mode to Broadcom

    GPIO.setmode(GPIO.BCM)

    # configure GPIO14 as input pin

    GPIO.setup(pir_port,  GPIO.IN)

async def InitIoTHubClient():

    # Fetch the connection string from an enviornment 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()

async def main():

    # stay in the loop to monitor PIR

    try:

        while (True):

            # if the input is zero, nobody is there at the sensor

            if GPIO.input(pir_port) == 0:

                print("000")

            else:

                # found somebody at the sensor

                print("111")

                global device_client

                await device_client.send_message("Found human!")

            # wait for 1 sec whether you detect someone or not

            time.sleep(1)

    # If user presses ^C cleanup the GPIO and disconnect from the IoT Hub

    except KeyboardInterrupt:

        GPIO.cleanup()

        await device_client.disconnect()

    print("Exiting")

if __name__ == "__main__":

    InitGPIO()

    asyncio.run(InitIoTHubClient())

    asyncio.run(main())
  • Copy the file to Raspbery Pi (using WinSCM)

 

The Raspberry Pi will need installation of one more package to send data to Azure. SSH into raspberry pi and install pip and the following package.

  • sudo apt install python3-pip
  • pip3 install azure-iot-device
 
Now you need to run the program as well as monitor IoT Hub to see if the messages are getting sent there.
 
  • You can run the program from the visual studio code using SSH and running
  • python3 <filename>
 
Messages in the IoTHub can be monitored using Azure CLI as follows:

# logs in the Azure account

az login

# Start monitoring

az iot hub monitor-events --hub-name <your hub> --output table
 
Now when you place your hand (or yourself) in front of the sensor, the shell will show the following message.
IotHubOutput
 
This proves that the data is sent to the Azure IoT Hub. Your backend system should be free to process it from there. 
 
If you want to develop on Azure using Python here is the documentation.
 
If you have come to this page via search and want to see the series, here is the beginning.

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