【发布时间】:2019-04-30 12:20:50
【问题描述】:
同步所需属性和报告属性的最合适方法是什么。
目前我认为应该是这样的:
- 在 Azure 门户设置中将“所需的属性更新”事件路由到 IotHub。
- 创建实现 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 有什么关系吗?
【问题讨论】:
-
为什么要更新云端上报的属性?通常报告的属性仅由设备写入。所需的属性由服务端编写。
-
@silent 因为我的硬件无法直接与 azure 通信。
-
@silent 的评论是正确的,请详细说明您的特殊设备端、网关等。注意,设备孪生代表真实设备在云之间的状态(影子)两个面向端点,例如设备和服务。每个状态传输都经过这些分布式侧。
-
@RomanKiss Cloud 通过 Java 应用程序与设备通信。设备只能向此应用程序发送消息。我需要管理设备的状态。
-
@RomanKiss 我的想法是按设备应用程序更改报告的属性(作为 Java 应用程序的一部分实现)。所以 - 我通过实现 IEventProcessor 和路由设置来捕获所需属性的更新,以将所需的属性更新引导到事件中心。当我得到这样的更新时,我会向真实设备发送命令,比如说,更新它的固件。当真实设备更新其固件时,它会向 java 应用程序发送回电报,然后应用程序更新报告的属性 - 我可以使用 DeviceClient 对象。
标签: c# azure azure-iot-hub