How can I receive messages to a C# Console app from an Azure IoT Hub device, using the Azure IoT Hub SDK

huangapple go评论71阅读模式
英文:

How can I receive messages to a C# Console app from an Azure IoT Hub device, using the Azure IoT Hub SDK

问题

目前我正在编写逻辑来测试从Azure IoT Hub设备接收数据到我的控制台应用程序。我已将IoT Hub连接到一个容器,以便我可以看到消息进入容器,但在控制台应用程序中看不到。我已经检查了控制台应用程序是否成功连接到Hub,以及是否可以发送虚拟消息到设备,但它们无法被接收。不能接收任何消息。

英文:

I am currently writing logic to test receiving data from an Azure IoT hub device into my console app. I've got the IoT Hub connected to a container so I can see messages entering the container, but not in the console app. I've checked that the console app is successfully connected to the hub, and that dummy messages can be sent to the device, but they can't be received

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.");
        }
    }
}
        

Can't receive any messages at all

答案1

得分: 1

我按照以下步骤连接到了IoT Hub,并可以在控制台应用程序中看到发送到设备的消息。

  • 创建一个IoT Hub

How can I receive messages to a C# Console app from an Azure IoT Hub device, using the Azure IoT Hub SDK

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

How can I receive messages to a C# Console app from an Azure IoT Hub device, using the Azure IoT Hub SDK

  • 通过提供设备名称并单击保存来创建设备。

How can I receive messages to a C# Console app from an Azure IoT Hub device, using the Azure IoT Hub SDK

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

namespace IoTHubReceiver
{
    class Program
    {
        private static DeviceClient _deviceClient;
        private static string _connectionString = "[您的设备连接字符串](https://i.imgur.com/KFP47V8.png)";

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

            try
            {
                _deviceClient.OpenAsync().Wait();
                Console.WriteLine("成功连接到Azure IoT Hub。");
                ReceiveMessages();
            }
            catch (Exception ex)
            {
                Console.WriteLine("无法连接到Azure IoT Hub。");
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("按任意键退出...");
            Console.ReadKey();
        }

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

How can I receive messages to a C# Console app from an Azure IoT Hub device, using the Azure IoT Hub SDK

How can I receive messages to a C# Console app from an Azure IoT Hub device, using the Azure IoT Hub SDK

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

How can I receive messages to a C# Console app from an Azure IoT Hub device, using the Azure IoT Hub SDK

英文:

I Followed the below steps to connect the IoT Hub and I can see messages sent to device in console application.

  • Create a IoT Hub

How can I receive messages to a C# Console app from an Azure IoT Hub device, using the Azure IoT Hub SDK

  • Go to the IoT hub you created. Search for Devices and add device.

How can I receive messages to a C# Console app from an Azure IoT Hub device, using the Azure IoT Hub SDK

  • Create Device by giving the device name and click on Save.

How can I receive messages to a C# Console app from an Azure IoT Hub device, using the Azure IoT Hub SDK

  • In Visual Studio select Console application and enter this code

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);
            }
        }
    }
}    

  • Run the console application and check device is connected or not.

How can I receive messages to a C# Console app from an Azure IoT Hub device, using the Azure IoT Hub SDK

  • Go to IoT device you created click on Message to Device .Type you message and click on send .

How can I receive messages to a C# Console app from an Azure IoT Hub device, using the Azure IoT Hub SDK

  • Check the Run window of Console application to check the message.

How can I receive messages to a C# Console app from an Azure IoT Hub device, using the Azure IoT Hub SDK

huangapple
  • 本文由 发表于 2023年2月8日 17:56:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75384043.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定