重现步骤:
注意:代码在本地环境中运行,但是当我们将其作为自定义模块部署在 azure 中时,它会停止运行。
我已附上日志供参考。
Twin Before Update:
{
"deviceId": null,
"etag": null,
"version": null,
"properties": {
"desired": {
"general": {
"autoUpdate": false
},
"specific": {
"autoUpdate": false
},
"$version": 1
},
"reported": {
"$version": 1
}
}
}
Twin After Update:
{
"deviceId": null,
"etag": null,
"version": null,
"properties": {
"desired": {
"general": {
"autoUpdate": false
},
"specific": {
"autoUpdate": false
},
"$version": 1
},
"reported": {
"$version": 1
}
}
}
下面的代码我已经尝试过
public async Task UpdateReportedProperties(TwinCollection twinCollection)
{
await _moduleClient.UpdateReportedPropertiesAsync(twinCollection);
ModuleTwin = await _moduleClient!.GetTwinAsync();
}
下面的示例代码使用 Azure IoT SDK 与 Azure IoT 中心进行交互。它检索设备孪生,更新报告的属性,然后使用
UpdateReportedPropertiesAsync
和 GetTwinAsync
检索更新的孪生。该代码利用 Microsoft.Azure.Devices.Client
、GetTwinAsync 和 UpdateReported(或)使用 C# 的 REST API。
moduleClient = ModuleClient.CreateFromConnectionString(connectionString);
await moduleClient.OpenAsync();
// Get the twin before update
Twin twinBefore = await moduleClient.GetTwinAsync();
Console.WriteLine("Twin Before Update:");
Console.WriteLine(JsonConvert.SerializeObject(twinBefore, Formatting.Indented));
// Update reported properties
var patch = new
{
properties = new
{
reported = new
{
info = new
{
origin = "Argentina",
version = "14.01"
}
}
}
};
var patchJson = JsonConvert.SerializeObject(patch);
var patchBytes = Encoding.UTF8.GetBytes(patchJson);
var patchTwin = new TwinCollection(patchJson);
await moduleClient.UpdateReportedPropertiesAsync(patchTwin);
// Get the twin after update
Twin twinAfter = await moduleClient.GetTwinAsync();
Console.WriteLine("\nTwin After Update:");
Console.WriteLine(JsonConvert.SerializeObject(twinAfter, Formatting.Indented));
await moduleClient.CloseAsync();
输出:
蔚蓝:
下面的代码是使用 REST API 连接到 Azure IoT 设备 Get Twin 的示例。
string deviceid = "<deviceid>";
string hubName = "<your_iot_hub_name>";
string APIVersion = "2020-05-31-preview";
string URL = $"https://{hubName}.azure-devices.net/twins/{deviceid}?api-version={APIVersion}";
string SAS_TOKEN = "<IOT_SAS_TOKEN>";
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("Device Twin Information:");
Console.WriteLine(resultStr);
Azure IoT 设备更新孪生可以通过此链接使用 REST API 完成。