How to do it...

In this section we will send a cloud-to-device message. Upon receiving it, the IoT device will perform an action:

  1. Send a cloud-to-device message from a cloud solution to an IoT device:
ServiceClient serviceClient;
serviceClient = ServiceClient.CreateFromConnectionString(abc.GetConnectionString());

abc.SendCloudToDeviceMessageAsync(deviceId, serviceClient);
  1. Prepare and send messages:
var commandMessage = new Message(Encoding.ASCII.GetBytes("Close=100"));
await serviceClient.SendAsync(deviceId, commandMessage);
  1. The IoT device will reply by sending an acknowledgement message:
 while (true)
{
Message receivedMessage = await deviceClient.ReceiveAsync();
if (receivedMessage == null) continue;

var cmdMessage = Encoding.ASCII.GetString(receivedMessage.GetBytes());

// take acttion based on cmdMessage value
// ..... Some code here .....

//Send Ack to IoT Hub
await deviceClient.CompleteAsync(receivedMessage);
}
  1. The IoT solution will process the feedback acknowledgement:
var feedbackReceiver = serviceClient.GetFeedbackReceiver();

while (true)
{
var feedbackBatch = await feedbackReceiver.ReceiveAsync();
if (feedbackBatch == null) continue;

// take action & Udate database for action taken
foreach (var feedback in feedbackBatch.Records)
{
if (feedback.StatusCode != FeedbackStatusCode.Success)
{
// Handle compensation here
}
}

await feedbackReceiver.CompleteAsync(feedbackBatch);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.204.208