如何从设备端(IoT 中心)更新可写属性?

问题描述 投票:0回答:1

我有所需的属性更改回调,如下所示,但此代码不会更新后端(IoT Central)上报告的属性。该代码来自这些示例here

private async Task OnDesiredPropertyChangedAsync(TwinCollection desiredProperties, object userContext)
 {
    JValue targetHeartbeatPeriodJson = desiredProperties["heartbeatPeriod"];
            if (targetHeartbeatPeriodJson != null)
            {
                int targetPeriod = targetHeartbeatPeriodJson.Value<int>();
                timerInterval = targetPeriod;  
                timer.Interval = timerInterval * 60000; // minutes * milliseconds

                TwinCollection reportedProperties = new TwinCollection();
                TwinCollection ackProps = new TwinCollection();

                ackProps["value"] = targetPeriod;
                ackProps["ac"] = 200;
                ackProps["av"] = desiredProperties.Version;
                ackProps["ad"] = "Desired property accepted";
                reportedProperties["heartbeatPeriod"] = ackProps;
                eventLog1.WriteEntry($"Set desired property heartbeatPeriod : {ackProps["value"]}");
                await deviceClient.UpdateReportedPropertiesAsync(reportedProperties);
            }
}

设备属性最终看起来像这样:

{
    "$metadata": {
       
        "heartbeatPeriod": {
            "desiredValue": 15,
            "desiredVersion": 7,
            "lastUpdateTime": "2023-08-22T09:30:45.6558675Z",
            "ackDescription": "reported value",
            "ackCode": 200
        },
        ...
    },
    ...,
    ...,
    "heartbeatPeriod": 1,
    ...
  
}

我是否遗漏了一些属性未更新的内容。

azure-iot-hub
1个回答
0
投票

根据 MSDOC 设备开发人员指南 - IoT 即插即用。


            TwinCollection reportedProperties = new TwinCollection() 
            TwinCollection ackProps = new TwinCollection();
            ackProps["value"] = 24.2;   
            ackProps["ac"] = 300;    
            ackProps["av"] = 1;         
            ackProps["ad"] = "reported default value";   reportedProperties["targetTemperature"] = ackProps;
  var twinPatch = new Twin();
            twinPatch.Properties = new TwinProperties();
            twinPatch.Properties.Reported = reportedProperties;

            await deviceClient.UpdateReportedPropertiesAsync(twinPatch.Properties.Reported);

            Console.WriteLine("Reported properties updated successfully.");

            
            var twin = await deviceClient.GetTwinAsync();
            Console.WriteLine("Reported properties:");
            Console.WriteLine(twin.Properties.Reported.ToJson());
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
        finally
        {
            await deviceClient.CloseAsync();
        }
    }
}

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.