Device-to-Cloud Tutorials

This section provides comprehensive guides on enabling your IoT devices to securely send telemetry and data to Azure IoT Hub.

Overview

Device-to-cloud (D2C) messaging is a fundamental capability for IoT solutions. It allows devices to transmit telemetry data, operational events, and status updates to the cloud for processing, analysis, and storage. Azure IoT Hub provides a robust and scalable platform to manage this communication securely.

Key Concepts

  • Telemetry: Sensor readings, operational data, and other messages sent from a device to the cloud.
  • Messages: D2C messages can be sent with configurable properties, including message routing information.
  • Security: Each device must authenticate with IoT Hub using X.509 certificates or shared access signatures (SAS) tokens.
  • Protocols: Common protocols for D2C communication include MQTT, AMQP, and HTTPS.

Tutorials

  1. 1

    Set up Azure IoT Hub

    Learn how to create an Azure IoT Hub instance in your Azure subscription and register your first device.

    Prerequisites: An Azure account. You can create a free account if you don't have one.

    Follow these steps:

    1. Navigate to the Azure portal.
    2. Search for "IoT Hub" and select it.
    3. Click "Create".
    4. Fill in the required details (Subscription, Resource Group, Region, IoT Hub name, Pricing tier).
    5. Click "Review + create", then "Create".
    Guide to Creating IoT Hub
  2. 2

    Register a Device in IoT Hub

    Learn how to register a physical or simulated device with your IoT Hub instance. This step generates the device connection string needed for your device to authenticate.

    Steps:

    1. Open your IoT Hub in the Azure portal.
    2. Go to "Devices" under "Explorers".
    3. Click "+ Add device".
    4. Provide a Device ID and choose an authentication type (e.g., Symmetric key).
    5. Click "Save".
    6. Copy the Primary Connection String for your device.
    Note: Securely store your device connection string. It's a secret credential.
  3. 3

    Simulate a Device and Send Telemetry (Python)

    This tutorial shows how to use the Azure IoT SDK for Python to simulate a device sending temperature and humidity data to IoT Hub.

    Prerequisites:

    • Python 3.7+ installed
    • Device connection string from the previous step

    Code Example:

    
    import asyncio
    import os
    import random
    from azure.iot.device.aio import IoTHubDeviceClient
    
    # Replace with your device connection string
    CONNECTION_STRING = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")
    
    async def send_telemetry_data(device_client):
        print("Sending telemetry data...")
        while True:
            temperature = 20 + (random.random() * 15)
            humidity = 60 + (random.random() * 20)
            message = {
                "temperature": round(temperature, 2),
                "humidity": round(humidity, 2)
            }
            await device_client.send_message(str(message))
            print(f"Sent message: {message}")
            await asyncio.sleep(5) # Send every 5 seconds
    
    async def main():
        print("Connecting to IoT Hub...")
        # Create instance of the device client using the connection string
        device_client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
    
        # Connect the device client.
        await device_client.connect()
        print("Connected to IoT Hub.")
    
        # Start sending telemetry data
        await send_telemetry_data(device_client)
    
        # Finally, disconnect the device client.
        await device_client.disconnect()
        print("Disconnected from IoT Hub.")
    
    if __name__ == "__main__":
        # To run this sample, you need to set the IOTHUB_DEVICE_CONNECTION_STRING environment variable.
        if CONNECTION_STRING is None:
            print("Error: IOTHUB_DEVICE_CONNECTION_STRING environment variable not set.")
        else:
            asyncio.run(main())
                                

    To run this:

    1. Install the SDK: pip install azure-iot-device
    2. Set the environment variable: export IOTHUB_DEVICE_CONNECTION_STRING="YOUR_DEVICE_CONNECTION_STRING"
    3. Run the script: python your_script_name.py
    More Azure IoT SDK Examples
  4. 4

    Monitor Device Messages in IoT Hub

    Discover how to use the Azure portal or Azure CLI to view the D2C messages sent by your devices in real-time.

    Using Azure Portal:

    1. Navigate to your IoT Hub.
    2. Under "Explorers", select "Message routing".
    3. Configure a route to an endpoint (e.g., Event Hubs, Storage).
    4. Alternatively, use the "Monitoring" section to view live events if configured.

    Using Azure CLI:

    
    az iot hub monitor-events --hub-name YOUR_IOT_HUB_NAME --device-id YOUR_DEVICE_ID
                                
    Important: For production scenarios, consider routing messages to dedicated endpoints like Event Hubs or Azure Functions for robust processing.