Skip to content

Commit f27e230

Browse files
committed
Added content for Python
1 parent 0740ef5 commit f27e230

File tree

3 files changed

+237
-0
lines changed

3 files changed

+237
-0
lines changed

includes/iot-hub-howto-device-management-java.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,30 @@ ms.custom: amqp, mqtt, devx-track-java, devx-track-extended-java
1414
## Overview
1515

1616
This article describes how to use the [Azure IoT SDK for Java](https://github.com/Azure/azure-iot-sdk-java) to create device and backend service application code for device direct methods.
17+
18+
## Create a device application
19+
20+
This section describes how to use device application code to:
21+
22+
* Respond to a direct method called by the cloud
23+
* Trigger a simulated device reboot
24+
* Use the reported properties to enable device twin queries to identify devices and when they were last rebooted
25+
26+
### Connect to a device
27+
28+
29+
### Create a direct method callback
30+
31+
32+
### SDK device samples
33+
34+
## Create a backend application
35+
36+
37+
### Connect to IoT hub
38+
39+
40+
### Invoke a method on a device
41+
42+
### SDK service samples
43+

includes/iot-hub-howto-device-management-node.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,25 @@ ms.custom: mqtt, devx-track-js
1414
## Overview
1515

1616
This article describes how to use the [Azure IoT SDK for Node.js](https://github.com/Azure/azure-iot-sdk-node) to create device and backend service application code for device direct methods.
17+
18+
## Create a device application
19+
20+
This section describes how to use device application code to:
21+
22+
* Respond to a direct method called by the cloud
23+
* Trigger a simulated device reboot
24+
* Use the reported properties to enable device twin queries to identify devices and when they were last rebooted
25+
26+
### Connect to a device
27+
28+
### Create a direct method callback
29+
30+
### SDK device samples
31+
32+
## Create a backend application
33+
34+
### Connect to IoT hub
35+
36+
### Invoke a method on a device
37+
38+
### SDK service samples

includes/iot-hub-howto-device-management-python.md

Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,191 @@ ms.custom: mqtt, devx-track-python, py-fresh-zinc
1414
## Overview
1515

1616
This article describes how to use the [Azure IoT SDK for Python](https://github.com/Azure/azure-iot-sdk-python) to create device and backend service application code for device direct methods.
17+
18+
## Create a device application
19+
20+
This section describes how to use device application code to:
21+
22+
* Respond to a direct method called by the cloud
23+
* Trigger a simulated device reboot
24+
* Use the reported properties to enable device twin queries to identify devices and when they were last rebooted
25+
26+
[!INCLUDE [iot-authentication-device-connection-string.md](iot-authentication-device-connection-string.md)]
27+
28+
### Connect to a device
29+
30+
The [IoTHubDeviceClient](/python/api/azure-iot-device/azure.iot.device.iothubdeviceclient) class contains methods that can be used to work with direct methods.
31+
32+
To connect an application to a device:
33+
1. Call [create_from_connection_string](/python/api/azure-iot-device/azure.iot.device.iothubdeviceclient?#azure-iot-device-iothubdeviceclient-create-from-connection-string) to add the device connection string
34+
1. Call [connect](/python/api/azure-iot-device/azure.iot.device.iothubdeviceclient?#azure-iot-device-iothubdeviceclient-connect) to connect the device client to an Azure IoT hub
35+
36+
```python
37+
# import the device client library
38+
import asyncio
39+
from azure.iot.device.aio import IoTHubDeviceClient
40+
41+
# substitute the device connection string in conn_str
42+
# and add it to the IoTHubDeviceClient object
43+
conn_str = "{IOT hub device connection string}"
44+
device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)
45+
46+
# connect the application to the device
47+
await device_client.connect()
48+
```
49+
50+
### Create a direct method callback
51+
52+
Call [on_method_request_received](/python/api/azure-iot-device/azure.iot.device.iothubdeviceclient?&#azure-iot-device-iothubdeviceclient-on-twin-desired-properties-patch-received) to create a handler function or coroutine that is called when a direct method is received. The listener is associated with a method name keyword, such as "reboot". The method name can be used in an IoT Hub or backend application to trigger the callback method on the device.
53+
54+
This example sets up a desired properties patch handler named `method_request_handler`.
55+
56+
For example:
57+
58+
```python
59+
try:
60+
# Attach the handler to the client
61+
client.on_method_request_received = method_request_handler
62+
except:
63+
# In the event of failure, clean up
64+
client.shutdown()
65+
```
66+
67+
In this example, the `method_request_handler` callback method implements the direct method on the device. This code updates reported properties related to a simulated device reboot. The reported properties can be read and verified by an IoT Hub or backend application, as demonstrated in the **Create a backend application** section of this article.
68+
69+
This example sets up a callback listener named `method_request_handler` that will trigger when the "rebootDevice" direct method name is called.
70+
71+
```python
72+
# Define the handler for method requests
73+
def method_request_handler(method_request):
74+
if method_request.name == "rebootDevice":
75+
# Act on the method by rebooting the device
76+
print("Rebooting device")
77+
time.sleep(20)
78+
print("Device rebooted")
79+
80+
# ...and patching the reported properties
81+
current_time = str(datetime.datetime.now())
82+
reported_props = {"rebootTime": current_time}
83+
client.patch_twin_reported_properties(reported_props)
84+
print( "Device twins updated with latest rebootTime")
85+
86+
# Create a method response indicating the method request was resolved
87+
resp_status = 200
88+
resp_payload = {"Response": "This is the response from the device"}
89+
method_response = MethodResponse(method_request.request_id, resp_status, resp_payload)
90+
91+
else:
92+
# Create a method response indicating the method request was for an unknown method
93+
resp_status = 404
94+
resp_payload = {"Response": "Unknown method"}
95+
method_response = MethodResponse(method_request.request_id, resp_status, resp_payload)
96+
97+
# Send the method response
98+
client.send_method_response(method_response)
99+
```
100+
101+
### SDK device samples
102+
103+
The Azure IoT SDK for Python provides a working sample of a device app that handles direct method tasks. For more information, see [Receive direct method](https://github.com/Azure/azure-iot-sdk-python/blob/main/samples/async-hub-scenarios/receive_direct_method.py).
104+
105+
## Create a backend application
106+
107+
This section describes how to initiate a remote reboot on a device using a direct method.
108+
109+
The [IoTHubRegistryManager](/python/api/azure-iot-hub/azure.iot.hub.iothubregistrymanager) class exposes all methods required to create a backend application to send messages to a device.
110+
111+
### Import statements
112+
113+
Add these import statements to connect to Iot Hub, receive cloud-to-device methods, and call twin methods.
114+
115+
```python
116+
import sys, time
117+
118+
from azure.iot.hub import IoTHubRegistryManager
119+
from azure.iot.hub.models import CloudToDeviceMethod, CloudToDeviceMethodResult, Twin
120+
```
121+
122+
### Connect to IoT hub
123+
124+
Connect to IoT hub using [from_connection_string](/python/api/azure-iot-hub/azure.iot.hub.iothubregistrymanager?#azure-iot-hub-iothubregistrymanager-from-connection-string). As a parameter, supply the **IoT Hub service connection string** that you created in the prerequisites section.
125+
126+
To invoke a direct method on a device through IoT Hub, 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.
127+
128+
As a parameter to `CreateFromConnectionString`, supply the **service** shared access policy. For more information about shared access policies, see [Control access to IoT Hub with shared access signatures](/azure/iot-hub/authenticate-authorize-sas).
129+
130+
For example:
131+
132+
```python
133+
# Connect to IoT hub
134+
IOTHUB_CONNECTION_STRING = "{IoT hub service connection string}"
135+
iothub_registry_manager = IoTHubRegistryManager.from_connection_string(IOTHUB_CONNECTION_STRING)
136+
```
137+
138+
### Invoke a method on a device
139+
140+
You can invoke a direct method on a device. The method name is mapped to a name, which is "rebootTime" in the examples within this article.
141+
142+
To invoke a direct method on a device:
143+
144+
1. Create a [CloudToDeviceMethod](/python/api/azure-iot-hub/azure.iot.hub.protocol.models.cloudtodevicemethod) object. Supply the method name and payload as parameters.
145+
1. Call [invoke_device_method](/python/api/azure-iot-hub/azure.iot.hub.iothub_registry_manager.iothubregistrymanager?#azure-iot-hub-iothub-registry-manager-iothubregistrymanager-invoke-device-method) to invoke a direct method on a device. Supply the device ID and `CloudToDeviceMethod` payload object as parameters.
146+
147+
This example invokes a direct method named "rebootDevice" on a device. The example then uses device twin queries to discover the last reboot time for the device that was updated in the **Create a direct method callback** section of this article.
148+
149+
```python
150+
CONNECTION_STRING = "{IoTHubConnectionString}"
151+
DEVICE_ID = "{deviceId}"
152+
153+
METHOD_NAME = "rebootDevice"
154+
METHOD_PAYLOAD = "{\"method_number\":\"42\"}"
155+
TIMEOUT = 60
156+
WAIT_COUNT = 10
157+
158+
try:
159+
print ( "" )
160+
print ( "Invoking device to reboot..." )
161+
162+
# Call the direct method.
163+
deviceMethod = CloudToDeviceMethod(method_name=METHOD_NAME, payload=METHOD_PAYLOAD)
164+
response = registry_manager.invoke_device_method(DEVICE_ID, deviceMethod)
165+
166+
print ( "" )
167+
print ( "Successfully invoked the device to reboot." )
168+
169+
print ( "" )
170+
print ( response.payload )
171+
172+
while True:
173+
print ( "" )
174+
print ( "IoTHubClient waiting for commands, press Ctrl-C to exit" )
175+
176+
status_counter = 0
177+
while status_counter <= WAIT_COUNT:
178+
twin_info = registry_manager.get_twin(DEVICE_ID)
179+
180+
if twin_info.properties.reported.get("rebootTime") != None :
181+
print ("Last reboot time: " + twin_info.properties.reported.get("rebootTime"))
182+
else:
183+
print ("Waiting for device to report last reboot time...")
184+
185+
time.sleep(5)
186+
status_counter += 1
187+
188+
except Exception as ex:
189+
print ( "" )
190+
print ( "Unexpected error {0}".format(ex) )
191+
return
192+
except KeyboardInterrupt:
193+
print ( "" )
194+
print ( "IoTHubDeviceMethod sample stopped" )
195+
196+
if __name__ == '__main__':
197+
print ( "Starting the IoT Hub Service Client DeviceManagement Python sample..." )
198+
print ( " Connection string = {0}".format(CONNECTION_STRING) )
199+
print ( " Device ID = {0}".format(DEVICE_ID) )
200+
```
201+
202+
### SDK service samples
203+
204+
The Azure IoT SDK for Python provides a working sample of a service app that handles direct method tasks. For more information, see [Service helper sync](https://github.com/Azure/azure-iot-sdk-python/blob/e75d1c2026eab939d5d31097fd0c22924c53abf8/dev_utils/dev_utils/service_helper_sync.py).

0 commit comments

Comments
 (0)