Azure Device Twin所需和报告的属性同步

时间:2019-04-30 12:20:51

标签: c# azure azure-iot-hub

最理想的同步所需属性和报告属性的方法是什么。

目前我的想法是:

  1. 在Azure门户设置中,将“所需属性更新”事件路由到IotHub。
  2. 创建实现IEventProcessor的类:

内部类LoggingEventProcessor:IEventProcessor {     公共任务OpenAsync(PartitionContext上下文)     {         Console.WriteLine($“ LoggingEventProcessor打开,分区:{context.PartitionId}”);         返回Task.CompletedTask;     }

public async Task CloseAsync(PartitionContext context, CloseReason reason)
{
    Console.WriteLine($"LoggingEventProcessor closing, partition: {context.PartitionId}, reason: {reason}");
    if (reason == CloseReason.Shutdown)
    {
        await context.CheckpointAsync();
    }
}

public Task ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
{
    foreach (var msg in messages)
    {
        string messageSource = (string)msg.SystemProperties["iothub-message-source"];
        var deviceId = msg.SystemProperties["iothub-connection-device-id"];
        var payload = Encoding.ASCII.GetString(msg.Body.Array,
            msg.Body.Offset,
            msg.Body.Count);

        switch (messageSource)
        {
            case "deviceLifecycleEvents":
                Twin tw = JsonConvert.DeserializeObject<Twin>(payload);
                Console.WriteLine($"Events received on partition: {context.PartitionId}, deviceId: {deviceId}, payload: {payload}");
                break;
            case "twinChangeEvents":
                DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionStringBuilder.ToString(), Microsoft.Azure.Devices.Client.TransportType.Amqp);
                var props = new TwinCollection();
                props["temperature"] = payload;
                return deviceClient.UpdateReportedPropertiesAsync(props);
                break;
            default:
                Console.WriteLine($"Message source '{messageSource}' not supported");
                break;
        }
    }
    return context.CheckpointAsync();
}

public Task ProcessErrorAsync(PartitionContext context, Exception error)
{
    Console.WriteLine($"LoggingEventProcessor closing, partition: {context.PartitionId}, reason: {error.Message}");
    return Task.CompletedTask;
}

}

有更好的主意吗?与Microsoft.Azure.Devices.JobClient有关吗?

1 个答案:

答案 0 :(得分:0)

最好从IoT中心或IoT事件中心使用事件触发功能。

然后在进行Evenhub操作时检查所需和报告的值。

希望这能回答您的问题。