我目前正在编写逻辑,以测试从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.");
}
}
}
根本收不到任何消息
1条答案
按热度按时间tcomlyy61#
我按照以下步骤连接物联网集线器,我可以在控制台应用程序中看到发送到设备的消息。