Connect Your Device to Azure IoT Hub
This guide provides step-by-step instructions to connect a device to Azure IoT Hub using common SDKs. Learn how to send telemetry data and receive device-to-cloud messages.
Prerequisites
- An Azure subscription. If you don't have one, create a free account.
- An IoT Hub instance created in your Azure subscription. Refer to Create an IoT Hub.
- Your device's unique connection string. This can be found in the Azure portal under your IoT Hub -> Devices ->
-> Primary Connection String. - Ensure your device is configured with the necessary network connectivity to reach Azure IoT Hub.
Choose Your Device SDK
Azure IoT provides SDKs for various programming languages and platforms. Select the SDK that best fits your device's environment.
Install the SDK and Dependencies
Follow the specific installation instructions for your chosen SDK. This typically involves using a package manager like pip (Python), npm (Node.js), Maven (Java), or NuGet (.NET).
Example (Python):
pip install azure-iot-device
Write Device Code
The core of device connection involves initializing the IoT Hub client with your device's connection string, establishing a connection, and then sending messages.
Example (Python - Basic Telemetry):
import os
import random
import time
from azure.iot.device import IoTHubDeviceClient, Message
# Replace with your device's connection string
CONNECTION_STRING = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")
def main():
print("Connecting to IoT Hub...")
device_client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
def send_message_handler(message):
print(f"Received message: {message}")
try:
# Connect the device client.
device_client.connect()
print("Connected to IoT Hub.")
# Set the handler for incoming messages.
device_client.on_message_received = send_message_handler
# Send telemetry messages
print("Sending telemetry...")
for i in range(100):
temperature = 20 + (random.random() * 15)
humidity = 60 + (random.random() * 20)
data = f"{{'temperature': {temperature:.2f}, 'humidity': {humidity:.2f}}}"
message = Message(data)
message.content_encoding = "utf-8"
message.content_type = "application/json"
print(f"Sending message: {message}")
device_client.send_message(message)
time.sleep(5) # Send a message every 5 seconds
except KeyboardInterrupt:
print("IoT Hub device sending stopped")
finally:
# Gracefully shut down the client
print("Shutting down IoT Hub device client...")
device_client.shutdown()
print("Client shut down.")
if __name__ == "__main__":
if not CONNECTION_STRING:
print("Error: IOTHUB_DEVICE_CONNECTION_STRING environment variable not set.")
else:
main()
Remember to set the IOTHUB_DEVICE_CONNECTION_STRING
environment variable with your device's actual connection string before running the code.
Run Your Device Application
Execute your device code. You should see output indicating connection and message transmission.
Example (Python):
python your_device_app.py
Monitor in Azure Portal
Navigate to your IoT Hub in the Azure portal. Under "Metrics" or by using Azure CLI/PowerShell, you can verify that your device is connected and receiving telemetry data.
- Go to your IoT Hub resource.
- Under "Monitoring" -> "Metrics", you can view metrics like "Telemetry messages sent".
- Alternatively, use Azure CLI:
az iot hub monitor-events --hub-name
Congratulations! You have successfully connected your device to Azure IoT Hub and started sending telemetry. Explore further to learn about device twins, direct methods, and device-to-cloud messaging patterns.