Azure IoT Hub DPS custom allocation policies by functions- 在DPS中啓用設備自定義分配策略
視頻介紹:
azure iot hub DPS 自定義策略
圖文介紹:
本問參考官網文檔:https://docs.microsoft.com/zh-cn/azure/iot-dps/how-to-use-custom-allocation-policies
在實際的業務中,可能存在某個DPS服務根據特定的策略將設備分配到不同的Azure IoT Hub 的情況,比如:
1. 大型項目中,將不同客戶的設備分配到該客戶獨有的IoT Hub中;
2. 根據硬件版本號,將V1.1的版本號分配到中國東部2的IoT Hub,將V1.2的分配到中國北部的IoT Hub;
3. 根據硬件種類,將冰箱分配到冰箱專用的IoT Hub, 將空調分配到空調專用的IoT Hub;
4. 其他場景
這時候的這個分配規則,就是自定義規則,通過Azure functions實現,示意圖如下:
本例中,
1. 創建了兩個IoT Hub,一個是冰箱專用的,Hub名稱包含 fridge字樣,一個是空調專用的,hub名稱包含conditioner字樣;
2. 1個DPS服務,鏈接了上述兩個IoT Hub, 配置了一個Function 自定義分配規則;
3. 1個function app,通過http觸發,規則如上述圖片所示;
4. 使用示例代碼(C#)模擬設備進行測試,下載鏈接:https://codeload.github.com/Azure-Samples/azure-iot-samples-csharp/zip/master
重點步驟:
1.創建兩個IoT Hub, 一個是冰箱專用的,Hub名稱包含 fridge字樣,一個是空調專用的,hub名稱包含conditioner字樣
2. 創建1個DPS服務
3.鏈接兩個IoT Hub:
4. 準備Functions, Http 觸發:
引用如下包:
<PackageReference Include="Microsoft.Azure.Devices.Provisioning.Service" Version="1.5.0" />
<PackageReference Include="Microsoft.Azure.Devices.Shared" Version="1.16.0" />
代碼如下:
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.Devices.Shared; // For TwinCollection
using Microsoft.Azure.Devices.Provisioning.Service; // For TwinState
namespace Company.Function
{
public static class HttpTriggerCSharp1
{
[FunctionName("HttpTriggerCSharp1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
// Get request body
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
log.LogInformation("Request.Body:...");
log.LogInformation(requestBody);
// Get registration ID of the device
string regId = data?.deviceRuntimeContext?.registrationId;
string message = "Uncaught error";
bool fail = false;
ResponseObj obj = new ResponseObj();
if (regId == null)
{
message = "Registration ID not provided for the device.";
log.LogInformation("Registration ID : NULL");
fail = true;
}
else
{
string[] hubs = data?.linkedHubs.ToObject<string[]>();
// Must have hubs selected on the enrollment
if (hubs == null)
{
message = "No hub group defined for the enrollment.";
log.LogInformation("linkedHubs : NULL");
fail = true;
}
else
{
// This is a air-conditioner
if (regId.Contains("-conditioner"))
{
//Find the "conditioner" IoT hub configured on the enrollment
foreach(string hubString in hubs)
{
if (hubString.Contains("-conditioner"))
obj.iotHubHostName = hubString;
}
if (obj.iotHubHostName == null)
{
message = "No conditioner hub found for the enrollment.";
log.LogInformation(message);
fail = true;
}
else
{
// Specify the initial tags for the device.
TwinCollection tags = new TwinCollection();
tags["deviceType"] = "conditioner";
// Specify the initial desired properties for the device.
TwinCollection properties = new TwinCollection();
properties["state"] = "code";
// Add the initial twin state to the response.
TwinState twinState = new TwinState(tags, properties);
obj.initialTwin = twinState;
}
}
// This is fridge
else if (regId.Contains("-fridge"))
{
//Find the "-heatpumps-" IoT hub configured on the enrollment
foreach(string hubString in hubs)
{
if (hubString.Contains("-fridge"))
obj.iotHubHostName = hubString;
}
if (obj.iotHubHostName == null)
{
message = "No fridge hub found for the enrollment.";
log.LogInformation(message);
fail = true;
}
else
{
// Specify the initial tags for the device.
TwinCollection tags = new TwinCollection();
tags["deviceType"] = "fridge";
// Specify the initial desired properties for the device.
TwinCollection properties = new TwinCollection();
properties["state"] = "on";
properties["temperatureSetting"] = "-18";
// Add the initial twin state to the response.
TwinState twinState = new TwinState(tags, properties);
obj.initialTwin = twinState;
}
}
// Unrecognized device.
else
{
fail = true;
message = "Unrecognized device registration.";
log.LogInformation("Unknown device registration");
}
}
}
log.LogInformation("\nResponse");
log.LogInformation((obj.iotHubHostName != null) ? JsonConvert.SerializeObject(obj) : message);
return (fail)
? new BadRequestObjectResult(message)
: (ActionResult)new OkObjectResult(obj);
}
}
public class ResponseObj
{
public string iotHubHostName {get; set;}
public TwinState initialTwin {get; set;}
}
}
發佈Function:
5. 在DPS中創建組註冊,策略選擇自定義function,IoT Hub 選擇冰箱和空調兩個
6. 運行設備示例代碼:
修改idScope, primarykey,secondarykey, 可參見《DPS 組註冊示例》
其中registrationId 也就是註冊到iot hub後的設備ID,如果包含“fridge”則註冊到冰箱iot hub,如果包含“conditioner” 則註冊到空調iot hub,
依次修改爲包含fridge和conditioner的字符串後運行程序:
7. 在iot hub中檢查結果:
同時驗證 device twin也由Function 寫好: