DEV Community

Cover image for Stream Data to Azure IoT Hub from Raspberry Pi
Nihal Baig
Nihal Baig

Posted on • Updated on

Stream Data to Azure IoT Hub from Raspberry Pi

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

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
You can leave everything as it is in Networking Tab.

Pricing Tab
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
In the Tag section you can give any name and value as tag as you want.

validation
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
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
Give a Device Id and click on Save.

primary key
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 from this link if needed.

VS Code extension

Install Azure IoT Tools Extension for VS Code.

VS Code extension installed
After installation it will look something like this.

File explorer
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
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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
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
Now you will see the messages coming from Raspberry Pi to Azure IoT hub.

Pi terminal
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 :) .

Discussion (0)