IOT集线器无法接收或发送消息

时间:2017-04-09 18:47:59

标签: azure raspberry-pi windows-10-iot-core azure-iot-hub

我试图为我的覆盆子pi制作一个简单的应用程序,它会向IOThub发送一条消息,然后尝试接收响应但是没有任何事情发生。

我从设备控制器复制了连接字符串。 Ofcource我为这个问题隐藏了它。

我看到它打印出消息已成功发送到iothub但是当我检查iothub时,我看到0收到消息。

我使用iothub的免费等级这是一个限制吗?

    public sealed partial class MainPage : Page
{
    private const string DeviceConnectionString = "Hidden";

    private readonly DeviceClient _deviceClient;

    public MainPage()
    {
        this.InitializeComponent();
        _deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString, TransportType.Amqp); //Already tried using different transport types but no succes.
    }

    public async Task SendEvent()
    {
        Debug.WriteLine("\t{0}> Sending message", DateTime.Now.ToLocalTime());
        var commandMessage = new Message(Encoding.ASCII.GetBytes("Cloud to device message."));
        await _deviceClient.SendEventAsync(commandMessage);
        Debug.WriteLine("Succesfully sended message to IotHub");
    }

    public async Task ReceiveCommands()
    {
        Debug.WriteLine("\nDevice waiting for commands from IoTHub...\n");

        while (true)
        {
            var receivedMessage = await _deviceClient.ReceiveAsync();

            if (receivedMessage != null)
            {
                var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                Debug.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);

                var propCount = 0;
                foreach (var prop in receivedMessage.Properties)
                {
                    Debug.WriteLine("\t\tProperty[{0}> Key={1} : Value={2}", propCount++, prop.Key, prop.Value);
                }

                await _deviceClient.CompleteAsync(receivedMessage);
                Debug.WriteLine("Finishing recieving message");
            }
            await Task.Delay(TimeSpan.FromSeconds(1));
        }
    }

    private async void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
    {
        Debug.WriteLine("Sending event");
        await SendEvent();
        await ReceiveCommands();
        Debug.WriteLine("Received commands");
    }
}

1 个答案:

答案 0 :(得分:3)

这与iothub的免费等级无关。没有这样的限制。

您无法使用ReceiveCommands()中使用的Device-To-Cloud(D2C) messages来接收DeviceClient。它是按设计的。您似乎对Azure IoT Hub消息类型和SDK有一些误解。

有两种消息类型:Device-To-Cloud(D2C) messageCloud-To-Device(C2D) message

还有两种SDK:device SDKservice SDK

Device SDK用于连接到Azure IoT Hub并将其发送到Azure IoT Hub。 虽然service SDK用于管理C2D messages并将其发送到设备。

因此,如果您在Device Explorer中向设备发送C2D消息,您将在ReceiveCommands方法中收到这些消息。

如果要接收D2C消息,可以使用与Event Hub兼容的端点(消息/事件)。您可以参考a console sample。但由于service bus not supported in UWP,这在UWP中无法完成。