如何使用Azure IoT Hub SDK从Azure IoT Hub设备接收发往C#控制台应用的消息

e37o9pze  于 2023-02-09  发布在  C#
关注(0)|答案(1)|浏览(228)

我目前正在编写逻辑,以测试从Azure IoT集线器设备接收数据到我的控制台应用程序的情况。我已将IoT集线器连接到容器,因此我可以看到进入容器的消息,但无法看到进入控制台应用程序的消息。我已检查控制台应用程序是否已成功连接到集线器,以及是否可以将虚拟消息发送到设备,但无法接收这些消息

using System;
using System.IO;
using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Text;
using System.Runtime.CompilerServices;

namespace IoTHubTesting2
{
    class Program
    {
        private static DeviceClient _deviceClient;
        private static string _connectionString = "ConnectionString";
        private static string deviceID = ("TestDevice1");

        static void Main(string[] args)
        {
            Console.WriteLine("Connecting to Azure IoT Hub...");
            _deviceClient = DeviceClient.CreateFromConnectionString(_connectionString, TransportType.Amqp);

            try
            {
                _deviceClient.OpenAsync().Wait();
                Console.WriteLine("Successfully connected to Azure IoT Hub.");
                SendSimulatedMessage();
                ReceiveMessages();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to connect to Azure IoT Hub.");
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }

        private static async void ReceiveMessages()
        {
            Console.WriteLine("Listening for messages from Azure IoT Hub...");
            while (true)
            {
                var message = await _deviceClient.ReceiveAsync();
                if (message == null) continue;
                var messageString = Encoding.UTF8.GetString(message.GetBytes());
                Console.WriteLine("Received message: {0}", messageString);

                // Parse message as JSON
                var messageData = JsonConvert.DeserializeObject<dynamic>(messageString);
                Console.WriteLine("Message data: {0}", messageData);

                await _deviceClient.CompleteAsync(message);
            }
        }

        private static async void SendSimulatedMessage()
        {
            Console.WriteLine("Sending a simulated message to Azure IoT Hub...");
            var message = new Message(System.Text.Encoding.UTF8.GetBytes("Hello from the console app!"));
            await _deviceClient.SendEventAsync(message);
            Console.WriteLine("Simulated message sent.");
        }
    }
}

根本收不到任何消息

tcomlyy6

tcomlyy61#

我按照以下步骤连接物联网集线器,我可以在控制台应用程序中看到发送到设备的消息。

  • 创建物联网中心

  • 转到您创建的IoT集线器。搜索设备并添加设备。

  • 通过提供设备名称创建设备,然后单击保存。

  • 在Visual Studio中,选择控制台应用程序并输入以下代码
using System;
using Microsoft.Azure.Devices.Client;
using System.Text;

namespace IoTHubReceiver
{
    class Program
    {
        private static DeviceClient _deviceClient;
        private static string _connectionString = "[Your Device connection String](https://i.imgur.com/KFP47V8.png)  ";

        static void Main(string[] args)
        {
            Console.WriteLine("Connecting to Azure IoT Hub...");
            _deviceClient = DeviceClient.CreateFromConnectionString(_connectionString, TransportType.Amqp);

            try
            {
                _deviceClient.OpenAsync().Wait();
                Console.WriteLine("Successfully connected to Azure IoT Hub.");
                ReceiveMessages();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to connect to Azure IoT Hub.");
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }

        private static async void ReceiveMessages()
        {
            Console.WriteLine("Listening for messages from Azure IoT Hub...");
            while (true)
            {
                var message = await _deviceClient.ReceiveAsync();
                if (message == null) continue;
                var messageString = Encoding.UTF8.GetString(message.GetBytes());
                Console.WriteLine("Received message: {0}", messageString);
                await _deviceClient.CompleteAsync(message);
            }
        }
    }
}
  • 运行控制台应用程序并检查设备是否连接。

  • 转到您创建的物联网设备,点击Message to Device。键入您的消息,然后点击发送。

  • 检查控制台应用程序的“运行”窗口以检查消息。

相关问题