Device Twin:如何在C#中读取/写入属性

我已经在IoT中注册了设备,并且客户端应用程序(设备)可以读取/更新报告的孪生属性。

这些属性是令人垂涎的:

"EbbyVersion": {
"Major": 2,"Minor": 1,"Revision": 0
},"Telemetry": {
"CachingInterval": 60,"SendingInterval": 480,"UploadTimeout": 10
},"Power": {
"MaximumAvailable": 3500,"Thresholds": {
    "Low": 2500,"Medium": 3000,"High": 3500
}
},"Lighting": {
"R": 32,"G": 64,"B": 128,"W": 255
},

我编写以下代码以连接到IoT Device Twin:

var registryManager = RegistryManager.CreateFromConnectionString(AppSettings.KeyIoT);
var twin = await registryManager.GetTwinAsync(dto.DeviceIdorId);

现在,我必须从后端应用程序(在C#中)读取/更新所需的twin属性。需要帮助。

zhanghuiqingIT 回答:Device Twin:如何在C#中读取/写入属性

希望TwinCollection类会有所帮助。请参阅此讨论C# How to update desired twin property of an Azure IoT Hub device

,

您可能已经知道了,但我想将其写下来是值得的。

我们至少有两种方法可以做到这一点:

  1. 使用Azure IoT Service SDK:

  2. 使用Azure IoT API:

1-使用Azure IoT SDK阅读双胞胎

    using Microsoft.Azure.Devices;
    ...

    static RegistryManager registryManager;
    static string connectionString = "<Enter the IoT Hub Connection String>";
    ...

    string deviceid = "<deviceid>";
    registryManager = RegistryManager.CreateFromConnectionString(connectionString);  
    var twin = await registryManager.GetTwinAsync(deviceid);
    Console.WriteLine(twin.ToJson())

注意:您也可以在Twin Class的实例上检索双胞胎。您只需要添加

    using Microsoft.Azure.Devices.Shared;
    ...
    Twin twin = await registryManager.GetTwinAsync(deviceid);

1-使用Azure IoT API阅读Twin

就像使用HTTP客户端(例如Postman)一样,您需要发出 GET 请求以

https://YOUR_IOT_HUB_NAME.azure-devices.net/twins/{deviceid}?api-version=2020-05-31-preview

在撰写本文时,Microsoft Official Docs指出,服务IoT中心的最新API版本为:“ 2020-05-31-preview”,因此随时间而变化。

您还需要提供 Authorization 标头和有效的SAS令牌值。

使用HttpWebRequest的所有示例如下所示:

string deviceid = "<deviceid>";
string URL = $"https://YOUR_IOT_HUB_NAME.azure-devices.net/twins/{deviceid}?api-version=2020-05-31-preview"
string SAS_TOKEN = "<IOT_SAS_TOKEN>";
...

try
{ 
    string resultStr = string.Empty;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.AutomaticDecompression = DecompressionMethods.GZip;
    request.Headers.Add("Authorization",SAS_TOKEN);
    request.ContentType = "application/json";
 
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using (Stream stream = response.GetResponseStream())
    using (StreamReader reader = new StreamReader(stream))
    {
        resultStr = reader.ReadToEnd();
    }

    Console.WriteLine(resultStr);
}
catch (Exception e)
{
    throw e;
}

2-使用Azure IoT SDK更新双胞胎

    using Microsoft.Azure.Devices;
    ...

    static RegistryManager registryManager;
    static string connectionString = "<Enter the IoT Hub Connection String>";
    ...
    
    registryManager = RegistryManager.CreateFromConnectionString(connectionString);  

    string deviceid = "<deviceid>";
    string etag = "<twinETag>"; // You could also get this value from the twin if you previously read it,by doing twin.ETag

    // This is the piece of the twin tags we want to update
    var patch = @"{
        tags: {
            info: {  
                origin: 'Argentina',version: '14.01'  
            }  
        }  
    }";  

    await registryManager.UpdateTwinAsync(deviceid,patch,twinETag);  

2-使用Azure IoT API更新双胞胎

与步骤“ 1-使用Azure IoT API读取Twin ”完全相同,您需要使用相同的URL

https://YOUR_IOT_HUB_NAME.azure-devices.net/twins/{deviceid}?api-version=2020-05-31-preview

并向 Authorization 标头添加IoT SAS令牌值,您现在需要使用 PATCH 方法。这意味着,在正文中,您需要发送要更新的作品。

重要:请勿无意使用 POST 方法,因为这将用您发送的邮件代替整个双胞胎。仅当您发送整个新双胞胎作为正文时,才应使用POST方法。我们现在不这样做。

同样,使用HttpWebRequest的所有示例如下:

string deviceid = "<deviceid>";
string URL = $"https://YOUR_IOT_HUB_NAME.azure-devices.net/twins/{deviceid}?api-version=2020-05-31-preview"
string SAS_TOKEN = "<IOT_SAS_TOKEN>";

...

var patch = @"{
    tags: {
        info: {  
            origin: 'Argentina',version: '14.01'  
        }  
    }  
}";  

try
    {
        
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GetDeviceTwinURL(deviceid));
        req.Method = "PATCH";
        req.Headers.Add("Authorization",SAS_TOKEN);
        req.ContentType = "application/json";
        Stream stream = req.GetRequestStream();
        byte[] buffer = Encoding.UTF8.GetBytes(patch);
        stream.Write(buffer,buffer.Length);
        HttpWebResponse res = (HttpWebResponse)req.GetResponse();
    }
    catch (Exception e)
    {
        throw e;
    }

请注意,每当我使用'string URL = $“ ... {deviceid} ...”'时,我都会用先前使用字符串插值法定义的deviceid替换deviceid变量。

您可以找到另一个出色的示例here

,

一种方法是:

  1. 将所需或报告的json反序列化为一个类
  2. 根据需要修改对象
  3. 序列化回json(确保包含null)
  4. 使用新的json更新twin。
本文链接:https://www.f2er.com/3046492.html

大家都在问