物联网集线器不接收或发送消息

IOT hub not recieving or sending messages

我正在尝试为我的 raspberry pi 制作一个简单的应用程序,它将向 IOThub 发送一条消息,然后尝试接收响应,但没有任何反应。

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

我看到它打印出消息已成功发送到 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");
    }
}

与iothub的free tier无关。没有这个限制。

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

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

还有两种SDK:device SDK and service SDK

Device SDK 用于连接到 Azure IoT 中心并向其发送 D2C 消息。 而服务 SDK 用于管理和发送 C2D messages 到设备。

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

如果您想接收 D2C 消息,您可以使用与事件中心兼容的端点 (messages/events)。这里是 a console sample you can reference. But this is can't be done in UWP due to service bus not supported in UWP.