ThisCalculator

Everyday

Azure IoT Hub: Identity, Messaging & Routing Guide

Updated · Standard formula, shown below

This guide explains how Azure IoT Hub manages device identity, handles device-to-cloud and cloud-to-device messaging, and routes messages to downstream services. You will learn the core concepts, the step-by-step setup for each feature, and how to troubleshoot common issues.

What You’ll Need

  • An active Azure subscription
  • Azure CLI installed (or use Azure Cloud Shell)
  • Basic familiarity with JSON and REST APIs
  • A code editor or terminal for testing device connections

Step-by-Step

Part 1: Device Identity

  1. Create an IoT Hub – In the Azure portal, search for “IoT Hub” and click “Create”. Fill in the resource group, region, and a unique name. Choose a pricing tier (F1 free tier is fine for testing).
  2. Add a device identity – Go to your IoT Hub, select “Devices” under the “Device management” section, then click “+ Add Device”. Provide a device ID (e.g., sensor-001) and leave authentication set to “Symmetric key”. Click “Save”.
  3. Get the device connection string – Click on the newly created device, copy the “Primary Connection String”. This string contains the hostname, device ID, and shared access key. It is used by the device to authenticate.
  4. Understand device twins – Each device has a twin, a JSON document that stores device state (reported properties) and desired configuration (desired properties). You can update these via the portal or SDKs.

Part 2: Device-to-Cloud Messaging

  1. Send a message from a device – Use the Azure IoT SDK (e.g., Python, C#, Node.js) to send a telemetry message. The device connects using the connection string and sends a message to the endpoint devices/{deviceId}/messages/events.
  2. Set message properties – You can add application properties (key-value pairs) and system properties (like message ID, correlation ID) to the message. These are useful for routing and filtering.
  3. Read messages in the portal – To verify, use the “Built-in endpoints” > “Events” in the portal, or use the Azure CLI command az iot hub monitor-events --hub-name {your-hub} --device-id {device-id}.

Part 3: Cloud-to-Device Messaging

  1. Send a command from the cloud – Use the portal’s “Message to Device” feature or the SDK to send a message to devices/{deviceId}/messages/devicebound. The device must be connected and listening.
  2. Handle delivery acknowledgments – The device can send a feedback message to confirm receipt. Set the “Acknowledgment” field to “positive”, “negative”, or “full” when sending.

Part 4: Message Routing

  1. Add a custom endpoint – In the IoT Hub, go to “Message routing” > “Custom endpoints”. Click “+ Add” and choose a service like Storage Container, Service Bus Queue, or Event Hubs. Fill in the connection details.
  2. Create a route – Under “Routes”, click “+ Add”. Give the route a name, select the data source (Device Telemetry Messages), and choose the endpoint you just created.
  3. Write a routing query – In the “Routing query” field, you can filter messages. For example, temperature > 25 will only route messages where the application property temperature exceeds 25. Use the syntax property = 'value' for string properties.
  4. Enable fallback route – The fallback route sends all messages that don’t match any route to the built-in endpoint (messages/events). You can enable or disable it in the “Message routing” settings.

Common Mistakes

  • Using the wrong connection string – Device connection strings are different from hub-level shared access policy strings. The device string starts with HostName=...;DeviceId=...;SharedAccessKey=....
  • Forgetting to set message properties – Routing queries rely on message properties. If you don’t set them, your query may match nothing.
  • Mixing up device-to-cloud and cloud-to-device endpoints – Sending to the wrong endpoint will result in errors or messages being silently dropped.
  • Not enabling the fallback route – If you disable it and no route matches, messages are discarded. Keep it enabled unless you have a specific reason.
  • Using the wrong SDK version – Always use the latest stable SDK for your language to avoid deprecated API issues.

Tips

  • Use device twins for configuration – Instead of sending individual commands, update desired properties. Devices can react to changes automatically.
  • Batch messages for efficiency – If you send many small messages, batch them into a single request to reduce overhead.
  • Monitor with Azure Monitor – Enable diagnostic settings for your IoT Hub to see metrics like “messages completed” and “routing failures”.
  • Test routing with the portal – Use the “Test Route” button in the portal to simulate a message and see if it matches your query.
  • Secure your connection strings – Never embed them in client-side code. Use Azure Key Vault or environment variables.

Troubleshooting

  • Device cannot connect – Check the connection string for typos. Verify the device is not disabled (status should be “Enabled”). Ensure the device ID matches exactly.
  • Messages not appearing in the portal – Use the Azure CLI monitor command to see if messages are arriving. If not, check your device code for errors. If they are, the issue is with the portal’s event display – try refreshing.
  • Routing not working – Check the route’s query syntax. Use the “Test Route” feature to see if a sample message matches. Verify the endpoint is healthy (check its status in the portal).
  • Cloud-to-device messages not received – The device must be connected and listening. Also check if the message TTL (time-to-live) expired. Set a longer TTL if needed.
  • Authentication errors – If you get 401 Unauthorized, your SAS token may be expired. Regenerate the connection string or use a token that doesn’t expire quickly.

Frequently Asked Questions

Can I have multiple devices with the same device ID?

No, device IDs must be unique within an IoT Hub. If you try to add a duplicate, you will get an error.

What is the difference between a device twin and a message?

A device twin is a JSON document that stores state and configuration, while a message is a transient data packet (telemetry or command). Twins are for long-lived state, messages for short-lived data.

How do I route messages based on the message body?

Routing queries can reference message body properties using the syntax $body.temperature for JSON bodies. For example, $body.temperature > 25.

Can I send a message to a specific device from the cloud?

Yes, use the cloud-to-device messaging feature. You need the device ID and the device must be connected to receive it.

What happens if a route fails?

IoT Hub will attempt to deliver the message to the endpoint. If it fails, it will retry a few times. If it still fails, the message is moved to the dead-letter queue (if configured) or dropped.

Is the free tier sufficient for production?

No, the free tier is limited to 8,000 messages per day and is meant for testing and evaluation. For production, use a paid tier like S1 or S2.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.