我目前正在使用Windows10 IoT核心和Raspberry PI 2在Azure IoT中心上进行研发。我正在跟踪此处的示例,以在房间温度高于25时从IoT中心向设备发送警报。 但是该示例适用于mbed板。
为此,我为Raspberry Pi开发了一个示例UWP应用程序,它将温度数据发送到IoT中心。 在Azure中,我创建了一个流分析作业,它将以IoT中心作为输入并过滤数据(仅温度大于25度),然后将其发送到输出EventHub。 在这里,我创建了一个工作者角色/云服务,该服务将从EventHub读取数据,然后将其发送回IoT中心到我用来从树莓派发送温度信息的同一服务中。
我的疑问是,IoT中心如何区分树莓派发送的数据和工作者角色发送的数据? 怎样才能只接收工作者角色发送的数据?
因为如果我将云读到设备消息,则会收到从树莓派发送的数据。
在这里,我陷入了困境,我尝试使用以下代码从IoT中心读取数据,但是却使我的所有消息都从树莓派pi发送,而工人角色消息的温度仅高于25条消息。
public async void ReceiveDataFromCloud()
{
startingDateTimeUtc = DateTime.UtcNow;
ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(ConnectionString);
builder.TransportType = ppatierno.AzureSBLite.Messaging.TransportType.Amqp;
factory = MessagingFactory.CreateFromConnectionString(ConnectionString);
client = factory.CreateEventHubClient(eventHubEntity);
group = client.GetDefaultConsumerGroup();
receiver = group.CreateReceiver(partitionId.ToString(), startingDateTimeUtc);//startingDateTimeUtc
for (int i = 0; i <= 0; i++)
{
while (true)
{
EventData data = receiver.Receive();
if (data != null)
{
var receiveddata = Encoding.UTF8.GetString(data.GetBytes());
//var messageString = JsonConvert.DeserializeObject<ConferenceRooms>(receiveddata);
Debug.WriteLine("{0} {1} {2}", data.SequenceNumber, data.EnqueuedTimeUtc.ToLocalTime(), Encoding.UTF8.GetString(data.GetBytes()));
}
else
{
break;
}
await Task.Delay(2000);
}
}
receiver.Close();
client.Close();
factory.Close();
}
如何将警报从IoT中心发送回设备,使其仅将由流分析作业筛选的消息发送回设备?
更新:
当我使用上述代码进行接收时,我会从IoT中心获取树莓派发送的所有消息。
但是,当我使用下面的代码接收消息时,我仅收到由工作人员角色发送到IoT中心的消息。
while (true)
{
Message receivedMessage = await deviceClient.ReceiveAsync();
if (receivedMessage == null) continue;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Received message: {0}", Encoding.ASCII.GetString(receivedMessage.GetBytes()));
Console.ResetColor();
await deviceClient.CompleteAsync(receivedMessage);
}
这就是我的要求,我能够实现。
IoT中心提供设备与云之间的双向非对称通信方式。 本文很好地描述了从IoT设备上的云中接收消息的过程。
简而言之,尝试使用以下代码从IoT中心接收云到设备的消息:
while (true)
{
Message receivedMessage = await deviceClient.ReceiveAsync();
if (receivedMessage == null) continue;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Received message: {0}", Encoding.ASCII.GetString(receivedMessage.GetBytes()));
Console.ResetColor();
await deviceClient.CompleteAsync(receivedMessage);
}
在这里, deviceClient
是您创建的Microsoft.Azure.Devices.Client.DeviceClient
的实例,如下所示:
deviceClient = DeviceClient.Create(iotHubUri,
newDeviceAuthenticationWithRegistrySymmetricKey("myFirstDevice", deviceKey));