title | description | author | ms.service | services | ms.devlang | ms.topic | ms.date | ms.author | ms.custom |
---|---|---|---|---|---|---|---|---|---|
Get started with Azure IoT Hub device management (Python) | Microsoft Docs |
How to use IoT Hub device management to initiate a remote device reboot. You use the Azure IoT SDK for Python to implement a simulated device app that includes a direct method and a service app that invokes the direct method. |
kgremban |
iot-hub |
iot-hub |
python |
conceptual |
01/17/2020 |
kgremban |
mqtt, devx-track-python, devx-track-azurecli |
[!INCLUDE iot-hub-selector-dm-getstarted]
This tutorial shows you how to:
-
Use the Azure portal to create an IoT Hub and create a device identity in your IoT hub.
-
Create a simulated device app that contains a direct method that reboots that device. Direct methods are invoked from the cloud.
-
Create a Python console app that calls the reboot direct method in the simulated device app through your IoT hub.
At the end of this tutorial, you have two Python console apps:
-
dmpatterns_getstarted_device.py, which connects to your IoT hub with the device identity created earlier, receives a reboot direct method, simulates a physical reboot, and reports the time for the last reboot.
-
dmpatterns_getstarted_service.py, which calls a direct method in the simulated device app, displays the response, and displays the updated reported properties.
[!INCLUDE iot-hub-include-python-sdk-note]
[!INCLUDE iot-hub-include-python-installation-notes]
- 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).
[!INCLUDE iot-hub-include-create-hub]
[!INCLUDE iot-hub-get-started-create-device-identity]
In this section, you:
-
Create a Python console app that responds to a direct method called by the cloud
-
Simulate a device reboot
-
Use the reported properties to enable device twin queries to identify devices and when they last rebooted
-
At your command prompt, run the following command to install the azure-iot-device package:
pip install azure-iot-device
-
Using a text editor, create a file named dmpatterns_getstarted_device.py in your working directory.
-
Add the following
import
statements at the start of the dmpatterns_getstarted_device.py file.import time import datetime from azure.iot.device import IoTHubDeviceClient, MethodResponse
-
Add the CONNECTION_STRING variable. Replace the
{deviceConnectionString}
placeholder value with your device connection string. You copied this connection string previously in Register a new device in the IoT hub.CONNECTION_STRING = "{deviceConnectionString}"
-
Add the following function to instantiate a client configured for direct methods on the device.
def create_client(): # Instantiate the client client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING) # Define the handler for method requests def method_request_handler(method_request): if method_request.name == "rebootDevice": # Act on the method by rebooting the device print("Rebooting device") time.sleep(20) print("Device rebooted") # ...and patching the reported properties current_time = str(datetime.datetime.now()) reported_props = {"rebootTime": current_time} client.patch_twin_reported_properties(reported_props) print( "Device twins updated with latest rebootTime") # Create a method response indicating the method request was resolved resp_status = 200 resp_payload = {"Response": "This is the response from the device"} method_response = MethodResponse(method_request.request_id, resp_status, resp_payload) else: # Create a method response indicating the method request was for an unknown method resp_status = 404 resp_payload = {"Response": "Unknown method"} method_response = MethodResponse(method_request.request_id, resp_status, resp_payload) # Send the method response client.send_method_response(method_response) try: # Attach the handler to the client client.on_method_request_received = method_request_handler except: # In the event of failure, clean up client.shutdown() return client
-
Start the direct method sample and wait.
def main(): print ("Starting the IoT Hub Python sample...") client = create_client() print ("Waiting for commands, press Ctrl-C to exit") try: # Wait for program exit while True: time.sleep(1000) except KeyboardInterrupt: print("IoTHubDeviceClient sample stopped") finally: # Graceful exit print("Shutting down IoT Hub Client") client.shutdown() if __name__ == '__main__': main()
-
Save and close the dmpatterns_getstarted_device.py file.
Note
To keep things simple, this tutorial does not implement any retry policy. In production code, you should implement retry policies (such as an exponential backoff), as suggested in the article, Transient Fault Handling.
[!INCLUDE iot-hub-howto-device-management-shared-access-policy-text]
[!INCLUDE iot-hub-include-find-service-connection-string]
In this section, you create a Python console app that initiates a remote reboot on a device using a direct method. The app uses device twin queries to discover the last reboot time for that device.
-
At your command prompt, run the following command to install the azure-iot-hub package:
pip install azure-iot-hub
-
Using a text editor, create a file named dmpatterns_getstarted_service.py in your working directory.
-
Add the following
import
statements at the start of the dmpatterns_getstarted_service.py file.import sys, time from azure.iot.hub import IoTHubRegistryManager from azure.iot.hub.models import CloudToDeviceMethod, CloudToDeviceMethodResult, Twin
-
Add the following variable declarations. Replace the
{IoTHubConnectionString}
placeholder value with the IoT hub connection string you copied previously in Get the IoT hub connection string. Replace the{deviceId}
placeholder value with the device ID you registered in Register a new device in the IoT hub.CONNECTION_STRING = "{IoTHubConnectionString}" DEVICE_ID = "{deviceId}" METHOD_NAME = "rebootDevice" METHOD_PAYLOAD = "{\"method_number\":\"42\"}" TIMEOUT = 60 WAIT_COUNT = 10
-
Add the following function to invoke the device method to reboot the target device, then query for the device twins and get the last reboot time.
def iothub_devicemethod_sample_run(): try: # Create IoTHubRegistryManager registry_manager = IoTHubRegistryManager(CONNECTION_STRING) print ( "" ) print ( "Invoking device to reboot..." ) # Call the direct method. deviceMethod = CloudToDeviceMethod(method_name=METHOD_NAME, payload=METHOD_PAYLOAD) response = registry_manager.invoke_device_method(DEVICE_ID, deviceMethod) print ( "" ) print ( "Successfully invoked the device to reboot." ) print ( "" ) print ( response.payload ) while True: print ( "" ) print ( "IoTHubClient waiting for commands, press Ctrl-C to exit" ) status_counter = 0 while status_counter <= WAIT_COUNT: twin_info = registry_manager.get_twin(DEVICE_ID) if twin_info.properties.reported.get("rebootTime") != None : print ("Last reboot time: " + twin_info.properties.reported.get("rebootTime")) else: print ("Waiting for device to report last reboot time...") time.sleep(5) status_counter += 1 except Exception as ex: print ( "" ) print ( "Unexpected error {0}".format(ex) ) return except KeyboardInterrupt: print ( "" ) print ( "IoTHubDeviceMethod sample stopped" ) if __name__ == '__main__': print ( "Starting the IoT Hub Service Client DeviceManagement Python sample..." ) print ( " Connection string = {0}".format(CONNECTION_STRING) ) print ( " Device ID = {0}".format(DEVICE_ID) ) iothub_devicemethod_sample_run()
-
Save and close the dmpatterns_getstarted_service.py file.
You're now ready to run the apps.
-
At the command prompt, run the following command to begin listening for the reboot direct method.
python dmpatterns_getstarted_device.py
-
At another command prompt, run the following command to trigger the remote reboot and query for the device twin to find the last reboot time.
python dmpatterns_getstarted_service.py
-
You see the device response to the direct method in the console.
The following shows the device response to the reboot direct method:
The following shows the service calling the reboot direct method and polling the device twin for status:
[!INCLUDE iot-hub-dm-followup]