Skip to content

Commit 4a9ac79

Browse files
authored
Merge pull request #222759 from vmagelo/freshness-work2
Freshness work for Python.
2 parents 03f92d3 + 5c038d6 commit 4a9ac79

File tree

1 file changed

+90
-90
lines changed

1 file changed

+90
-90
lines changed

articles/iot-hub/iot-hub-python-twin-getstarted.md

Lines changed: 90 additions & 90 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: 03/11/2020
9+
ms.date: 01/03/2023
1010
ms.author: kgremban
1111
ms.custom: mqtt, devx-track-python, py-fresh-zinc
1212
---
@@ -22,7 +22,7 @@ In this article, you create two Python console apps:
2222
* **ReportConnectivity.py**: a simulated device app that connects to your IoT hub and reports its connectivity condition.
2323

2424
> [!NOTE]
25-
> See [Azure IoT SDKs](iot-hub-devguide-sdks.md) for more information about the SDK tools available to build both device and back-end apps.
25+
> For more information about the SDK tools available to build both device and back-end apps, see [Azure IoT SDKs](iot-hub-devguide-sdks.md).
2626
2727
## Prerequisites
2828

@@ -42,6 +42,94 @@ In this article, you create two Python console apps:
4242

4343
[!INCLUDE [iot-hub-include-find-custom-connection-string](../../includes/iot-hub-include-find-custom-connection-string.md)]
4444

45+
## Create a service app that updates desired properties and queries twins
46+
47+
In this section, you create a Python console app that adds location metadata to the device twin associated with your **{Device ID}**. The app queries IoT hub for devices located in the US and then queries devices that report a cellular network connection.
48+
49+
1. In your working directory, open a command prompt and install the **Azure IoT Hub Service SDK for Python**.
50+
51+
```cmd/sh
52+
pip install azure-iot-hub
53+
```
54+
55+
2. Using a text editor, create a new **AddTagsAndQuery.py** file.
56+
57+
3. Add the following code to import the required modules from the service SDK:
58+
59+
```python
60+
import sys
61+
from time import sleep
62+
from azure.iot.hub import IoTHubRegistryManager
63+
from azure.iot.hub.models import Twin, TwinProperties, QuerySpecification, QueryResult
64+
```
65+
66+
4. Add the following code. Replace `[IoTHub Connection String]` with the IoT hub connection string you copied in [Get the IoT hub connection string](#get-the-iot-hub-connection-string). Replace `[Device Id]` with the device ID (the name) from your registered device in the IoT Hub.
67+
68+
```python
69+
IOTHUB_CONNECTION_STRING = "[IoTHub Connection String]"
70+
DEVICE_ID = "[Device Id]"
71+
```
72+
73+
5. Add the following code to the **AddTagsAndQuery.py** file:
74+
75+
```python
76+
def iothub_service_sample_run():
77+
try:
78+
iothub_registry_manager = IoTHubRegistryManager(IOTHUB_CONNECTION_STRING)
79+
80+
new_tags = {
81+
'location' : {
82+
'region' : 'US',
83+
'plant' : 'Redmond43'
84+
}
85+
}
86+
87+
twin = iothub_registry_manager.get_twin(DEVICE_ID)
88+
twin_patch = Twin(tags=new_tags, properties= TwinProperties(desired={'power_level' : 1}))
89+
twin = iothub_registry_manager.update_twin(DEVICE_ID, twin_patch, twin.etag)
90+
91+
# Add a delay to account for any latency before executing the query
92+
sleep(1)
93+
94+
query_spec = QuerySpecification(query="SELECT * FROM devices WHERE tags.location.plant = 'Redmond43'")
95+
query_result = iothub_registry_manager.query_iot_hub(query_spec, None, 100)
96+
print("Devices in Redmond43 plant: {}".format(', '.join([twin.device_id for twin in query_result.items])))
97+
98+
print()
99+
100+
query_spec = QuerySpecification(query="SELECT * FROM devices WHERE tags.location.plant = 'Redmond43' AND properties.reported.connectivity = 'cellular'")
101+
query_result = iothub_registry_manager.query_iot_hub(query_spec, None, 100)
102+
print("Devices in Redmond43 plant using cellular network: {}".format(', '.join([twin.device_id for twin in query_result.items])))
103+
104+
except Exception as ex:
105+
print("Unexpected error {0}".format(ex))
106+
return
107+
except KeyboardInterrupt:
108+
print("IoT Hub Device Twin service sample stopped")
109+
```
110+
111+
The **IoTHubRegistryManager** object exposes all the methods required to interact with device twins from the service. The code first initializes the **IoTHubRegistryManager** object, then updates the device twin for **DEVICE_ID**, 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 a cellular network.
112+
113+
6. Add the following code at the end of **AddTagsAndQuery.py** to implement the **iothub_service_sample_run** function:
114+
115+
```python
116+
if __name__ == '__main__':
117+
print("Starting the Python IoT Hub Device Twin service sample...")
118+
print()
119+
120+
iothub_service_sample_run()
121+
```
122+
123+
7. Run the application with:
124+
125+
```cmd/sh
126+
python AddTagsAndQuery.py
127+
```
128+
129+
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. In the next section, you'll create a device app that will use a cellular network and you'll rerun this query to see how it changes.
130+
131+
![Screenshot of the first query showing all devices in Redmond.](./media/iot-hub-python-twin-getstarted/service-1.png)
132+
45133
## Create a device app that updates reported properties
46134

47135
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 confirm that it's connected using a cellular network.
@@ -142,94 +230,6 @@ In this section, you create a Python console app that connects to your hub as yo
142230

143231
![receive desired properties on device app](./media/iot-hub-python-twin-getstarted/device-2.png)
144232

145-
## Create a service app that updates desired properties and queries twins
146-
147-
In this section, you create a Python console app that adds location metadata to the device twin associated with your **{Device ID}**. The app queries IoT hub for devices located in the US and then queries devices that report a cellular network connection.
148-
149-
1. In your working directory, open a command prompt and install the **Azure IoT Hub Service SDK for Python**.
150-
151-
```cmd/sh
152-
pip install azure-iot-hub
153-
```
154-
155-
2. Using a text editor, create a new **AddTagsAndQuery.py** file.
156-
157-
3. Add the following code to import the required modules from the service SDK:
158-
159-
```python
160-
import sys
161-
from time import sleep
162-
from azure.iot.hub import IoTHubRegistryManager
163-
from azure.iot.hub.models import Twin, TwinProperties, QuerySpecification, QueryResult
164-
```
165-
166-
4. Add the following code. Replace `[IoTHub Connection String]` with the IoT hub connection string you copied in [Get the IoT hub connection string](#get-the-iot-hub-connection-string). Replace `[Device Id]` with the device ID (the name) from your registered device in the IoT Hub.
167-
168-
```python
169-
IOTHUB_CONNECTION_STRING = "[IoTHub Connection String]"
170-
DEVICE_ID = "[Device Id]"
171-
```
172-
173-
5. Add the following code to the **AddTagsAndQuery.py** file:
174-
175-
```python
176-
def iothub_service_sample_run():
177-
try:
178-
iothub_registry_manager = IoTHubRegistryManager(IOTHUB_CONNECTION_STRING)
179-
180-
new_tags = {
181-
'location' : {
182-
'region' : 'US',
183-
'plant' : 'Redmond43'
184-
}
185-
}
186-
187-
twin = iothub_registry_manager.get_twin(DEVICE_ID)
188-
twin_patch = Twin(tags=new_tags, properties= TwinProperties(desired={'power_level' : 1}))
189-
twin = iothub_registry_manager.update_twin(DEVICE_ID, twin_patch, twin.etag)
190-
191-
# Add a delay to account for any latency before executing the query
192-
sleep(1)
193-
194-
query_spec = QuerySpecification(query="SELECT * FROM devices WHERE tags.location.plant = 'Redmond43'")
195-
query_result = iothub_registry_manager.query_iot_hub(query_spec, None, 100)
196-
print("Devices in Redmond43 plant: {}".format(', '.join([twin.device_id for twin in query_result.items])))
197-
198-
print()
199-
200-
query_spec = QuerySpecification(query="SELECT * FROM devices WHERE tags.location.plant = 'Redmond43' AND properties.reported.connectivity = 'cellular'")
201-
query_result = iothub_registry_manager.query_iot_hub(query_spec, None, 100)
202-
print("Devices in Redmond43 plant using cellular network: {}".format(', '.join([twin.device_id for twin in query_result.items])))
203-
204-
except Exception as ex:
205-
print("Unexpected error {0}".format(ex))
206-
return
207-
except KeyboardInterrupt:
208-
print("IoT Hub Device Twin service sample stopped")
209-
```
210-
211-
The **IoTHubRegistryManager** object exposes all the methods required to interact with device twins from the service. The code first initializes the **IoTHubRegistryManager** object, then updates the device twin for **DEVICE_ID**, 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 a cellular network.
212-
213-
6. Add the following code at the end of **AddTagsAndQuery.py** to implement the **iothub_service_sample_run** function:
214-
215-
```python
216-
if __name__ == '__main__':
217-
print("Starting the Python IoT Hub Device Twin service sample...")
218-
print()
219-
220-
iothub_service_sample_run()
221-
```
222-
223-
7. Run the application with:
224-
225-
```cmd/sh
226-
python AddTagsAndQuery.py
227-
```
228-
229-
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.
230-
231-
![first query showing all devices in Redmond](./media/iot-hub-python-twin-getstarted/service-1.png)
232-
233233
In this article, you:
234234

235235
* Added device metadata as tags from a back-end app

0 commit comments

Comments
 (0)