Edge Computing with Azure IoT: Practical Example
Introduction
Edge Computing is a technology that allows data processing directly on the device, reducing latency and network traffic to the cloud. This approach is particularly useful in scenarios where internet connectivity is not always available or when real-time response is required. In this tutorial, we will see how to set up an IoT Edge device with Azure IoT using a practical example. Our project consists of two applications:
1️⃣ Device App → A Docker application running on the Edge device, simulating a temperature sensor and sending data to Azure IoT Hub.
2️⃣ Event Consumer → A Python application running on a PC that reads data from Azure Event Hub and processes it.
This guide is designed to be clear even for those who have never worked with Azure IoT! 🚀
🔍 Use Case
Imagine having a temperature monitoring system in a factory. Each IoT Edge device measures ambient temperature and sends data to the cloud only when the temperature exceeds a certain threshold. This approach allows:
- ✅ Reducing network traffic by sending only relevant data.
- ✅ Triggering alarm notifications in case of abnormal values.
- ✅ Processing data in real time on the device without continuously transferring it to the cloud.
- ✅ Reducing server load and improving scalability.
🌐 What is Azure IoT Hub?
Azure IoT Hub is a managed service from Microsoft that acts as a bridge between IoT devices and the cloud. It allows connecting, monitoring, and controlling millions of devices in a scalable and secure way.
✨ Key Features:
- Bidirectional communication between devices and the cloud.
- Advanced authentication and security to protect devices with access keys and certificates.
- Remote device management and monitoring with logs and telemetry.
- Scalability to handle thousands or millions of devices without performance issues.
- Integration with Azure Event Hub, Azure Functions, and AI for advanced processing.
In this guide, Azure IoT Hub will collect data from the Edge device and forward it to Azure Event Hub, where it can be read and processed.
🏢 Provisioning the Edge Device
Before running the Device App, the device hosting it must be configured and registered with Azure IoT Hub.
In our example, we simulated the device using Ubuntu 20.04 LTS.
Microsoft provides an official guide for provisioning a single Linux device with symmetric authentication, available here: 👉 Official Microsoft Guide
After installing the packages, follow the guide to register the device with Azure IoT Hub.
Once this setup is complete, the device is ready to run Device App via Docker.
📡 Device App: Simulating the IoT Sensor
Where is it executed? 🔜 On the Edge device (Docker)
What does it do?
- Simulates a temperature sensor generating random values.
- If the temperature exceeds a threshold, it sends an alert message to Azure IoT Hub.
📝 Sensor Code (main.py)
import json
import random
import time
import os
from azure.iot.device import IoTHubDeviceClient
# Connection string from environment variable
CONNECTION_STRING = os.getenv("IOT_HUB_CONNECTION_STRING")
if not CONNECTION_STRING:
raise ValueError("IOT_HUB_CONNECTION_STRING is not set!")
client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
def monitor_temperature():
while True:
temperature = random.uniform(-10, 10)
threshold = 2
if temperature < -threshold or temperature > threshold:
message = {
"temperature": temperature,
"alert": "⚠️ Temperature out of range!"
}
print("⚠️ ALERT:", message)
client.send_message(json.dumps(message))
else:
print(f"🌡 Temperature OK: {temperature:.2f}°C")
time.sleep(5)
if __name__ == "__main__":
try:
client.connect()
print("✅ Connected to IoT Hub!")
except Exception as e:
print(f"❌ Connection error: {e}")
monitor_temperature()
🚀 Deploying the Docker Image
After creating the Docker image, it must be uploaded to an Azure Container Registry (ACR) and then automatically deployed via the Azure portal.
To upload the image to ACR, use the following commands:
docker tag iot-edge-device myacr.azurecr.io/iot-edge-device
az acr login --name myacr
docker push myacr.azurecr.io/iot-edge-device
After uploading the image, go to the Device section in Azure IoT Hub, fill out the form to specify the image to be deployed automatically on the device, and set the required environment variables.
Once this step is complete, Azure will automatically deploy the image on the Edge device without manual intervention.
📡 Event Consumer: Reading the Data
Where is it executed? 🔜 On a PC or server
What does it do?
- Receives data sent by the Edge device via Azure Event Hub.
- Reads only new messages to avoid duplicates.
📝 Consumer Code (main.py)
import os
from azure.eventhub import EventHubConsumerClient
# Connection string and Event Hub name from environment variables
CONNECTION_STR = os.getenv("EVENT_HUB_CONNECTION_STRING")
EVENTHUB_NAME = os.getenv("EVENT_HUB_NAME")
CONSUMER_GROUP = "$Default"
if not CONNECTION_STR or not EVENTHUB_NAME:
raise ValueError("Environment variables EVENT_HUB_CONNECTION_STRING and EVENT_HUB_NAME must be set!")
def on_event(partition_context, event):
print(f"📰 Message received from Partition {partition_context.partition_id}: {event.body_as_str()}")
partition_context.update_checkpoint(event)
client = EventHubConsumerClient.from_connection_string(CONNECTION_STR, CONSUMER_GROUP, eventhub_name=EVENTHUB_NAME)
with client:
print("📰 Listening for messages from Event Hub...")
client.receive(on_event=on_event, starting_position="@latest")
📥 Expected Output from the Consumer
Once the Event Consumer is running, it will listen for events coming from Azure Event Hub. Every time the Device App sends a temperature message, the consumer will receive and process it.
A successful execution should display an output similar to the following:
📰 Listening for messages from Event Hub...
📰 Message received from Partition 0: {"temperature": 5.6, "alert": "Temperature OK"}
📰 Message received from Partition 0: {"temperature": -3.2, "alert": "⚠️ Temperature out of range!"}
📰 Message received from Partition 0: {"temperature": 7.8, "alert": "Temperature OK"}
If the temperature exceeds the threshold set in the Device App, an alert message (⚠️ Temperature out of range!
) will be generated. Otherwise, a confirmation message (Temperature OK
) will be displayed.
✅ Conclusion
📂 Full code on GitHub 👉 DevAccelerateCom/azure-iot-edge-example
💡 Subscribe to the YouTube channel for more tutorials! 🚀