Skip to content

Commit 4b29bd4

Browse files
committed
Update python c2d messaging howto for V2 SDK
1 parent b1cc8b7 commit 4b29bd4

File tree

1 file changed

+59
-76
lines changed

1 file changed

+59
-76
lines changed

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

Lines changed: 59 additions & 76 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,8 +24,6 @@ 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:
@@ -38,17 +36,23 @@ At the end of this tutorial, you run two Python console apps:
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
5357
```python
5458
import threading
@@ -57,27 +61,31 @@ In this section, you create a Python console app to simulate the device and rece
5761
RECEIVED_MESSAGES = 0
5862
```
5963
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:
64+
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:
6165
6266
```python
6367
CONNECTION_STRING = "{deviceConnectionString}"
6468
```
6569
66-
4. Add the following function to print received messages to the console:
70+
1. Add the following function to print received messages to the console:
6771
6872
```python
6973
def message_listener(client):
7074
global RECEIVED_MESSAGES
7175
while True:
7276
message = client.receive_message()
7377
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))
78+
print("\nMessage received:")
79+
80+
#print data and both system and application (custom) properties
81+
for property in vars(message).items():
82+
print (" {0}".format(property))
83+
84+
print( "Total calls received: {}".format(RECEIVED_MESSAGES))
85+
print()
7886
```
7987
80-
5. Add the following code to initialize the client and wait to receive the cloud-to-device message:
88+
1. Add the following code to initialize the client and wait to receive the cloud-to-device message:
8189
8290
```python
8391
def iothub_client_sample_run():
@@ -92,20 +100,20 @@ In this section, you create a Python console app to simulate the device and rece
92100
time.sleep(1000)
93101
94102
except KeyboardInterrupt:
95-
print ( "IoTHubDeviceClient sample stopped" )
103+
print ( "IoT Hub C2d Messaging device sample stopped" )
96104
```
97105
98-
6. Add the following main function:
106+
1. Add the following main function:
99107
100108
```python
101109
if __name__ == '__main__':
102-
print ( "Starting the IoT Hub Python sample..." )
110+
print ( "Starting the Python IoT Hub C2D Messaging device sample..." )
103111
print ( "IoTHubDeviceClient waiting for commands, press Ctrl-C to exit" )
104112
105113
iothub_client_sample_run()
106114
```
107115
108-
7. Save and close **SimulatedDevice.py** file.
116+
1. Save and close the **SimulatedDevice.py** file.
109117
110118
## Get the IoT hub connection string
111119
@@ -117,65 +125,56 @@ In this article you create a backend service to send cloud-to-device messages th
117125
118126
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).
119127
120-
1. Using a text editor, create a **SendCloudToDeviceMessage.py** file.
128+
1. In your working directory, open a command prompt and install the **Azure IoT Hub Service SDK for Python**.
129+
130+
```cmd/sh
131+
pip install azure-iot-hub
132+
```
121133

122-
2. Add the following `import` statements and variables at the start of the **SendCloudToDeviceMessage.py** file:
134+
1. Using a text editor, create a file named **SendCloudToDeviceMessage.py**.
135+
136+
1. Add the following `import` statements and variables at the start of the **SendCloudToDeviceMessage.py** file:
123137

124138
```python
125139
import random
126140
import sys
127-
import iothub_service_client
128-
from iothub_service_client import IoTHubMessaging, IoTHubMessage, IoTHubError
141+
from azure.iot.hub import IoTHubRegistryManager
129142

130-
OPEN_CONTEXT = 0
131-
FEEDBACK_CONTEXT = 1
132-
MESSAGE_COUNT = 1
143+
MESSAGE_COUNT = 2
133144
AVG_WIND_SPEED = 10.0
134145
MSG_TXT = "{\"service client sent a message\": %.2f}"
135146
```
136147

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:
148+
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:
138149

139150
```python
140151
CONNECTION_STRING = "{IoTHubConnectionString}"
141152
DEVICE_ID = "{deviceId}"
142153
```
143154

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:
155+
1. Add the following code to send messages to your device:
157156

158157
```python
159158
def iothub_messaging_sample_run():
160159
try:
161-
iothub_messaging = IoTHubMessaging(CONNECTION_STRING)
162-
163-
iothub_messaging.open(open_complete_callback, OPEN_CONTEXT)
160+
# Create IoTHubRegistryManager
161+
registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
164162

165163
for i in range(0, MESSAGE_COUNT):
166164
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()
165+
data = MSG_TXT % (AVG_WIND_SPEED + (random.random() * 4 + 2))
166+
167+
props={}
168+
# optional: assign system properties
169+
props.update(messageId = "message_%d" % i)
170+
props.update(correlationId = "correlation_%d" % i)
171+
props.update(contentType = "application/json")
172+
173+
# optional: assign application properties
175174
prop_text = "PropMsg_%d" % i
176-
prop_map.add("Property", prop_text)
175+
props.update(testProperty = prop_text)
177176

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

180179
try:
181180
# Try Python 2.xx first
@@ -185,61 +184,45 @@ In this section, you create a Python console app that sends cloud-to-device mess
185184
# Use Python 3.xx in the case of exception
186185
input("Press Enter to continue...\n")
187186

188-
iothub_messaging.close()
189-
190-
except IoTHubError as iothub_error:
191-
print ( "Unexpected error {0}" % iothub_error )
187+
except Exception as ex:
188+
print ( "Unexpected error {0}" % ex )
192189
return
193190
except KeyboardInterrupt:
194-
print ( "IoTHubMessaging sample stopped" )
191+
print ( "IoT Hub C2D Messaging service sample stopped" )
195192
```
196193

197-
6. Add the following main function:
194+
1. Add the following main function:
198195

199196
```python
200197
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) )
198+
print ( "Starting the Python IoT Hub C2D Messaging service sample..." )
204199

205200
iothub_messaging_sample_run()
206201
```
207202

208-
7. Save and close **SendCloudToDeviceMessage.py** file.
203+
1. Save and close **SendCloudToDeviceMessage.py** file.
209204

210205
## Run the applications
211206

212207
You are now ready to run the applications.
213208

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:
209+
1. At the command prompt in your working directory, run the following command to listen for cloud-to-device messages:
221210

222211
```shell
223212
python SimulatedDevice.py
224213
```
225214

226215
![Run the simulated device app](./media/iot-hub-python-python-c2d/simulated-device.png)
227216

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-
```
233-
234-
4. At a command prompt, run the following command to send a cloud-to-device message and wait for the message feedback:
217+
1. Open a new command prompt in your working directory and run the following command to send cloud-to-device messages:
235218

236219
```shell
237220
python SendCloudToDeviceMessage.py
238221
```
239222

240223
![Run the app to send the cloud-to-device command](./media/iot-hub-python-python-c2d/send-command.png)
241224

242-
5. Note the message received by the device.
225+
1. Note the message received by the device.
243226

244227
![Message received](./media/iot-hub-python-python-c2d/message-received.png)
245228

0 commit comments

Comments
 (0)