我尝试使用“EventHubReceiver”(Device2Cloud)从设备接收消息。每个设备都应该有自己的单个接收器。
为所有设备(每个分区)创建一个 EventHubReceiver 不是问题:
string iotHubconnectionString = CloudConfigurationManager.GetSetting("Microsoft.IotHub.ConnectionStringPayed");
string iotHubD2cEndpoint = "messages/events";
EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(iotHubconnectionString, iotHubD2cEndpoint);
EventHubRuntimeInformation runtimeInformation = eventHubClient.GetRuntimeInformation();
如果我想接收来自客户端的消息,我会执行以下步骤:
EventHubReceiver eventHubReceiver = eventHubClient2.GetDefaultConsumerGroup().CreateReceiver(partition); //Get the partitions via the runtimeInformation: string[] partitions = runtimeInformation.PartitionIds;
var incommingMessage = eventHubReceiver.ReceiveAsync(); //Wait here for incomming messages
这工作正常,但来自所有“设备”的所有消息都会到达此“EventHubReceiver”。我想要多个接收器,仅从单个设备接收消息。
我尝试更改以下代码行:
string iotHubD2cEndpoint = "messages/events";
至
string iotHubD2cEndpoint = "devices/{deviceID}/messages/events";
但这并不能正常工作。我收到以下错误:
The link address 'devices/secondDevice/messages/events/$management' did not match any of the expected formats. Supported formats: '/$cbs', '/devices/{deviceid}/messages/events', '/devices/{deviceid}/messages/deviceBound', '/messages/deviceBound', '/messages/serviceBound/feedback', '/messages/events/*'.
所以问题是我得到了 'devices/secondDevice/messages/events/$management'
insted of 'devices/secondDevice/messages/events/'
我不知道,是否无法为每个设备创建一个 EventHubReceiver,或者我在代码或思考中遇到了错误。
最佳答案
当设备将遥测数据发送到 IoT 中心时,事件将可供云中“事件中心兼容”的相关 D2C 终结点使用。 它具有“类似事件中心”的行为,因此我们能够使用 EventHubReceiver 获取消息。 但是,事件中心在分区中工作,传入消息可以以循环方式或散列分区键分配给分区。 在 IoT 中心架构中,我不知道它是否使用循环,但它有可能使用散列设备 ID(作为分区键),以便来自设备的所有消息都进入分区。这并不意味着该分区仅包含该设备的消息!每个设备都有一个分区是不可能的:-) 所以......一个分区包含来自不同设备的混合消息(但来自特定设备的消息始终位于同一分区中)。事件中心接收器可以从分区读取,因此它可以从更多设备获取所有消息。您需要根据设备id来区分它们。
关于Azure IoT 中心 - 使用多个 EventHubReceiver 从不同设备接收事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33754583/