Skip to content

Commit 61e4394

Browse files
authored
Merge pull request MicrosoftDocs#29250 from msebolt/python-device-twins
iot-hub-python-twin-getstarted initial draft
2 parents bf69ecb + 265120c commit 61e4394

File tree

6 files changed

+300
-1
lines changed

6 files changed

+300
-1
lines changed

articles/iot-hub/TOC.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@
8888
#### [.NET back end/Node.js device](iot-hub-csharp-node-twin-getstarted.md)
8989
#### [.NET back end/.NET device](iot-hub-csharp-csharp-twin-getstarted.md)
9090
#### [Java back end/Java device](iot-hub-java-java-twin-getstarted.md)
91+
#### [Python back end/Python device](iot-hub-python-twin-getstarted.md)
9192
### Use direct methods
9293
#### [Node.js back end/Node.js device](iot-hub-node-node-direct-methods.md)
9394
#### [.NET back end/Node.js device](iot-hub-csharp-node-direct-methods.md)
Lines changed: 297 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,297 @@
1+
---
2+
title: Get started with Azure IoT Hub device twins (Python) | Microsoft Docs
3+
description: How to use Azure IoT Hub device twins to add tags and then use an IoT Hub query. You use the Azure IoT SDKs for Python to implement the simulated device app and a service app that adds the tags and runs the IoT Hub query.
4+
services: iot-hub
5+
documentationcenter: python
6+
author: msebolt
7+
manager: timlt
8+
editor: ''
9+
10+
ms.assetid: 314c88e4-cce1-441c-b75a-d2e08e39ae7d
11+
ms.service: iot-hub
12+
ms.devlang: python
13+
ms.topic: article
14+
ms.tgt_pltfrm: na
15+
ms.workload: na
16+
ms.date: 12/04/2017
17+
ms.author: v-masebo
18+
19+
---
20+
# Get started with device twins (Python)
21+
[!INCLUDE [iot-hub-selector-twin-get-started](../../includes/iot-hub-selector-twin-get-started.md)]
22+
23+
At the end of this tutorial, you will have two Python console apps:
24+
25+
* **AddTagsAndQuery.py**, a Python back-end app, which adds tags and queries device twins.
26+
* **ReportConnectivity.py**, a Python app, which simulates a device that connects to your IoT hub with the device identity created earlier, and reports its connectivity condition.
27+
28+
> [!NOTE]
29+
> The article [Azure IoT SDKs][lnk-hub-sdks] provides information about the Azure IoT SDKs that you can use to build both device and back-end apps.
30+
>
31+
>
32+
33+
To complete this tutorial you need the following:
34+
35+
* [Python 2.x or 3.x][lnk-python-download]. Make sure to use the 32-bit or 64-bit installation as required by your setup. When prompted during the installation, make sure to add Python to your platform-specific environment variable. If you are using Python 2.x, you may need to [install or upgrade *pip*, the Python package management system][lnk-install-pip].
36+
* If you are using Windows OS, then [Visual C++ redistributable package][lnk-visual-c-redist] to allow the use of native DLLs from Python.
37+
* An active Azure account. (If you don't have an account, you can create a [free account][lnk-free-trial] in just a couple of minutes.)
38+
39+
> [!NOTE]
40+
> The *pip* packages for `azure-iothub-service-client` and `azure-iothub-device-client` are currently available only for Windows OS. For Linux/Mac OS, please refer to the Linux and Mac OS-specific sections on the [Prepare your development environment for Python][lnk-python-devbox] post.
41+
>
42+
43+
[!INCLUDE [iot-hub-get-started-create-hub](../../includes/iot-hub-get-started-create-hub.md)]
44+
45+
[!INCLUDE [iot-hub-get-started-create-device-identity](../../includes/iot-hub-get-started-create-device-identity-portal.md)]
46+
47+
## Create the service app
48+
In this section, you create a Python console app that adds location metadata to the device twin associated with your **{Device Id}**. It then queries the device twins stored in the IoT hub selecting the devices located in Redmond, and then the ones that are reporting a cellular connection.
49+
50+
1. Open a command prompt and install the **Azure IoT Hub Service SDK for Python**. Close the command prompt after you install the SDK.
51+
52+
```
53+
pip install azure-iothub-service-client
54+
```
55+
56+
1. Using a text editor, create a new **AddTagsAndQuery.py** file.
57+
58+
3. Add the following code to import the required modules from the service SDK:
59+
60+
```python
61+
import sys
62+
import iothub_service_client
63+
from iothub_service_client import IoTHubRegistryManager, IoTHubRegistryManagerAuthMethod
64+
from iothub_service_client import IoTHubDeviceTwin, IoTHubError
65+
```
66+
2. Add the following code, replacing the placeholder for `[IoTHub Connection String]` and `[Device Id]` with the connection string for the IoT hub and the device id you created in the previous sections.
67+
68+
```python
69+
CONNECTION_STRING = "[IoTHub Connection String]"
70+
DEVICE_ID = "[Device Id]"
71+
72+
UPDATE_JSON = "{\"properties\":{\"desired\":{\"location\":\"Redmond\"}}}"
73+
74+
UPDATE_JSON_SEARCH = "\"location\":\"Redmond\""
75+
UPDATE_JSON_CLIENT_SEARCH = "\"connectivity\":\"cellular\""
76+
```
77+
78+
1. Add the following code to the **AddTagsAndQuery.py** file:
79+
80+
```python
81+
def iothub_service_sample_run():
82+
try:
83+
iothub_registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
84+
85+
iothub_registry_statistics = iothub_registry_manager.get_statistics()
86+
print ( "Total device count : {0}".format(iothub_registry_statistics.totalDeviceCount) )
87+
print ( "Enabled device count : {0}".format(iothub_registry_statistics.enabledDeviceCount) )
88+
print ( "Disabled device count : {0}".format(iothub_registry_statistics.disabledDeviceCount) )
89+
print ( "" )
90+
91+
number_of_devices = iothub_registry_statistics.totalDeviceCount
92+
dev_list = iothub_registry_manager.get_device_list(number_of_devices)
93+
94+
iothub_twin_method = IoTHubDeviceTwin(CONNECTION_STRING)
95+
96+
for device in range(0, number_of_devices):
97+
if dev_list[device].deviceId == DEVICE_ID:
98+
twin_info = iothub_twin_method.update_twin(dev_list[device].deviceId, UPDATE_JSON)
99+
100+
print ( "Devices in Redmond: " )
101+
for device in range(0, number_of_devices):
102+
twin_info = iothub_twin_method.get_twin(dev_list[device].deviceId)
103+
104+
if twin_info.find(UPDATE_JSON_SEARCH) > -1:
105+
print ( dev_list[device].deviceId )
106+
107+
print ( "" )
108+
109+
print ( "Devices in Redmond using cellular network: " )
110+
for device in range(0, number_of_devices):
111+
twin_info = iothub_twin_method.get_twin(dev_list[device].deviceId)
112+
113+
if twin_info.find(UPDATE_JSON_SEARCH) > -1:
114+
if twin_info.find(UPDATE_JSON_CLIENT_SEARCH) > -1:
115+
print ( dev_list[device].deviceId )
116+
117+
except IoTHubError as iothub_error:
118+
print ( "Unexpected error {0}".format(iothub_error) )
119+
return
120+
except KeyboardInterrupt:
121+
print ( "IoTHub sample stopped" )
122+
```
123+
124+
The **Registry** object exposes all the methods required to interact with device twins from the service. The code first initializes the **Registry** object, then updates the device twin for **deviceId**, and finally runs two queries. The first selects only the device twins of devices located in the **Redmond43** plant, and the second refines the query to select only the devices that are also connected through cellular network.
125+
126+
1. Add the following code at the end of **AddTagsAndQuery.py** to implement the **iothub_service_sample_run** function:
127+
128+
```python
129+
if __name__ == '__main__':
130+
print ( "Starting the IoT Hub Device Twins Python service sample..." )
131+
132+
iothub_service_sample_run()
133+
```
134+
135+
1. Run the application with:
136+
137+
```cmd/sh
138+
python AddTagsAndQuery.py
139+
```
140+
141+
You should see one device in the results for the query asking for all devices located in **Redmond43** and none for the query that restricts the results to devices that use a cellular network.
142+
143+
![first query][1]
144+
145+
In the next section, you create a device app that reports the connectivity information and changes the result of the query in the previous section.
146+
147+
## Create the device app
148+
In this section, you create a Python console app that connects to your hub as your **{Device Id}**, and then updates its device twin's reported properties to contain the information that it is connected using a cellular network.
149+
150+
1. Open a command prompt and install the **Azure IoT Hub Service SDK for Python**. Close the command prompt after you install the SDK.
151+
152+
```
153+
pip install azure-iothub-device-client
154+
```
155+
156+
1. Using a text editor, create a new **ReportConnectivity.py** file.
157+
158+
3. Add the following code to import the required modules from the service SDK:
159+
160+
```python
161+
import time
162+
import iothub_client
163+
from iothub_client import IoTHubClient, IoTHubClientError, IoTHubTransportProvider, IoTHubClientResult, IoTHubError
164+
```
165+
166+
2. Add the following code, replacing the placeholder for `[IoTHub Device Connection String]` with the connection string for the IoT hub device you created in the previous sections.
167+
168+
```python
169+
CONNECTION_STRING = "[IoTHub Device Connection String]"
170+
171+
# choose HTTP, AMQP, AMQP_WS or MQTT as transport protocol
172+
PROTOCOL = IoTHubTransportProvider.MQTT
173+
174+
TIMER_COUNT = 5
175+
TWIN_CONTEXT = 0
176+
SEND_REPORTED_STATE_CONTEXT = 0
177+
```
178+
179+
1. Add the following code to the **ReportConnectivity.py** file to implement the device twins functionality:
180+
181+
```python
182+
def device_twin_callback(update_state, payload, user_context):
183+
print ( "" )
184+
print ( "Twin callback called with:" )
185+
print ( " updateStatus: %s" % update_state )
186+
print ( " payload: %s" % payload )
187+
188+
def send_reported_state_callback(status_code, user_context):
189+
print ( "" )
190+
print ( "Confirmation for reported state called with:" )
191+
print ( " status_code: %d" % status_code )
192+
193+
def iothub_client_init():
194+
client = IoTHubClient(CONNECTION_STRING, PROTOCOL)
195+
196+
if client.protocol == IoTHubTransportProvider.MQTT or client.protocol == IoTHubTransportProvider.MQTT_WS:
197+
client.set_device_twin_callback(
198+
device_twin_callback, TWIN_CONTEXT)
199+
200+
return client
201+
202+
def iothub_client_sample_run():
203+
try:
204+
client = iothub_client_init()
205+
206+
if client.protocol == IoTHubTransportProvider.MQTT:
207+
print ( "Sending data as reported property..." )
208+
209+
reported_state = "{\"connectivity\":\"cellular\"}"
210+
211+
client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT)
212+
213+
while True:
214+
print ( "Press Ctrl-C to exit" )
215+
216+
status_counter = 0
217+
while status_counter <= TIMER_COUNT:
218+
status = client.get_send_status()
219+
time.sleep(10)
220+
status_counter += 1
221+
except IoTHubError as iothub_error:
222+
print ( "Unexpected error %s from IoTHub" % iothub_error )
223+
return
224+
except KeyboardInterrupt:
225+
print ( "IoTHubClient sample stopped" )
226+
```
227+
228+
The **Client** object exposes all the methods you require to interact with device twins from the device. The previous code, after it initializes the **Client** object, retrieves the device twin for your device and updates its reported property with the connectivity information.
229+
230+
1. Add the following code at the end of **ReportConnectivity.py** to implement the **iothub_client_sample_run** function:
231+
232+
```python
233+
if __name__ == '__main__':
234+
print ( "Starting the IoT Hub Device Twins Python client sample..." )
235+
236+
iothub_client_sample_run()
237+
```
238+
239+
1. Run the device app
240+
241+
```cmd/sh
242+
python ReportConnectivity.js
243+
```
244+
245+
You should see confirmation the device twins were updated.
246+
247+
![update twins][2]
248+
249+
6. Now that the device reported its connectivity information, it should appear in both queries. Go back and run the queries again:
250+
251+
```cmd/sh
252+
python AddTagsAndQuery.js
253+
```
254+
255+
This time your **{Device Id}** should appear in both query results.
256+
257+
![second query][3]
258+
259+
## Next steps
260+
In this tutorial, you configured a new IoT hub in the Azure portal, and then created a device identity in the IoT hub's identity registry. You added device metadata as tags from a back-end app, and wrote a simulated device app to report device connectivity information in the device twin. You also learned how to query this information using the registry.
261+
262+
Use the following resources to learn how to:
263+
264+
* Send telemetry from devices with the [Get started with IoT Hub][lnk-iothub-getstarted] tutorial,
265+
* Configure devices using device twin's desired properties with the [Use desired properties to configure devices][lnk-twin-how-to-configure] tutorial,
266+
* Control devices interactively (such as turning on a fan from a user-controlled app), with the [Use direct methods][lnk-methods-tutorial] tutorial.
267+
268+
<!-- images -->
269+
[1]: media/iot-hub-python-twin-getstarted/1.png
270+
[2]: media/iot-hub-python-twin-getstarted/2.png
271+
[3]: media/iot-hub-python-twin-getstarted/3.png
272+
273+
<!-- links -->
274+
[lnk-hub-sdks]: iot-hub-devguide-sdks.md
275+
[lnk-free-trial]: http://azure.microsoft.com/pricing/free-trial/
276+
277+
[lnk-python-download]: https://www.python.org/downloads/
278+
[lnk-visual-c-redist]: http://www.microsoft.com/download/confirmation.aspx?id=48145
279+
[lnk-install-pip]: https://pip.pypa.io/en/stable/installing/
280+
[lnk-python-devbox]: https://github.com/Azure/azure-iot-sdk-python/blob/master/doc/python-devbox-setup.md
281+
282+
[lnk-d2c]: iot-hub-devguide-messaging.md#device-to-cloud-messages
283+
[lnk-methods]: iot-hub-devguide-direct-methods.md
284+
[lnk-twins]: iot-hub-devguide-device-twins.md
285+
[lnk-query]: iot-hub-devguide-query-language.md
286+
[lnk-identity]: iot-hub-devguide-identity-registry.md
287+
288+
[lnk-iothub-getstarted]: iot-hub-python-getstarted.md
289+
[lnk-device-management]: iot-hub-node-node-device-management-get-started.md
290+
[lnk-iot-edge]: iot-hub-linux-iot-edge-get-started.md
291+
[lnk-connect-device]: https://azure.microsoft.com/develop/iot/
292+
293+
[lnk-twin-how-to-configure]: iot-hub-node-node-twin-how-to-configure.md
294+
[lnk-dev-setup]: https://github.com/Azure/azure-iot-sdk-node/tree/master/doc/node-devbox-setup.md
295+
296+
[lnk-methods-tutorial]: iot-hub-node-node-direct-methods.md
297+
[lnk-devguide-mqtt]: iot-hub-mqtt-support.md
Loading
Loading
Loading

includes/iot-hub-selector-twin-get-started.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
> * [C#/Node.js](../articles/iot-hub/iot-hub-csharp-node-twin-getstarted.md)
44
> * [C#](../articles/iot-hub/iot-hub-csharp-csharp-twin-getstarted.md)
55
> * [Java](../articles/iot-hub/iot-hub-java-java-twin-getstarted.md)
6+
> * [Python](../articles/iot-hub/iot-hub-python-twin-getstarted.md)
67
78
Device twins are JSON documents that store device state information (metadata, configurations, and conditions). IoT Hub persists a device twin for each device that connects to it.
89

@@ -14,7 +15,7 @@ Use device twins to:
1415
* Query your device metadata, configuration, or state.
1516

1617
> [!NOTE]
17-
> Device twins are designed for synchronization and for querying device configurations and conditions. More informations on when to use device twins can be found in [Understand device twins][lnk-twins].
18+
> Device twins are designed for synchronization and for querying device configurations and conditions. More information on when to use device twins can be found in [Understand device twins][lnk-twins].
1819
1920
Device twins are stored in an IoT hub and contain:
2021

0 commit comments

Comments
 (0)