Azure IoT Hub Tutorial
Introduction
Azure IoT Hub is a managed service that acts as a central message hub for bi-directional communication between your IoT application and the devices it manages. It provides device-to-cloud and cloud-to-device communication, ensuring reliable and secure data transfer.
Prerequisites
Before you start using Azure IoT Hub, you need to have the following:
- An active Azure subscription
- Basic knowledge of Azure portal
- Some familiarity with IoT concepts
Step 1: Create an IoT Hub
To create an IoT Hub in Azure, follow these steps:
- Go to the Azure portal.
- Click on "Create a resource" and then select "IoT Hub".
- Fill in the necessary details such as Subscription, Resource Group, Region, and IoT Hub Name.
- Click "Review + Create" and then "Create".
Step 2: Register a Device
Once the IoT Hub is created, you need to register a device:
- Navigate to your IoT Hub in the Azure portal.
- Click on "IoT devices" under the "Explorers" section.
- Click on "New" to add a new device.
- Enter a Device ID and click "Save".
Step 3: Connect a Device
To connect a device to your IoT Hub, you need the connection string:
- Go to the registered device in the IoT Hub.
- Copy the "Primary Connection String".
- Use this connection string in your device code to establish a connection.
const connectionString = 'HostName=MyIoTHub.azure-devices.net;DeviceId=MyFirstDevice;SharedAccessKey=
Step 4: Send Device-to-Cloud Messages
Use the following code snippet to send messages from your device to the cloud:
const iothub = require('azure-iot-device'); const Message = iothub.Message; const client = iothub.Client.fromConnectionString(connectionString, iothub.Mqtt); function sendMessage() { const message = new Message(JSON.stringify({ temperature: 22.5, humidity: 60 })); client.sendEvent(message, (err, res) => { if (err) console.log('Send error: ' + err.toString()); if (res) console.log('Send status: ' + res.constructor.name); }); } sendMessage();
Step 5: Receive Cloud-to-Device Messages
Use the following code snippet to receive messages from the cloud:
client.on('message', (msg) => { console.log('Message received: ' + msg.getData().toString()); client.complete(msg, () => { console.log('Message processed'); }); });
Step 6: Monitor IoT Hub
You can monitor the activity in your IoT Hub using Azure Monitor:
- Go to your IoT Hub in the Azure portal.
- Click on "Metrics" under the "Monitoring" section.
- Select the metrics you want to monitor, such as "Total messages sent" or "Total messages received".
- Set the time range and view the metrics.
Conclusion
Azure IoT Hub provides a robust platform for managing IoT devices and ensuring secure, reliable communication between devices and the cloud. By following this tutorial, you should now have a basic understanding of how to create an IoT Hub, register devices, and send and receive messages.