设备管理入门 (Python)Get started with device management (Python)

后端应用可以使用 Azure IoT 中心基元(例如设备孪生直接方法)远程启动和监视设备上的设备管理操作。Back-end apps can use Azure IoT Hub primitives, such as device twin and direct methods, to remotely start and monitor device management actions on devices. 本教程说明后端应用和设备应用如何协同工作,以便使用 IoT 中心发起远程设备重启操作并对其进行监视。This tutorial shows you how a back-end app and a device app can work together to initiate and monitor a remote device reboot using IoT Hub.

Note

本文介绍的功能仅在 IoT 中心的标准层中可用。The features described in this article are available only in the standard tier of IoT Hub. 有关基本和标准/免费 IoT 中心层的详细信息,请参阅选择合适的 IoT 中心层For more information about the basic and standard/free IoT Hub tiers, see Choose the right IoT Hub tier.

使用直接方法可从云中的后端应用启动设备管理操作(例如重新启动、恢复出厂设置以及固件更新)。Use a direct method to initiate device management actions (such as reboot, factory reset, and firmware update) from a back-end app in the cloud. 设备负责以下操作:The device is responsible for:

  • 处理从 IoT 中心发送的方法请求。Handling the method request sent from IoT Hub.
  • 在设备上启动相应的设备特定操作。Initiating the corresponding device-specific action on the device.
  • 通过向 IoT 中心报告的属性,提供状态更新。Providing status updates through reported properties to IoT Hub.

可以使用云中的后端应用运行设备孪生查询,以报告设备管理操作的进度。You can use a back-end app in the cloud to run device twin queries to report on the progress of your device management actions.

本教程演示如何:This tutorial shows you how to:

  • 使用 Azure 门户创建 IoT 中心,以及如何在 IoT 中心创建设备标识。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.
  • 创建一个 Python 控制台应用,它通过 IoT 中心调用模拟设备应用中的重新启动直接方法。Create a Python console app that calls the reboot direct method in the simulated device app through your IoT hub.

在本教程结束时,会获得两个 Python 控制台应用:At the end of this tutorial, you have two Python console apps:

  • dmpatterns_getstarted_device.py,它使用先前创建的设备标识连接到 IoT 中心,接收重新启动直接方法,模拟物理重新启动,并报告上次重新启动的时间。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,它调用模拟设备应用中的直接方法,显示响应,并显示更新后的报告属性。dmpatterns_getstarted_service.py, which calls a direct method in the simulated device app, displays the response, and displays the updated reported properties.

Note

IoT 中心通过 Azure IoT 设备 SDK 为许多设备平台和语言(包括 C、Java、Javascript 和 Python)提供 SDK 支持。IoT Hub has SDK support for many device platforms and languages (including C, Java, Javascript, and Python) through Azure IoT device SDKs. 有关如何使用 Python 将设备连接到本教程的代码,以及通常如何连接到 Azure IoT 中心的说明,请参阅 Azure IoT Python SDKFor instructions on how to use Python to connect your device to this tutorial's code, and generally to Azure IoT Hub, see the Azure IoT Python SDK.

必备条件Prerequisites

  • 确保已在防火墙中打开端口 8883。Make sure that port 8883 is open in your firewall. 本文中的设备示例使用 MQTT 协议,该协议通过端口 8883 进行通信。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. 有关解决此问题的更多信息和方法,请参阅连接到 IoT 中心(MQTT)For more information and ways to work around this issue, see Connecting to IoT Hub (MQTT).

创建 IoT 中心Create an IoT hub

此部分介绍如何使用 Azure 门户创建 IoT 中心。This section describes how to create an IoT hub using the Azure portal.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 从 Azure 主页中选择“+ 创建资源”按钮,然后在“搜索市场”字段中输入“IoT 中心”。 From the Azure homepage, select the + Create a resource button, and then enter IoT Hub in the Search the Marketplace field.

  3. 在搜索结果中选择“IoT 中心”,然后选择“创建” 。Select IoT Hub from the search results, and then select Create.

  4. 在“基本信息”选项卡上,按如下所示填写字段: On the Basics tab, complete the fields as follows:

    • 订阅:选择要用于中心的订阅。Subscription: Select the subscription to use for your hub.

    • 资源组:选择一个资源组或新建一个资源组。Resource Group: Select a resource group or create a new one. 若要新建资源组,请选择“新建”并填写要使用的名称。 To create a new one, select Create new and fill in the name you want to use. 若要使用现有的资源组,请选择它。To use an existing resource group, select that resource group. 有关详细信息,请参阅管理 Azure 资源管理器资源组For more information, see Manage Azure Resource Manager resource groups.

    • 区域:选择中心所在的区域。Region: Select the region in which you want your hub to be located. 选择最靠近你的位置。Select the location closest to you.

    • IoT 中心名称:输入中心的名称。IoT Hub Name: Enter a name for your hub. 此名称必须全局唯一。This name must be globally unique. 如果输入的名称可用,会显示一个绿色复选标记。If the name you enter is available, a green check mark appears.

    Important

    IoT 中心将公开为 DNS 终结点,因此,命名时请务必避免包含任何敏感信息。The IoT hub will be publicly discoverable as a DNS endpoint, so make sure to avoid any sensitive information while naming it.

    在 Azure 门户中创建中心

  5. 在完成时选择“下一步: 大小和规模”,以继续创建中心。Select Next: Size and scale to continue creating your hub.

    使用 Azure 门户为新的中心设置大小和规模

    在此屏幕中可以设置以下值:This screen allows you to set the following values:

    • 定价和缩放层:选择的层。Pricing and scale tier: Your selected tier. 可以根据你需要的功能数以及每天通过解决方案发送的消息数从多个层级中进行选择。You can choose from several tiers, depending on how many features you want and how many messages you send through your solution per day. 免费层适用于测试和评估。The free tier is intended for testing and evaluation. 允许 500 台设备连接到中心,每天最多可传输 8,000 条消息。It allows 500 devices to be connected to the hub and up to 8,000 messages per day. 每个 Azure 订阅可以在免费层中创建一个 IoT 中心。Each Azure subscription can create one IoT Hub in the free tier.

    • IoT 中心单元:每个单位每日允许的消息数取决于中心的定价层。IoT Hub units: The number of messages allowed per unit per day depends on your hub's pricing tier. 例如,如果希望中心支持 700,000 条消息引入,请选择两个 S1 层单位。For example, if you want the hub to support ingress of 700,000 messages, you choose two S1 tier units. 有关其他层选项的详细信息,请参阅选择合适的 IoT 中心层For details about the other tier options, see Choosing the right IoT Hub tier.

    • 高级设置 > 设备到云的分区:此属性将设备到云消息与这些消息的同步读取器数目相关联。Advanced Settings > Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. 大多数中心只需要 4 个分区。Most hubs need only four partitions.

  6. 对于本文,请接受默认选项,然后选择“查看 + 创建”以查看所做的选择。 For this article, accept the default choices, and then select Review + create to review your choices. 会显示类似于以下的屏幕。You see something similar to this screen.

    查看用于创建新中心的信息

  7. 选择“创建”以创建新的中心 。Select Create to create your new hub. 创建中心需要几分钟时间。Creating the hub takes a few minutes.

在 IoT 中心内注册新设备Register a new device in the IoT hub

在本部分中,将使用 Azure CLI 为本文创建设备标识。In this section, you use the Azure CLI to create a device identity for this article. 设备 ID 区分大小写。Device IDs are case sensitive.

  1. 运行以下命令以安装适用于 Azure CLI 的 Microsoft Azure IoT 扩展:Run the following command to install the Microsoft Azure IoT Extension for Azure CLI:

    az extension add --name azure-cli-iot-ext
    
  2. 使用以下命令创建一个名为 myDeviceId 的新设备标识并检索设备连接字符串:Create a new device identity called myDeviceId and retrieve the device connection string with these commands:

    az iot hub device-identity create --device-id myDeviceId --hub-name {Your IoT Hub name}
    az iot hub device-identity show-connection-string --device-id myDeviceId --hub-name {Your IoT Hub name} -o table
    

    Important

    收集的日志中可能会显示设备 ID 用于客户支持和故障排除,因此,在为日志命名时,请务必避免包含任何敏感信息。The device ID may be visible in the logs collected for customer support and troubleshooting, so make sure to avoid any sensitive information while naming it.

记下结果中的设备连接字符串。Make a note of the device connection string from the result. 设备应用使用此设备连接字符串以设备身份连接到 IoT 中心。This device connection string is used by the device app to connect to your IoT Hub as a device.

创建模拟设备应用程序Create a simulated device app

本部分的操作:In this section, you:

  • 创建一个 Python 控制台应用,用于响应通过云调用的直接方法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
  1. 在命令提示符处,运行以下命令以安装 azure-iot-device 包:At your command prompt, run the following command to install the azure-iot-device package:

    pip install azure-iot-device
    
  2. 使用文本编辑器,在工作目录中创建名为 dmpatterns_getstarted_device.py 的文件。Using a text editor, create a file named dmpatterns_getstarted_device.py in your working directory.

  3. importdmpatterns_getstarted_device.py文件开头添加以下 语句。Add the following import statements at the start of the dmpatterns_getstarted_device.py file.

    import threading
    import time
    import datetime
    from azure.iot.device import IoTHubDeviceClient, MethodResponse
    
  4. 添加 CONNECTION_STRING 变量。Add the CONNECTION_STRING variable. {deviceConnectionString} 占位符值替换为设备连接字符串。Replace the {deviceConnectionString} placeholder value with your device connection string. 你先前在在 IoT 中心注册新设备中复制了此连接字符串。You copied this connection string previously in Register a new device in the IoT hub.

    CONNECTION_STRING = "{deviceConnectionString}"
    
  5. 添加以下函数回调,实现设备上的直接方法。Add the following function callbacks to implement the direct method on the device.

    def reboot_listener(client):
        while True:
            # Receive the direct method request
            method_request = client.receive_method_request("rebootDevice")  # blocking call
    
            # 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")
    
            # Send 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)
            client.send_method_response(method_response)
    
  6. 启动直接方法侦听器并等待。Start the direct method listener and wait.

    def iothub_client_init():
        client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
        return client
    
    def iothub_client_sample_run():
        try:
            client = iothub_client_init()
    
            # Start a thread listening for "rebootDevice" direct method invocations
            reboot_listener_thread = threading.Thread(target=reboot_listener, args=(client,))
            reboot_listener_thread.daemon = True
            reboot_listener_thread.start()
    
            while True:
                time.sleep(1000)
    
        except KeyboardInterrupt:
            print ( "IoTHubDeviceClient sample stopped" )
    
    if __name__ == '__main__':
        print ( "Starting the IoT Hub Python sample..." )
        print ( "IoTHubDeviceClient waiting for commands, press Ctrl-C to exit" )
    
        iothub_client_sample_run()
    
  7. 保存并关闭 dmpatterns_getstarted_device.py 文件。Save and close the dmpatterns_getstarted_device.py file.

Note

为简单起见,本教程不实现任何重试策略。To keep things simple, this tutorial does not implement any retry policy. 在生产代码中,应该按文章 Transient Fault Handling(暂时性故障处理)中所述实施重试策略(例如指数退避)。In production code, you should implement retry policies (such as an exponential backoff), as suggested in the article Transient Fault Handling.

获取 IoT 中心连接字符串Get the IoT hub connection string

在本文中,你将创建一个在设备上调用直接方法的后端服务。In this article, you create a backend service that invokes a direct method on a device. 若要通过 IoT 中心在设备上调用直接方法,服务需要“服务连接” 权限。To invoke a direct method on a device through IoT Hub, your service needs the service connect permission. 默认情况下,每个 IoT 中心都使用名为 service 的共享访问策略创建,该策略授予此权限。By default, every IoT Hub is created with a shared access policy named service that grants this permission.

若要获取 service 策略的 IoT 中心连接字符串,请执行以下步骤:To get the IoT Hub connection string for the service policy, follow these steps:

  1. Azure 门户中,选择“资源组” 。In the Azure portal, select Resource groups. 选择中心所在的资源组,然后从资源列表中选择中心。Select the resource group where your hub is located, and then select your hub from the list of resources.

  2. 在 IoT 中心的左侧窗格中,选择“共享访问策略” 。On the left-side pane of your IoT hub, select Shared access policies.

  3. 从策略列表中选择“service” 策略。From the list of policies, select the service policy.

  4. 在“共享访问密钥” 下,选择“连接字符串 - 主密钥” 所对应的“复制”图标并保存该值。Under Shared access keys, select the copy icon for the Connection string -- primary key and save the value.

    显示如何检索连接字符串

有关 IoT 中心共享访问策略和权限的详细信息,请参阅访问控制和权限For more information about IoT Hub shared access policies and permissions, see Access control and permissions.

使用直接方法在设备上触发远程重新启动Trigger a remote reboot on the device using a direct method

此部分将创建一个 Python 控制台应用,以使用直接方法在设备上启动远程重新启动。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.

  1. 在命令提示符处,运行以下命令以安装 azure-iot-hub 包:At your command prompt, run the following command to install the azure-iot-hub package:

    pip install azure-iot-hub
    
  2. 使用文本编辑器,在工作目录中创建名为 dmpatterns_getstarted_service.py 的文件。Using a text editor, create a file named dmpatterns_getstarted_service.py in your working directory.

  3. dmpatterns_getstarted_service.py 文件开头添加以下 import 语句。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
    
  4. 添加以下变量声明。Add the following variable declarations. {IoTHubConnectionString} 占位符值替换为先前在获取 IoT 中心连接字符串中复制的 IoT 中心连接字符串。Replace the {IoTHubConnectionString} placeholder value with the IoT hub connection string you copied previously in Get the IoT hub connection string. {deviceId} 占位符值替换为在在 IoT 中心注册新设备中注册的设备 ID。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
    
  5. 添加以下函数以调用设备方法重新启动目标设备,然后查询设备孪生并获取上次重新启动时间。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()
    
  6. 保存并关闭 dmpatterns_getstarted_service.py 文件。Save and close the dmpatterns_getstarted_service.py file.

运行应用Run the apps

现已准备好运行应用。You're now ready to run the apps.

  1. 在命令提示符处,运行以下命令以开始侦听重新启动直接方法。At the command prompt, run the following command to begin listening for the reboot direct method.

    python dmpatterns_getstarted_device.py
    
  2. 在另一个命令提示符处,运行以下命令以触发远程重新启动并查询设备孪生以查找上次重新启动时间。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
    
  3. 可在控制台查看对直接方法的设备响应。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:

    触发重新启动服务输出

自定义和扩展设备管理操作Customize and extend the device management actions

IoT 解决方案可扩展已定义的设备管理模式集,或通过使用设备孪生和云到设备方法基元启用自定义模式。Your IoT solutions can expand the defined set of device management patterns or enable custom patterns by using the device twin and cloud-to-device method primitives. 设备管理操作的其他示例包括恢复出厂设置、固件更新、软件更新、电源管理、网络和连接管理以及数据加密。Other examples of device management actions include factory reset, firmware update, software update, power management, network and connectivity management, and data encryption.

设备维护时段Device maintenance windows

通常情况下,将设备配置为在某一时间执行操作,以最大程度减少中断和停机时间。Typically, you configure devices to perform actions at a time that minimizes interruptions and downtime. 设备维护时段是一种常用模式,用于定义设备应更新其配置的时间。Device maintenance windows are a commonly used pattern to define the time when a device should update its configuration. 后端解决方案使用设备孪生所需属性在设备上定义并激活策略,以启用维护时段。Your back-end solutions can use the desired properties of the device twin to define and activate a policy on your device that enables a maintenance window. 当设备收到维护时段策略时,它可以使用设备孪生报告属性报告策略状态。When a device receives the maintenance window policy, it can use the reported property of the device twin to report the status of the policy. 然后,后端应用可以使用设备孪生查询来证明设备和每个策略的符合性。The back-end app can then use device twin queries to attest to compliance of devices and each policy.

后续步骤Next steps

本教程使用直接方法触发设备上的远程重新启动。In this tutorial, you used a direct method to trigger a remote reboot on a device. 使用报告属性报告设备上次重新启动时间,并查询设备孪生从云中发现设备上次重新启动时间。You used the reported properties to report the last reboot time from the device, and queried the device twin to discover the last reboot time of the device from the cloud.

若要继续完成 IoT 中心和设备管理模式(如远程无线固件更新)的入门内容,请参阅如何更新固件To continue getting started with IoT Hub and device management patterns such as remote over the air firmware update, see How to do a firmware update.

若要了解如何扩展 IoT 解决方案并在多个设备上计划方法调用,请参阅计划和广播作业To learn how to extend your IoT solution and schedule method calls on multiple devices, see Schedule and broadcast jobs.