Stream Data to Azure IoT Hub from Raspberry Pi
Tags: azure, iot, raspberrypi, beginners
Published: 2022-02-25 04:50:00

This is a Basic IoT Project where I have used used my Raspberry Pi to stream data to Microsoft Azure. It will be helpful for beginners who want to know about IoT and Azure.
Suppose you want to get some sensor data and monitor it from anywhere in the world. Azure IoT Hub is a great tool to do this. You can even make your own dataset for ML projects by streaming sensor data to Azure.

## Azure IoT Hub
Microsoft Azure has some IoT services. IoT Hub is one of them. Here you can stream data from your device such as Raspberry Pi or ESP32. This is really helpful if you are collecting data from sensors and want to monitor your data in the cloud. I already have an Azure Account. Go to this [link](https://azure.microsoft.com/en-us/) if you don't already have one.

## Raspberry Pi
I am using Raspberry Pi 4 as my IoT Device where I will be sending some text messages to Azure IoT Hub. You can also send your sensor data by editing the code. In this case I am using Raspberry Pi OS with Desktop. It comes with Python 3 and Thonny Python IDE by default. 

## Creating Azure IoT Resource
Go to Azure portal and select IoT Hub. Tap the **Create** button and it will go to this page
 
![Iot portal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2jiol8m0aand3e2fprv5.JPG)

I am using Azure Student Subscription. You can select your own free subscription. Resource group will be empty if you have a new account. I have already created a Resource Group _raspberrypi_ and selected it from dropdown. You have to give a unique name as **IoT hub name** and Select a region closest to you. In my case I have named it **pixyz**.

![Networking Tab](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mbfkkwg660hxcmg10bnm.JPG)
You can leave everything as it is in _Networking Tab_.

![Pricing Tab](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ax6pyhdqa0npb5fpy8hb.JPG)
For the _Pricing and scale tier_ select **F1:Free Tier** from Dropdown. It has a message limit of 8000 per day. It will be enough for this demo.

![Tag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9us5411sugo5gzl0ed86.JPG)
In the _Tag_ section you can give any name and value as tag as you want.

![validation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8vsjhagk65mfur5hmylj.JPG)
In the _Review and Create_ section it will show  **Validation Passed** if everything is in place. After that Tap the **Create** Button and it will take some time for deployment.

![devices](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2y8fzzh5mcuusbn56rm1.JPG) 
After successful deployment go to the resource (pixyz) you just created and it will show an overview of the resource. From the left side panel go to **Devices** and Select **Add Device**.

![create devices](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gox95rcmpk963byacsne.JPG) 
Give a **Device Id** and click on **Save**.

![primary key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/luhr785brezhe6xg2k53.JPG)
After the device has been added click on the Device Name (raspberry-pi) that you created and it will show you this page. There will be some info about the device. Copy the **Primary Connection String** and save it in a text file so that you can use it later.

## Connecting VS Code to Azure
Now we will use VS Code to connect with Azure IoT Hub. Install [VS Code](https://code.visualstudio.com/download) from this link if needed.

![VS Code extension](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5jhoukcv52jh8t5p56sg.JPG)

Install [Azure IoT Tools](https://marketplace.visualstudio.com/items?itemName=vsciot-vscode.azure-iot-tools) Extension for VS Code.

![VS Code extension installed](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iv41ykynyos96xkkecn5.JPG)
After installation it will look something like this.

![File explorer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6iy6i902nd6fxjn6ql4t.JPG)
You will Find Azure IoT Hub section in the File Explorer. Select it and you have to authorize your Azure account first. You will see your IoT Hub Devices from VS Code. (Pretty Cool)

## Configuring Raspberry Pi
Now go to Raspberry Pi and open terminal. Run the commands to install packages.

```
sudo pip3 install azure-iot-device
sudo pip3 install azure-iot-hub
```
Now open Thonny Python IDE and copy the code and save it under any name.

```
import time

from azure.iot.device import IoTHubDeviceClient, Message

CONNECTION_STRING = "{Primary Connection String}"

# Define the JSON message to send to IoT Hub.
From = "Pi"
To = "Azure"
MSG_TXT = '{{"From": {first},"To": {second}}}'

def iothub_client_init():
    # Create an IoT Hub client
    client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
    return client

def iothub_client_telemetry_sample_run():

    try:
        client = iothub_client_init()
        print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit" )
        while True:
            # Build the message with simulated telemetry values.
            first = From
            second = To
            msg_txt_formatted = MSG_TXT.format(first=first, second=second)
            message = Message(msg_txt_formatted)

            # Send the message.
            print( "Sending message: {}".format(message) )
            client.send_message(message)
            print ( "Message successfully sent" )
            time.sleep(3)

    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )

if __name__ == '__main__':
    print ( "IoT Hub Quickstart #1 - Simulated device" )
    print ( "Press Ctrl-C to exit" )
    iothub_client_telemetry_sample_run()
```
Replace the **Connection_String** variable with your own **Primary_Connection_String** that you copied earlier from Azure.
Now Run the python file and Raspberry Pi will start sending messages to Azure IoT Hub.

![End to end](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p940quvwliczwtzp6pe5.JPG)
In VS Code Click on **Azure IoT Hub** from File Explorer and right click on **raspberry-pi** (You IoT Device Name) and select **Start Monitoring built in Endpoint**. 

![vs code terminal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fk5t0ra4r916qmtb8zvg.JPG)
Now you will see the messages coming from Raspberry Pi to Azure IoT hub.

![Pi terminal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jxpo9fbcxv8nxg2zhmjn.png)
From Raspberry Pi you will see something like this in Thonny editor. 
If you don't have any Raspberry Pi you can use the Raspberry Pi Simulator to do the same thing. Thanks for reading :) .