Direct Methods
Direct Methods provide a synchronous, bi-directional communication pattern between a cloud solution and an IoT device. They are ideal for commanding a device, retrieving real‑time status, or performing configuration updates.
When to Use Direct Methods
- Triggering immediate actions on a device (e.g., reboot, firmware update)
- Retrieving a one‑time snapshot of device state
- Performing configuration changes that require acknowledgement
How It Works
- Cloud application calls
InvokeMethodAsync
on the device identity. - The IoT Hub routes the method request to the device client.
- The device processes the request and returns a response payload and status code.
- The cloud receives the response synchronously.
Sample Code
C#
Node.js
using Microsoft.Azure.Devices;
using System;
using System.Text;
using System.Threading.Tasks;
class Program{
static ServiceClient serviceClient;
const string connectionString = "";
const string deviceId = "myDevice";
static async Task Main(){
serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
var method = new CloudToDeviceMethod("reboot")
{
ResponseTimeout = TimeSpan.FromSeconds(30)
};
var result = await serviceClient.InvokeDeviceMethodAsync(deviceId, method);
Console.WriteLine($"\nStatus: {result.Status}");
Console.WriteLine($"Payload: {result.GetPayloadAsJson()}");
}
}
const { Client } = require('azure-iothub');
const connectionString = '';
const targetDevice = 'myDevice';
const client = Client.fromConnectionString(connectionString);
const methodParams = {
methodName: 'reboot',
payload: null,
timeoutInSeconds: 30
};
client.invokeDeviceMethod(targetDevice, methodParams, (err, result) => {
if (err) {
console.error('Failed to invoke method:', err);
} else {
console.log('Response status:', result.status);
console.log('Response payload:', result.payload);
}
});