如何使用 IOT Hub 将消息从云端发送到设备?
How to send messages from Cloud to Device with IOT Hub?
我已尝试使用下面 link 中提到的步骤通过 IOT Hub 接收云到设备的消息:
https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-c2d
我附上了我正在使用的代码和我得到的结果。
在模拟设备应用程序中,我调用此方法“ReceiveMessageAsync()”。
我已经更新了我得到的输出的屏幕截图。
输入“Enter”后,我没有得到任何输出。
解码代码后,我可以看到在 ReceiveMessageAsync() 方法中,我得到 receivedMessage == null
.
请帮助我处理此代码并建议我应该进行哪些更改以使其完美运行。
=======================================
public async void ReceiveMessageAsync()
{
try
{
Message receivedMessage = await _deviceClient?.ReceiveAsync();
if(receivedMessage == null)
{
ReceivedMessage = null;
return;
}
ReceivedMessage = Encoding.ASCII.GetString(receivedMessage.GetBytes());
if(double.TryParse(ReceivedMessage, out var requestedNoise))
{
ReceivedNoiseSetting = requestedNoise;
}
else
{
ReceivedNoiseSetting = null;
}
await _DeviceClient?.CompleteAsync(receivedMessage);
}
catch (NullReferenceException ex)
{
System.Diagnostics.Debug.WriteLine("The DeviceClient is null.");
}
}
============================================= =====
using System;
using Ststem.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Devices;
using System.Linq;
namespace SendCloudToDevice
{
internal class Program
{
static ServiceClient serviceClient;
static string connectionString = "<connectionString>";
static string targetDevice = "<deviceID>";
public static async Task Main(String[] args)
{
console.WriteLine("Send Cloud to device Message");
serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
ReceiveFeedbackAsync();
Console.WriteLine("Press any key to send C2D mesage.");
Console.ReadLine();
sendCloudToDeviceMessageAsync().Wait();
Console.ReadLine();
}
private async static Task SendCloudToDeviceMessageAsync()
{
var commandMessage = new Message(Encoding.ASCII.GetBytes("Cloud to device message."));
commandMessage.Ack = DeliveryAcknowledgement.Full;
await serviceClient.sendAsync(targetDevice,commandMessage);
}
private async static void ReceiveFeedbackAsync()
{
var feedbackReceiver = serviceClient.GetFeedbackReceiver();
Console.WriteLine("\n Receiving c2d feedback from service");
while (true)
{
var feedbackBatch = await feedbackReceiver.ReceiveAsync();
if(feedbackBatch == null) continue;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Received feedback: {0}",string.Join(", ", feedbackBatch.Recorfds.Select(f => f.StatusCode)));
Console.ResetColor();
await feedbackReceiver.CompleteAsync(feedbackBatch);
}
}
}
}
[1]: https://i.stack.imgur.com/sS8N0.jpg![enter image description here](https://i.stack.imgur.com/THylN.jpg)
如果您只想向设备发送消息并从设备接收消息,请尝试以下代码:
using System;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices;
using System.Linq;
using System.Text;
namespace SendCloudToDevice
{
internal class Program
{
public static void Main(String[] args)
{
var deviceConnStr = "";
var serviceClientStr = "";
//sned a new message from could to device
var serviceClient = ServiceClient.CreateFromConnectionString(serviceClientStr);
var messageContent = "Hello! This is a message from Cloud!";
var commandMessage = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(messageContent));
serviceClient.SendAsync("<deviceID here>", commandMessage).GetAwaiter().GetResult();
Console.WriteLine("sent message to device,content : "+ messageContent);
//device receive messages from cloud
var deviceClient = DeviceClient.CreateFromConnectionString(deviceConnStr);
Console.WriteLine("\nReceiving cloud to device messages from service");
while (true)
{
var receivedMessage = deviceClient.ReceiveAsync().GetAwaiter().GetResult();
if (receivedMessage == null) continue;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Received message: {0}",
Encoding.ASCII.GetString(receivedMessage.GetBytes()));
Console.ResetColor();
deviceClient.CompleteAsync(receivedMessage).GetAwaiter().GetResult();
}
}
}
}
结果:
您还可以从 Portal 发送消息:
我已尝试使用下面 link 中提到的步骤通过 IOT Hub 接收云到设备的消息: https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-c2d
我附上了我正在使用的代码和我得到的结果。
在模拟设备应用程序中,我调用此方法“ReceiveMessageAsync()”。
我已经更新了我得到的输出的屏幕截图。
输入“Enter”后,我没有得到任何输出。
解码代码后,我可以看到在 ReceiveMessageAsync() 方法中,我得到 receivedMessage == null
.
请帮助我处理此代码并建议我应该进行哪些更改以使其完美运行。
=======================================
public async void ReceiveMessageAsync()
{
try
{
Message receivedMessage = await _deviceClient?.ReceiveAsync();
if(receivedMessage == null)
{
ReceivedMessage = null;
return;
}
ReceivedMessage = Encoding.ASCII.GetString(receivedMessage.GetBytes());
if(double.TryParse(ReceivedMessage, out var requestedNoise))
{
ReceivedNoiseSetting = requestedNoise;
}
else
{
ReceivedNoiseSetting = null;
}
await _DeviceClient?.CompleteAsync(receivedMessage);
}
catch (NullReferenceException ex)
{
System.Diagnostics.Debug.WriteLine("The DeviceClient is null.");
}
}
============================================= =====
using System;
using Ststem.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Devices;
using System.Linq;
namespace SendCloudToDevice
{
internal class Program
{
static ServiceClient serviceClient;
static string connectionString = "<connectionString>";
static string targetDevice = "<deviceID>";
public static async Task Main(String[] args)
{
console.WriteLine("Send Cloud to device Message");
serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
ReceiveFeedbackAsync();
Console.WriteLine("Press any key to send C2D mesage.");
Console.ReadLine();
sendCloudToDeviceMessageAsync().Wait();
Console.ReadLine();
}
private async static Task SendCloudToDeviceMessageAsync()
{
var commandMessage = new Message(Encoding.ASCII.GetBytes("Cloud to device message."));
commandMessage.Ack = DeliveryAcknowledgement.Full;
await serviceClient.sendAsync(targetDevice,commandMessage);
}
private async static void ReceiveFeedbackAsync()
{
var feedbackReceiver = serviceClient.GetFeedbackReceiver();
Console.WriteLine("\n Receiving c2d feedback from service");
while (true)
{
var feedbackBatch = await feedbackReceiver.ReceiveAsync();
if(feedbackBatch == null) continue;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Received feedback: {0}",string.Join(", ", feedbackBatch.Recorfds.Select(f => f.StatusCode)));
Console.ResetColor();
await feedbackReceiver.CompleteAsync(feedbackBatch);
}
}
}
}
[1]: https://i.stack.imgur.com/sS8N0.jpg![enter image description here](https://i.stack.imgur.com/THylN.jpg)
如果您只想向设备发送消息并从设备接收消息,请尝试以下代码:
using System;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices;
using System.Linq;
using System.Text;
namespace SendCloudToDevice
{
internal class Program
{
public static void Main(String[] args)
{
var deviceConnStr = "";
var serviceClientStr = "";
//sned a new message from could to device
var serviceClient = ServiceClient.CreateFromConnectionString(serviceClientStr);
var messageContent = "Hello! This is a message from Cloud!";
var commandMessage = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(messageContent));
serviceClient.SendAsync("<deviceID here>", commandMessage).GetAwaiter().GetResult();
Console.WriteLine("sent message to device,content : "+ messageContent);
//device receive messages from cloud
var deviceClient = DeviceClient.CreateFromConnectionString(deviceConnStr);
Console.WriteLine("\nReceiving cloud to device messages from service");
while (true)
{
var receivedMessage = deviceClient.ReceiveAsync().GetAwaiter().GetResult();
if (receivedMessage == null) continue;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Received message: {0}",
Encoding.ASCII.GetString(receivedMessage.GetBytes()));
Console.ResetColor();
deviceClient.CompleteAsync(receivedMessage).GetAwaiter().GetResult();
}
}
}
}
结果:
您还可以从 Portal 发送消息: