创建 Azure IoT 中心设备

Create Azure IoT Hub devices

是否可以使用 .NET 以编程方式在 Azure IoT 中心上创建新设备?在 microsoft.docs 上的所有教程中,设备都是通过 Azure 门户或 Azure CLI 创建的。

如果有,能否提供一些有趣的链接?提前谢谢你。

creating a device identity 的教程,您可以关注。

相关的API是registryManager.AddDeviceAsync

    RegistryManager manager = RegistryManager.CreateFromConnectionString(connectionString);

    await manager.AddDeviceAsync(new Device(deviceID));

您可以在 GitHub 上的 Azure IoT SDK C# 存储库中找到 C# code sample

此外,您可以使用 IoT Hub REST APIs

  • 以下是Create Or Update Device的实现:

        string connectionString = "<yourIoTHubConnectionString>";
        string deviceId = "<yourDeviceId>";
    
        string iothubName = SharedAccessSignatureBuilder.GetHostNameNamespaceFromConnectionString(connectionString);
        string sasToken = SharedAccessSignatureBuilder.GetSASTokenFromConnectionString(connectionString);
        string requestUri = $"https://{iothubName}.azure-devices.net/devices/{deviceId}?api-version=2018-06-30";
    
        var httpclient = new HttpClient();
        httpclient.DefaultRequestHeaders.Add("Authorization", sasToken);
    
        var hrm = httpclient.PutAsJsonAsync(requestUri, new { deviceId = deviceId }).Result;
        hrm.EnsureSuccessStatusCode();
        string response = hrm.Content.ReadAsStringAsync().Result;            
    

其中 SharedAccessSignatureBuilder 是一个辅助静态 class:

public sealed class SharedAccessSignatureBuilder
{ 
    public static string GetHostNameNamespaceFromConnectionString(string connectionString)
    {
        return GetPartsFromConnectionString(connectionString)["HostName"].Split('.').FirstOrDefault();
    }
    public static string GetSASTokenFromConnectionString(string connectionString, uint hours = 24)
    {
        var parts = GetPartsFromConnectionString(connectionString);
        return GetSASToken(parts["HostName"], parts["SharedAccessKey"], parts["SharedAccessKeyName"], hours);
    }
    public static string GetSASToken(string resourceUri, string key, string keyName = null, uint hours = 24)
    {
        var expiry = GetExpiry(hours);
        string stringToSign = System.Web.HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;
        HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(key));

        var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
        var sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}", HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry);
        if(!string.IsNullOrEmpty(keyName))
            sasToken += String.Format(CultureInfo.InvariantCulture, "&skn={0}", keyName); 

        return sasToken;
    }

    private static Dictionary<string, string> GetPartsFromConnectionString(string connectionString)
    {
        return connectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Split(new[] { '=' }, 2)).ToDictionary(x => x[0].Trim(), x => x[1].Trim());
    }

    // default expiring = 24 hours
    private static string GetExpiry(uint hours = 24)
    {
        TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
        return Convert.ToString((int)sinceEpoch.TotalSeconds + 3600 * hours);
    }
}