Hello @DJ, Below is a sample code to retrieve device IDs from an Azure IoT Hub SQL query and pass each deviceId.
var query = registryManager.CreateQuery("SELECT * FROM devices", 100);
while (query.HasMoreResults)
{
var page = await query.GetNextAsTwinAsync();
foreach (var twin in page)
{
string deviceId = twin.DeviceId;
Console.WriteLine($"Processing Device ID: {deviceId}");
Below is sample Azure Function HTTP trigger code, to retrieves IoT device IDs from Azure IoT Hub and processes them concurrently. Refer this MSDOC for Query examples with the service SDKs.
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Devices;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace FunctionApp7
{
public static class ProcessIoTDevices
{
private const string iotHubConnectionString = "HostName=TODO.azure-devices.net;SharedAccessKeyName=TODO;SharedAccessKey=TODO";
[FunctionName("ProcessIoTDevices")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("Processing IoT devices concurrently...");
try
{
using var registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
List<string> deviceIds = await RetrieveDeviceIds(registryManager, log);
if (deviceIds.Count == 0)
{
return new OkObjectResult("No devices found in IoT Hub.");
}
var tasks = deviceIds.Select(deviceId => PrepareFlowDevice(deviceId, log));
await Task.WhenAll(tasks);
return new OkObjectResult($"Processed {deviceIds.Count} devices in parallel.");
}
catch (Exception ex)
{
log.LogError($"Error processing IoT devices: {ex.Message}");
return new StatusCodeResult(500);
}
}
private static async Task<List<string>> RetrieveDeviceIds(RegistryManager registryManager, ILogger log)
{
var deviceIds = new List<string>();
var query = registryManager.CreateQuery("SELECT deviceId FROM devices", 100);
try
{
while (query.HasMoreResults)
{
var page = await query.GetNextAsJsonAsync();
foreach (var json in page)
{
dynamic twin = JsonConvert.DeserializeObject(json);
deviceIds.Add((string)twin.deviceId);
}
}
log.LogInformation($"Retrieved {deviceIds.Count} device IDs.");
}
catch (Exception ex)
{
log.LogError($"Error retrieving device IDs: {ex.Message}");
}
return deviceIds;
}
private static async Task PrepareFlowDevice(string deviceId, ILogger log)
{
try
{
await Task.Delay(500);
log.LogInformation($"Device {deviceId} processed.");
}
catch (Exception ex)
{
log.LogError($"Error processing device {deviceId}: {ex.Message}");
}
}
}
}
Hope this helps!
If you found this answer helpful, please click Accept Answer and consider upvoting it /click yes.
If you have any further questions, please click Comment.