Skip to content

Commit 70017a9

Browse files
author
Jill Grant
authored
Merge pull request #239589 from KennedyDMSFT/US88322
Hub: Freshness (May)
2 parents 7a0b45b + e17213f commit 70017a9

File tree

7 files changed

+212
-126
lines changed

7 files changed

+212
-126
lines changed

articles/iot-hub/c2d-messaging-dotnet.md

Lines changed: 72 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,19 @@ ms.author: kgremban
88
ms.service: iot-hub
99
ms.devlang: csharp
1010
ms.topic: how-to
11-
ms.date: 10/20/2021
11+
ms.date: 05/30/2023
1212
ms.custom: [amqp, mqtt, 'Role: Cloud Development', 'Role: IoT Device', devx-track-csharp]
1313
---
1414

15-
# Send messages from the cloud to your device with IoT Hub (.NET)
15+
# Send cloud-to-device messages with IoT Hub (.NET)
1616

1717
[!INCLUDE [iot-hub-selector-c2d](../../includes/iot-hub-selector-c2d.md)]
1818

1919
Azure IoT Hub is a fully managed service that helps enable reliable and secure bi-directional communications between millions of devices and a solution back end.
2020

2121
This article shows you how to:
2222

23-
* Send cloud-to-device messages, from your solution backend, to a single device through IoT Hub
23+
* Send cloud-to-device (C2D) messages from your solution backend to a single device through IoT Hub
2424

2525
* Receive cloud-to-device messages on a device
2626

@@ -30,9 +30,9 @@ This article shows you how to:
3030

3131
At the end of this article, you run two .NET console apps.
3232

33-
* **SimulatedDevice**: a modified version of the app created in [Send telemetry from a device to an IoT hub](../iot-develop/quickstart-send-telemetry-iot-hub.md?pivots=programming-language-csharp), which connects to your IoT hub and receives cloud-to-device messages.
33+
* **MessageReceiveSample**: a sample device app included with the [Microsoft Azure IoT SDK for .NET](https://github.com/Azure/azure-iot-sdk-csharp/tree/main/iothub/device/samples), which connects to your IoT hub and receives cloud-to-device messages.
3434

35-
* **SendCloudToDevice**: sends a cloud-to-device message to the device app through IoT Hub and then receives its delivery acknowledgment.
35+
* **SendCloudToDevice**: a service app that sends a cloud-to-device message to the device app through IoT Hub and then receives its delivery acknowledgment.
3636

3737
> [!NOTE]
3838
> IoT Hub has SDK support for many device platforms and languages (C, Java, Python, and JavaScript) through [Azure IoT device SDKs](iot-hub-devguide-sdks.md).
@@ -41,48 +41,58 @@ You can find more information on cloud-to-device messages in [D2C and C2D Messag
4141

4242
## Prerequisites
4343

44-
* Visual Studio
44+
* An Azure subscription. If you don't have an Azure subscription, create a [free account](https://azure.microsoft.com/free/?WT.mc_id=A261C142F) before you begin.
4545

46-
* A complete working version of the [Send telemetry from a device to an IoT hub](../iot-develop/quickstart-send-telemetry-iot-hub.md?pivots=programming-language-java) quickstart or the [Configure message routing with IoT Hub](tutorial-routing.md) article. This cloud-to-device article builds on the quickstart.
46+
* An IoT hub in your Azure subscription. If you don't have a hub yet, you can follow the steps in [Create an IoT hub](iot-hub-create-through-portal.md).
47+
48+
* A device registered in your IoT hub. If you haven't registered a device yet, register one in the [Azure portal](iot-hub-create-through-portal.md#register-a-new-device-in-the-iot-hub).
49+
50+
* This article uses sample code from the [Azure IoT SDK for C#](https://github.com/Azure/azure-iot-sdk-csharp).
51+
52+
* Download or clone the SDK repository from GitHub to your development machine.
53+
* Make sure that .NET Core 3.0.0 or greater is installed on your development machine. Check your version by running `dotnet --version` and [download .NET](https://dotnet.microsoft.com/download) if necessary.
4754

4855
* Make sure that port 8883 is open in your firewall. The device sample in this article uses MQTT protocol, which communicates over port 8883. This port may be blocked in some corporate and educational network environments. For more information and ways to work around this issue, see [Connecting to IoT Hub (MQTT)](../iot/iot-mqtt-connect-to-iot-hub.md#connecting-to-iot-hub).
4956

50-
## Receive messages in the device app
57+
* Visual Studio.
5158

52-
In this section, modify your device app to receive cloud-to-device messages from the IoT hub.
59+
## Get the device connection string
5360

54-
1. In Visual Studio, in the **SimulatedDevice** project, add the following method to the **SimulatedDevice** class.
61+
In this article, you run a sample app that simulates a device, which receives cloud-to-device messages sent through your IoT Hub. The **MessageReceiveSample** sample app included with the [Microsoft Azure IoT SDK for .NET](https://github.com/Azure/azure-iot-sdk-csharp/tree/main/iothub/device/samples) connects to your IoT hub and acts as your simulated device. The sample uses the primary connection string of the registered device on your IoT hub.
5562

56-
```csharp
57-
private static async void ReceiveC2dAsync()
58-
{
59-
Console.WriteLine("\nReceiving cloud to device messages from service");
60-
while (true)
61-
{
62-
Message receivedMessage = await s_deviceClient.ReceiveAsync();
63-
if (receivedMessage == null) continue;
63+
[!INCLUDE [iot-hub-include-find-device-connection-string](../../includes/iot-hub-include-find-device-connection-string.md)]
6464

65-
Console.ForegroundColor = ConsoleColor.Yellow;
66-
Console.WriteLine("Received message: {0}",
67-
Encoding.ASCII.GetString(receivedMessage.GetBytes()));
68-
Console.ResetColor();
65+
## Receive messages in the device app
6966

70-
await s_deviceClient.CompleteAsync(receivedMessage);
71-
}
72-
}
73-
```
67+
In this section, run the **MessageReceiveSample** sample device app to receive C2D messages sent through your IoT hub. Open a new command prompt and navigate to the **azure-iot-sdk-csharp\iothub\device\samples\getting started\MessageReceiveSample** folder, under the folder where you expanded the Azure IoT C# SDK. Run the following commands, replacing the `{Your device connection string}` placeholder value with the device connection string you copied from the registered device in your IoT hub.
7468

75-
1. Add the following method in the **Main** method, right before the `Console.ReadLine()` line:
69+
```cmd/sh
70+
dotnet restore
71+
dotnet run --c "{Your device connection string}"
72+
```
7673

77-
```csharp
78-
ReceiveC2dAsync();
79-
```
74+
The following output is from the sample device app after it successfully starts and connects to your IoT hub:
75+
76+
```cmd/sh
77+
5/22/2023 11:13:18 AM> Press Control+C at any time to quit the sample.
78+
79+
5/22/2023 11:13:18 AM> Device waiting for C2D messages from the hub...
80+
5/22/2023 11:13:18 AM> Use the Azure Portal IoT hub blade or Azure IoT Explorer to send a message to this device.
81+
5/22/2023 11:13:18 AM> Trying to receive C2D messages by polling using the ReceiveAsync() method. Press 'n' to move to the next phase.
82+
```
83+
84+
The sample device app polls for messages by using the [ReceiveAsync](/dotnet/api/microsoft.azure.devices.client.deviceclient.receiveasync) and [CompleteAsync](/dotnet/api/microsoft.azure.devices.client.deviceclient.completeasync) methods. The `ReceiveC2dMessagesPollingAndCompleteAsync` method uses the `ReceiveAsync` method, which asynchronously returns the received message at the time the device receives the message. `ReceiveAsync` returns *null* after a specifiable timeout period. In this example, the default of one minute is used. When the device receives a *null*, it should continue to wait for new messages. This requirement is the reason why the sample app includes the following block of code in the `ReceiveC2dMessagesPollingAndCompleteAsync` method:
8085

81-
The `ReceiveAsync` method asynchronously returns the received message at the time that it's received by the device. It returns *null* after a specifiable timeout period. In this example, the default of one minute is used. When the app receives a *null*, it should continue to wait for new messages. This requirement is the reason for the `if (receivedMessage == null) continue` line.
86+
```csharp
87+
if (receivedMessage == null)
88+
{
89+
continue;
90+
}
91+
```
8292

83-
The call to `CompleteAsync()` notifies IoT Hub that the message has been successfully processed and that the message can be safely removed from the device queue. The device should call this method when its processing successfully completes regardless of the protocol it's using.
93+
The call to the `CompleteAsync` method notifies IoT Hub that the message has been successfully processed and that the message can be safely removed from the device queue. The device should call this method when its processing successfully completes regardless of the protocol it's using.
8494

85-
With AMQP and HTTPS, but not MQTT, the device can also:
95+
With AMQP and HTTPS protocols, but not the [MQTT protocol](../iot/iot-mqtt-connect-to-iot-hub.md), the device can also:
8696

8797
* Abandon a message, which results in IoT Hub retaining the message in the device queue for future consumption.
8898
* Reject a message, which permanently removes the message from the device queue.
@@ -124,7 +134,7 @@ In this section, you create a .NET console app that sends cloud-to-device messag
124134
using Microsoft.Azure.Devices;
125135
```
126136

127-
1. Add the following fields to the **Program** class. Replace the `{iot hub connection string}` placeholder value with the IoT hub connection string you noted previously in [Get the IoT hub connection string](#get-the-iot-hub-connection-string). Replace the `{device id}` placeholder value with the device ID of the device you added in the [Send telemetry from a device to an IoT hub](../iot-develop/quickstart-send-telemetry-iot-hub.md?pivots=programming-language-csharp) quickstart.
137+
1. Add the following fields to the **Program** class. Replace the `{iot hub connection string}` placeholder value with the IoT hub connection string you noted previously in [Get the IoT hub connection string](#get-the-iot-hub-connection-string). Replace the `{device id}` placeholder value with the device ID of the registered device in your IoT hub.
128138

129139
``` csharp
130140
static ServiceClient serviceClient;
@@ -155,19 +165,26 @@ In this section, you create a .NET console app that sends cloud-to-device messag
155165
Console.ReadLine();
156166
```
157167

158-
1. In Solutions Explorer, right-click your solution, and select **Set StartUp Projects**.
159-
160-
1. In **Common Properties** > **Startup Project**, select **Multiple startup projects**, then select the **Start** action for **SimulatedDevice** and **SendCloudToDevice**. Select **OK** to save your changes.
161-
162-
1. Press **F5**. Both applications should start. Select the **SendCloudToDevice** window, and press **Enter**. You should see the message being received by the device app.
163-
164-
![Device app receiving message](./media/iot-hub-csharp-csharp-c2d/sendc2d1.png)
168+
1. Press **F5** to start your sample service app. Select the **SendCloudToDevice** window, and press **Enter**. You should see the message received by the sample device app, as shown in the following output example.
169+
170+
```cmd/sh
171+
5/22/2023 11:13:18 AM> Press Control+C at any time to quit the sample.
172+
173+
5/22/2023 11:13:18 AM> Device waiting for C2D messages from the hub...
174+
5/22/2023 11:13:18 AM> Use the Azure Portal IoT hub blade or Azure IoT Explorer to send a message to this device.
175+
5/22/2023 11:13:18 AM> Trying to receive C2D messages by polling using the ReceiveAsync() method. Press 'n' to move to the next phase.
176+
5/22/2023 11:15:18 AM> Polling using ReceiveAsync() - received message with Id=
177+
5/22/2023 11:15:18 AM> Received message: [Cloud to device message.]
178+
Content type:
179+
180+
5/22/2023 11:15:18 AM> Completed C2D message with Id=.
181+
```
165182

166183
## Receive delivery feedback
167184

168185
It's possible to request delivery (or expiration) acknowledgments from IoT Hub for each cloud-to-device message. This option enables the solution back end to easily inform, retry, or compensation logic. For more information about cloud-to-device feedback, see [D2C and C2D Messaging with IoT Hub](iot-hub-devguide-messaging.md).
169186

170-
In this section, you modify the **SendCloudToDevice** app to request feedback, and receive it from the IoT hub.
187+
In this section, you modify the **SendCloudToDevice** sample service app to request feedback, and receive it from the IoT hub.
171188

172189
1. In Visual Studio, in the **SendCloudToDevice** project, add the following method to the **Program** class.
173190

@@ -196,19 +213,27 @@ In this section, you modify the **SendCloudToDevice** app to request feedback, a
196213

197214
1. Add the following line in the **Main** method, right after `serviceClient = ServiceClient.CreateFromConnectionString(connectionString)`.
198215

199-
``` csharp
216+
```csharp
200217
ReceiveFeedbackAsync();
201218
```
202219

203220
1. To request feedback for the delivery of your cloud-to-device message, you have to specify a property in the **SendCloudToDeviceMessageAsync** method. Add the following line, right after the `var commandMessage = new Message(...);` line.
204221

205-
``` csharp
222+
```csharp
206223
commandMessage.Ack = DeliveryAcknowledgement.Full;
207224
```
208225

209-
1. Run the apps by pressing **F5**. You should see both applications start. Select the **SendCloudToDevice** window, and press **Enter**. You should see the message being received by the device app, and after a few seconds, the feedback message being received by your **SendCloudToDevice** application.
226+
1. Make sure the sample device app is running, and then run the sample service app by pressing **F5**. Select the **SendCloudToDevice** console window and press **Enter**. You should see the message being received by the sample device app, and after a few seconds, the feedback message being received by your **SendCloudToDevice** application. The following output shows the feedback message received by the sample service app:
210227

211-
![Device app receiving message and service app receiving feedback](./media/iot-hub-csharp-csharp-c2d/sendc2d2.png)
228+
```cmd/sh
229+
Send Cloud-to-Device message
230+
231+
232+
Receiving c2d feedback from service
233+
Press any key to send a C2D message.
234+
235+
Received feedback: Success
236+
```
212237

213238
> [!NOTE]
214239
> For simplicity, this article does not implement any retry policy. In production code, you should implement retry policies, such as exponential backoff, as suggested in [Transient fault handling](/azure/architecture/best-practices/transient-faults).
@@ -221,4 +246,4 @@ In this article, you learned how to send and receive cloud-to-device messages.
221246
* To learn more about cloud-to-device messages, see [Send cloud-to-device messages from an IoT hub](iot-hub-devguide-messages-c2d.md).
222247

223248
* To learn more about IoT Hub message formats, see [Create and read IoT Hub messages](iot-hub-devguide-messages-construct.md).
224-
).
249+

articles/iot-hub/c2d-messaging-ios.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ ms.author: kgremban
88
ms.service: iot-hub
99
ms.devland: swift
1010
ms.topic: how-to
11-
ms.date: 04/19/2018
11+
ms.date: 05/30/2023
1212
ms.custom: mqtt
1313
---
1414

@@ -20,7 +20,7 @@ Azure IoT Hub is a fully managed service that helps enable reliable and secure b
2020

2121
This article shows you how to:
2222

23-
* Receive cloud-to-device messages on a device
23+
* Receive cloud-to-device (C2D) messages on a device
2424

2525
At the end of this article, you run the following Swift iOS project:
2626

0 commit comments

Comments
 (0)