Share via


開始使用裝置管理 (Python)

後端應用程式可使用 Azure IoT 中樞基元 (例如裝置對應項直接方法),從遠端啟動並監視裝置上的裝置管理動作。 本文會示範後端應用程式和裝置應用程式如何共同運作,以使用 IoT 中樞初始化和監視遠端裝置重新啟動。

注意

本文中所述的功能僅適用於 IoT 中樞的標準層。 如需有關基本和標準/免費 Azure IoT 中樞階層的詳細資訊,請參閱為您的解決方案選擇適合的 Azure IoT 中樞階層

使用直接方法從雲端中的後端應用程式起始裝置管理動作 (例如重新啟動、恢復出廠預設值,以及韌體更新)。 該裝置將負責:

  • 處理從 IoT 中樞傳送的方法要求。

  • 在裝置上起始對應的裝置專有動作。

  • 透過針對 IoT 中樞的報告屬性提供狀態更新。

您可以在雲端中使用後端 App 來執行裝置對應項查詢,以報告裝置管理動作的進度。

本文說明如何建立:

  • dmpatterns_getstarted_device.py:一個模擬裝置應用程式,使用直接方法重新啟動裝置,並報告上次重新啟動時間。 直接方法是從雲端叫用。

  • dmpatterns_getstarted_service.py:一個 Python 主控台應用程式,透過您的 IoT 中樞在模擬裝置應用程式中呼叫直接方法。 會顯示回應和更新的回報屬性。

注意

如需可用來建置裝置和後端應用程式的 SDK 工具詳細資訊,請參閱 Azure IoT SDK

必要條件

  • 使用中的 Azure 帳戶。 (如果您沒有帳戶,只需要幾分鐘的時間就可以建立免費帳戶。)

  • IoT 中樞。 使用 CLIAzure 入口網站建立一個。

  • 已註冊的裝置。 在 Azure 入口網站中註冊一個。

  • 建議使用 Python 3.7 版或更新版本。 請務必使用安裝程式所需的 32 位元或 64 位元安裝。 在安裝期間出現系統提示時,務必將 Python 新增至平台特有的環境變數。

  • 請確定您的防火牆已開啟連接埠 8883。 本文中的裝置範例會使用 MQTT 通訊協定,其會透過連接埠 8883 進行通訊。 某些公司和教育網路環境可能會封鎖此連接埠。 如需此問題的詳細資訊和解決方法,請參閱連線至 IoT 中樞 (MQTT)

在 IoT 中樞註冊新的裝置

在本節中,您會使用 Azure CLI 建立本文中的裝置身分識別。 裝置識別碼會區分大小寫。

  1. 開啟 Azure Cloud Shell

  2. 在 Azure Cloud Shell 中執行下列命令,以安裝適用於 Azure CLI 的 Microsoft Azure IoT 延伸模組:

    az extension add --name azure-iot
    
  3. 建立稱為 myDeviceId 的新裝置身分識別,並使用下列命令擷取裝置連接字串:

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

    重要

    裝置識別碼可能會顯示在為了客戶支援和疑難排解而收集的記錄中,因此務必避免在命名時使用任何敏感性資訊。

記下結果中的裝置連接字串。 裝置應用程式會使用此裝置連接字串,以裝置的形式連接到您的 IoT 中樞。

使用直接方法建立裝置應用程式

在本節中,您會:

  • 建立 Python 主控台應用程式,以回應雲端所呼叫的直接方法。

  • 模擬裝置重新啟動。

  • 使用回報的屬性來啟用裝置對應項查詢,以識別裝置及其上次重新啟動時間。

在先前使用的 Azure Cloud Shell 中 (或使用 Python 的任何其他環境),建立裝置代碼。

  1. 在命令提示字元中,執行下列命令以安裝 azure-iot-device 套件:

    pip install azure-iot-device
    
  2. 使用文字編輯器,在工作目錄中建立名為 dmpatterns_getstarted_device.py 的檔案。

  3. dmpatterns_getstarted_device.py 檔案的開頭新增下列 import 陳述式。

    import time
    import datetime
    from azure.iot.device import IoTHubDeviceClient, MethodResponse
    
  4. 新增 CONNECTION_STRING 變數。 將 {deviceConnectionString} 預留位置值取代為裝置連接字串。 先前已於 在 IoT 中樞註冊新裝置中複製此連接字串。

    CONNECTION_STRING = "{deviceConnectionString}"
    
  5. 新增下列函式,以具現化針對裝置上直接方法設定的用戶端。

    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
    
  6. 啟動直接方法範例並等待。

    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()
    
  7. 儲存並關閉 dmpatterns_getstarted_device.py 檔案。

注意

為了簡單起見,本教學課程不會實作任何重試原則。 在生產環境程式碼中,您應該如暫時性錯誤處理一文中所建議,實作重試原則 (例如指數型輪詢)。

取得 IoT 中樞連接字串

在本文中,您會建立後端服務,在裝置上叫用直接方法。 若要透過 IoT 中樞在裝置上叫用直接方法,則服務需要有服務連線權限。 根據預設,每個 IoT 中樞都是透過授與此權限且名為服務的共用存取原則所建立。

若要取得服務原則的 IoT 中樞連接字串,請遵循下列步驟:

  1. Azure 入口網站中,選取 [資源群組]。 選取中樞所在的資源群組,然後從資源清單選取中樞。

  2. 在 IoT 中樞的左側窗格中,選取 [共用存取原則]

  3. 從原則清單中,選取服務原則。

  4. 複製 [主要連接字串] 並儲存該值。

Screenshot that shows how to retrieve the connection string from your IoT Hub in the Azure portal.

如需 IoT 中樞共用存取原則和權限的詳細資訊,請參閱存取控制及權限

建立服務應用程式以觸發重新啟動

在本節中,您會建立 Python 主控台應用程式,此應用程式會使用直接方法起始遠端重新開機。 應用程式使用裝置對應項查詢來探索該裝置的上次重新開機時間。

在 Azure Cloud Shell 或使用 Python 的任何其他環境中建立裝置程式碼。

  1. 在命令提示字元中,執行下列命令以安裝 azure-iot-hub 套件:

    pip install azure-iot-hub
    
  2. 使用文字編輯器,在工作目錄中建立名為 dmpatterns_getstarted_service.py 的檔案。

  3. dmpatterns_getstarted_service.py 檔案的開頭新增下列 import 陳述式。

    import sys, time
    
    from azure.iot.hub import IoTHubRegistryManager
    from azure.iot.hub.models import CloudToDeviceMethod, CloudToDeviceMethodResult, Twin
    
  4. 新增下列變數宣告。 將 {IoTHubConnectionString} 預留位置值取代為先前在取得 IoT 中樞連接字串內複製的 IoT 中樞連接字串。 將 {deviceId} 預留位置值取代為於 在 IoT 中樞註冊新裝置內註冊的裝置識別碼。

    CONNECTION_STRING = "{IoTHubConnectionString}"
    DEVICE_ID = "{deviceId}"
    
    METHOD_NAME = "rebootDevice"
    METHOD_PAYLOAD = "{\"method_number\":\"42\"}"
    TIMEOUT = 60
    WAIT_COUNT = 10
    
  5. 新增下列函式來叫用裝置方法,以重新啟動目標裝置,然後查詢裝置對應項並取得上次重新啟動時間。

    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 檔案。

執行應用程式

您現在已準備好執行裝置程式碼和服務程式碼,以起始裝置重新啟動。

  1. 在您用以建立裝置的命令提示字元中,執行下列命令以開始接聽重新啟動直接方法。

    python dmpatterns_getstarted_device.py
    
  2. 在您用以建立服務的命令提示字元中,執行下列命令以觸發裝置對應項的遠端重新啟動,以及查詢裝置對應項來尋找上次重新啟動的時間。

    python dmpatterns_getstarted_service.py
    
  3. 您會在主控台中看到直接方法的裝置回應。

    下列顯示 reboot 直接方法的裝置回應:

    Simulated device app output

    下列顯示服務呼叫 reboot 直接方法,並輪詢裝置對應項的狀態:

    Trigger reboot service output

自訂及延伸裝置管理動作

您的 IoT 解決方案可以透過使用裝置對應項和雲端到裝置方法基元,擴充一組已定義的裝置管理模式或啟用自訂模式。 其他裝置管理動作範例還包括恢復出廠預設值、韌體更新、軟體更新、電源管理、網路和連線管理,以及資料加密。

裝置維護期間

一般而言,您會設定讓裝置在產生最短中斷和停機時間的時機執行動作。 裝置維護期間是用來定義裝置組態更新時機的常用模式。 您的後端解決方案可以使用所需的裝置對應項 (twin) 屬性,在您的裝置上定義可啟用維護期間的原則並啟用該原則。 當裝置收到維護期間原則時,它可以使用回報的裝置對應項 (twin) 屬性來回報原則的狀態。 接著,後端 App 便可使用裝置對應項 (twin) 查詢來證明是否符合裝置及每個原則的規定。

下一步

在本文中,您使用了直接方法在裝置上觸發遠端重新啟動。 您已使用報告屬性來從裝置回報上次重新開機時間,以及查詢裝置對應項來從雲端探索裝置的上次重新開機時間。

若要繼續開始使用 IoT 中樞和裝置管理模式,例如端對端映像型更新,請參閱 Azure IoT 中樞裝置更新文章,使用 Raspberry Pi 3 B+ 參考映像

若要了解如何擴充 IoT 解決方案,以及在多部裝置上排程方法呼叫,請參閱排程及廣播作業