Search code examples
c#azurecloudiotazure-iot-hub

How to send messages from Cloud to Device with IOT Hub?


I have tried to receive cloud to device message through IOT Hub using the steps mentioned in the link below: https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-c2d

I have attached the code that I am using and the result I am getting.

In the simulated device app, I am calling this method "ReceiveMessageAsync()".

I have updated the screenshot of the output that I am getting. After entering the "Enter", I am not getting any output. After decoding the code, I could see that in the ReceiveMessageAsync() method, I am getting receivedMessage == null.

Please help me with this code and suggest the changes that I should make to make it work perfectly.

=======================================

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.sstatic.net/sS8N0.jpg![enter image description here](https://i.sstatic.net/THylN.jpg)enter image description here


Solution

  • If you just want to send messages to a device and get messages from a device, try the code below:

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

    Result: enter image description here

    You can also send messages from Portal: enter image description here

    enter image description here