创建Azure IoT中心设备

时间:2018-07-20 07:32:14

标签: .net azure iot azure-iot-hub

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

如果可以的话,请提供一些有趣的链接吗?预先谢谢你。

2 个答案:

答案 0 :(得分:2)

有一个适用于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

答案 1 :(得分:0)

另外,您可以使用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是辅助静态类:

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);
    }
}