In this section we will send a cloud-to-device message. Upon receiving it, the IoT device will perform an action:
- 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);
- Prepare and send messages:
var commandMessage = new Message(Encoding.ASCII.GetBytes("Close=100"));
await serviceClient.SendAsync(deviceId, commandMessage);
- 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);
}
- 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);
}