Skip to content

Commit 430c320

Browse files
authored
Merge pull request #110925 from JimacoMS3/python-c2d-howto-v2-update
Python c2d howto v2 update
2 parents 0c73240 + e936bb7 commit 430c320

File tree

7 files changed

+68
-84
lines changed

7 files changed

+68
-84
lines changed

articles/iot-hub/iot-hub-python-python-c2d.md

Lines changed: 68 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ ms.service: iot-hub
66
services: iot-hub
77
ms.devlang: python
88
ms.topic: conceptual
9-
ms.date: 07/30/2019
9+
ms.date: 04/09/2020
1010
ms.author: robinsh
1111
---
1212

@@ -24,60 +24,69 @@ This tutorial builds on [Send telemetry from a device to an IoT hub](quickstart-
2424

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

27-
* From your solution back end, request delivery acknowledgment (*feedback*) for messages sent to a device from IoT Hub.
28-
2927
You can find more information on cloud-to-device messages in the [IoT Hub developer guide](iot-hub-devguide-messaging.md).
3028

3129
At the end of this tutorial, you run two Python console apps:
3230

3331
* **SimulatedDevice.py**, a modified version of the app created in [Send telemetry from a device to an IoT hub](quickstart-send-telemetry-python.md), which connects to your IoT hub and receives cloud-to-device messages.
3432

35-
* **SendCloudToDeviceMessage.py**, which sends a cloud-to-device message to the simulated device app through IoT Hub, and then receives its delivery acknowledgment.
33+
* **SendCloudToDeviceMessage.py**, which sends cloud-to-device messages to the simulated device app through IoT Hub.
3634

3735
[!INCLUDE [iot-hub-include-python-sdk-note](../../includes/iot-hub-include-python-sdk-note.md)]
3836

3937
## Prerequisites
4038

41-
[!INCLUDE [iot-hub-include-python-installation-notes](../../includes/iot-hub-include-python-installation-notes.md)]
39+
[!INCLUDE [iot-hub-include-python-v2-installation-notes](../../includes/iot-hub-include-python-v2-installation-notes.md)]
4240

4341
* 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-hub-mqtt-support.md#connecting-to-iot-hub).
4442

4543
## Receive messages in the simulated device app
4644

4745
In this section, you create a Python console app to simulate the device and receive cloud-to-device messages from the IoT hub.
4846

49-
1. Using a text editor, create a **SimulatedDevice.py** file.
47+
1. From a command prompt in your working directory, install the **Azure IoT Hub Device SDK for Python**:
48+
49+
```cmd/sh
50+
pip install azure-iot-device
51+
```
52+
53+
1. Using a text editor, create a file named **SimulatedDevice.py**.
5054
51-
2. Add the following `import` statements and variables at the start of the **SimulatedDevice.py** file:
55+
1. Add the following `import` statements and variables at the start of the **SimulatedDevice.py** file:
5256
53-
```python
57+
```python
5458
import threading
59+
import time
5560
from azure.iot.device import IoTHubDeviceClient
5661
5762
RECEIVED_MESSAGES = 0
5863
```
5964
60-
3. Add the following code to **SimulatedDevice.py** file. Replace the "{deviceConnectionString}" placeholder value with the device connection string for the device you created in the [Send telemetry from a device to an IoT hub](quickstart-send-telemetry-python.md) quickstart:
65+
1. Add the following code to **SimulatedDevice.py** file. Replace the `{deviceConnectionString}` placeholder value with the device connection string for the device you created in the [Send telemetry from a device to an IoT hub](quickstart-send-telemetry-python.md) quickstart:
6166
6267
```python
6368
CONNECTION_STRING = "{deviceConnectionString}"
6469
```
6570
66-
4. Add the following function to print received messages to the console:
71+
1. Add the following function to print received messages to the console:
6772
6873
```python
6974
def message_listener(client):
7075
global RECEIVED_MESSAGES
7176
while True:
7277
message = client.receive_message()
7378
RECEIVED_MESSAGES += 1
74-
print("Message received")
75-
print( " Data: <<{}>>".format(message.data) )
76-
print( " Properties: {}".format(message.custom_properties))
77-
print( " Total calls received: {}".format(RECEIVED_MESSAGES))
79+
print("\nMessage received:")
80+
81+
#print data and both system and application (custom) properties
82+
for property in vars(message).items():
83+
print (" {0}".format(property))
84+
85+
print( "Total calls received: {}".format(RECEIVED_MESSAGES))
86+
print()
7887
```
7988
80-
5. Add the following code to initialize the client and wait to receive the cloud-to-device message:
89+
1. Add the following code to initialize the client and wait to receive the cloud-to-device message:
8190
8291
```python
8392
def iothub_client_sample_run():
@@ -92,90 +101,81 @@ In this section, you create a Python console app to simulate the device and rece
92101
time.sleep(1000)
93102
94103
except KeyboardInterrupt:
95-
print ( "IoTHubDeviceClient sample stopped" )
104+
print ( "IoT Hub C2D Messaging device sample stopped" )
96105
```
97106
98-
6. Add the following main function:
107+
1. Add the following main function:
99108
100109
```python
101110
if __name__ == '__main__':
102-
print ( "Starting the IoT Hub Python sample..." )
103-
print ( "IoTHubDeviceClient waiting for commands, press Ctrl-C to exit" )
111+
print ( "Starting the Python IoT Hub C2D Messaging device sample..." )
112+
print ( "Waiting for C2D messages, press Ctrl-C to exit" )
104113
105114
iothub_client_sample_run()
106115
```
107116
108-
7. Save and close **SimulatedDevice.py** file.
117+
1. Save and close the **SimulatedDevice.py** file.
109118
110119
## Get the IoT hub connection string
111120
112-
In this article you create a backend service to send cloud-to-device messages through the IoT hub you created in [Send telemetry from a device to an IoT hub](quickstart-send-telemetry-python.md). To send cloud-to-device messages, your service needs the **service connect** permission. By default, every IoT Hub is created with a shared access policy named **service** that grants this permission.
121+
In this article, you create a backend service to send cloud-to-device messages through the IoT hub you created in [Send telemetry from a device to an IoT hub](quickstart-send-telemetry-python.md). To send cloud-to-device messages, your service needs the **service connect** permission. By default, every IoT Hub is created with a shared access policy named **service** that grants this permission.
113122
114123
[!INCLUDE [iot-hub-include-find-service-connection-string](../../includes/iot-hub-include-find-service-connection-string.md)]
115124
116125
## Send a cloud-to-device message
117126
118-
In this section, you create a Python console app that sends cloud-to-device messages to the simulated device app. You need the device ID of the device you added in the [Send telemetry from a device to an IoT hub](quickstart-send-telemetry-python.md) quickstart. You also need the the IoT hub connection string you copied previously in [Get the IoT hub connection string](#get-the-iot-hub-connection-string).
127+
In this section, you create a Python console app that sends cloud-to-device messages to the simulated device app. You need the device ID of the device you added in the [Send telemetry from a device to an IoT hub](quickstart-send-telemetry-python.md) quickstart. You also need the IoT hub connection string you copied previously in [Get the IoT hub connection string](#get-the-iot-hub-connection-string).
119128
120-
1. Using a text editor, create a **SendCloudToDeviceMessage.py** file.
129+
1. In your working directory, open a command prompt and install the **Azure IoT Hub Service SDK for Python**.
121130
122-
2. Add the following `import` statements and variables at the start of the **SendCloudToDeviceMessage.py** file:
131+
```cmd/sh
132+
pip install azure-iot-hub
133+
```
134+
135+
1. Using a text editor, create a file named **SendCloudToDeviceMessage.py**.
136+
137+
1. Add the following `import` statements and variables at the start of the **SendCloudToDeviceMessage.py** file:
123138

124139
```python
125140
import random
126141
import sys
127-
import iothub_service_client
128-
from iothub_service_client import IoTHubMessaging, IoTHubMessage, IoTHubError
142+
from azure.iot.hub import IoTHubRegistryManager
129143

130-
OPEN_CONTEXT = 0
131-
FEEDBACK_CONTEXT = 1
132-
MESSAGE_COUNT = 1
144+
MESSAGE_COUNT = 2
133145
AVG_WIND_SPEED = 10.0
134146
MSG_TXT = "{\"service client sent a message\": %.2f}"
135147
```
136148

137-
3. Add the following code to **SendCloudToDeviceMessage.py** file. Replace the "{iot hub connection string}" and "{device id}" placeholder values with the IoT hub connection string and device ID you noted previously:
149+
1. Add the following code to **SendCloudToDeviceMessage.py** file. Replace the `{iot hub connection string}` and `{device id}` placeholder values with the IoT hub connection string and device ID you noted previously:
138150

139151
```python
140152
CONNECTION_STRING = "{IoTHubConnectionString}"
141153
DEVICE_ID = "{deviceId}"
142154
```
143155

144-
4. Add the following function to print feedback messages to the console:
145-
146-
```python
147-
def open_complete_callback(context):
148-
print ( 'open_complete_callback called with context: {0}'.format(context) )
149-
150-
def send_complete_callback(context, messaging_result):
151-
context = 0
152-
print ( 'send_complete_callback called with context : {0}'.format(context) )
153-
print ( 'messagingResult : {0}'.format(messaging_result) )
154-
```
155-
156-
5. Add the following code to send a message to your device and handle the feedback message when the device acknowledges the cloud-to-device message:
156+
1. Add the following code to send messages to your device:
157157

158158
```python
159159
def iothub_messaging_sample_run():
160160
try:
161-
iothub_messaging = IoTHubMessaging(CONNECTION_STRING)
162-
163-
iothub_messaging.open(open_complete_callback, OPEN_CONTEXT)
161+
# Create IoTHubRegistryManager
162+
registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
164163

165164
for i in range(0, MESSAGE_COUNT):
166165
print ( 'Sending message: {0}'.format(i) )
167-
msg_txt_formatted = MSG_TXT % (AVG_WIND_SPEED + (random.random() * 4 + 2))
168-
message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8'))
169-
170-
# optional: assign ids
171-
message.message_id = "message_%d" % i
172-
message.correlation_id = "correlation_%d" % i
173-
# optional: assign properties
174-
prop_map = message.properties()
166+
data = MSG_TXT % (AVG_WIND_SPEED + (random.random() * 4 + 2))
167+
168+
props={}
169+
# optional: assign system properties
170+
props.update(messageId = "message_%d" % i)
171+
props.update(correlationId = "correlation_%d" % i)
172+
props.update(contentType = "application/json")
173+
174+
# optional: assign application properties
175175
prop_text = "PropMsg_%d" % i
176-
prop_map.add("Property", prop_text)
176+
props.update(testProperty = prop_text)
177177

178-
iothub_messaging.send_async(DEVICE_ID, message, send_complete_callback, i)
178+
registry_manager.send_c2d_message(DEVICE_ID, data, properties=props)
179179

180180
try:
181181
# Try Python 2.xx first
@@ -185,63 +185,47 @@ In this section, you create a Python console app that sends cloud-to-device mess
185185
# Use Python 3.xx in the case of exception
186186
input("Press Enter to continue...\n")
187187

188-
iothub_messaging.close()
189-
190-
except IoTHubError as iothub_error:
191-
print ( "Unexpected error {0}" % iothub_error )
188+
except Exception as ex:
189+
print ( "Unexpected error {0}" % ex )
192190
return
193191
except KeyboardInterrupt:
194-
print ( "IoTHubMessaging sample stopped" )
192+
print ( "IoT Hub C2D Messaging service sample stopped" )
195193
```
196194

197-
6. Add the following main function:
195+
1. Add the following main function:
198196

199197
```python
200198
if __name__ == '__main__':
201-
print ( "Starting the IoT Hub Service Client Messaging Python sample..." )
202-
print ( " Connection string = {0}".format(CONNECTION_STRING) )
203-
print ( " Device ID = {0}".format(DEVICE_ID) )
199+
print ( "Starting the Python IoT Hub C2D Messaging service sample..." )
204200

205201
iothub_messaging_sample_run()
206202
```
207203

208-
7. Save and close **SendCloudToDeviceMessage.py** file.
204+
1. Save and close **SendCloudToDeviceMessage.py** file.
209205

210206
## Run the applications
211207

212208
You are now ready to run the applications.
213209

214-
1. Open a command prompt and install the **Azure IoT Hub Device SDK for Python**.
215-
216-
```shell
217-
pip install azure-iothub-device-client
218-
```
219-
220-
2. At the command prompt, run the following command to listen for cloud-to-device messages:
210+
1. At the command prompt in your working directory, run the following command to listen for cloud-to-device messages:
221211

222212
```shell
223213
python SimulatedDevice.py
224214
```
225215

226-
![Run the simulated device app](./media/iot-hub-python-python-c2d/simulated-device.png)
227-
228-
3. Open a new command prompt and install the **Azure IoT Hub Service SDK for Python**.
229-
230-
```shell
231-
pip install azure-iothub-service-client
232-
```
216+
![Run the simulated device app](./media/iot-hub-python-python-c2d/device-1.png)
233217

234-
4. At a command prompt, run the following command to send a cloud-to-device message and wait for the message feedback:
218+
1. Open a new command prompt in your working directory and run the following command to send cloud-to-device messages:
235219

236220
```shell
237221
python SendCloudToDeviceMessage.py
238222
```
239223

240-
![Run the app to send the cloud-to-device command](./media/iot-hub-python-python-c2d/send-command.png)
224+
![Run the app to send the cloud-to-device command](./media/iot-hub-python-python-c2d/service.png)
241225

242-
5. Note the message received by the device.
226+
1. Note the messages received by the device.
243227

244-
![Message received](./media/iot-hub-python-python-c2d/message-received.png)
228+
![Message received](./media/iot-hub-python-python-c2d/device-2.png)
245229

246230
## Next steps
247231

8.74 KB
Loading
43.6 KB
Loading
Binary file not shown.
Binary file not shown.
10 KB
Loading
Binary file not shown.

0 commit comments

Comments
 (0)