Azure IoT Hub SDK

Azure IoT Hub SDKs

The Azure IoT Hub SDKs simplify the development of IoT solutions across multiple platforms and languages. Choose the SDK that best matches your development stack.

C#/.NET
Java
Python
Node.js

.NET SDK

Install the package via NuGet:

dotnet add package Microsoft.Azure.Devices

Simple send telemetry

using Microsoft.Azure.Devices.Client;
using System.Text;
using System.Threading.Tasks;

var deviceClient = DeviceClient.CreateFromConnectionString(
    "HostName=your-iothub.azure-devices.net;DeviceId=myDevice;SharedAccessKey=...",
    TransportType.Mqtt);

await deviceClient.SendEventAsync(new Message(Encoding.UTF8.GetBytes("{\"temperature\":23}")));
Console.WriteLine("Telemetry sent");

Java SDK

Add the dependency using Maven:

<dependency>
    <groupId>com.microsoft.azure.sdk.iot</groupId>
    <artifactId>iot-device-client</artifactId>
    <version>1.33.0</version>
</dependency>

Send telemetry

import com.microsoft.azure.sdk.iot.device.*;
import java.io.IOException;

public class SendTelemetry {
    public static void main(String[] args) throws IOException {
        IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
        String connString = "HostName=your-iothub.azure-devices.net;DeviceId=myDevice;SharedAccessKey=...";
        DeviceClient client = new DeviceClient(connString, protocol);
        client.open();

        Message msg = new Message("{\"temperature\":23}");
        client.sendEventAsync(msg, (status, ctx) -> System.out.println("Sent: " + status), null);
    }
}

Python SDK

Install with pip:

pip install azure-iot-device

Send telemetry example

from azure.iot.device import IoTHubDeviceClient, Message
import asyncio

conn_str = "HostName=your-iothub.azure-devices.net;DeviceId=myDevice;SharedAccessKey=..."

client = IoTHubDeviceClient.create_from_connection_string(conn_str)

async def send():
    await client.connect()
    await client.send_message(Message('{"temperature":23}'))
    print("Message sent")
    await client.shutdown()

asyncio.run(send())

Node.js SDK

Install via npm:

npm install azure-iot-device azure-iot-device-mqtt

Sample code

const { Client } = require('azure-iot-device');
const { Mqtt } = require('azure-iot-device-mqtt');

const connectionString = 'HostName=your-iothub.azure-devices.net;DeviceId=myDevice;SharedAccessKey=...';
const client = Client.fromConnectionString(connectionString, Mqtt);

client.open((err) => {
    if (err) {
        console.error('Could not connect: ' + err.message);
    } else {
        const message = new Message(JSON.stringify({ temperature: 23 }));
        client.sendEvent(message, (err) => {
            if (err) console.error('Send error: ' + err.toString());
            else console.log('Message sent');
            client.close();
        });
    }
});

Resources