了解和使用 Azure IoT 中樞的裝置對應項Understand and use device twins in IoT Hub

裝置對應項是存放裝置狀態資訊的 JSON 文件,包括中繼資料、組態和條件。Device twins are JSON documents that store device state information including metadata, configurations, and conditions. Azure IoT 中樞會為連線到 IoT 中樞的每個裝置維持裝置對應項。Azure IoT Hub maintains a device twin for each device that you connect to IoT Hub.

注意

這篇文章中所述的功能是僅適用於 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 IoT Hub tiers, see Choose the right IoT Hub tier.

本文章說明:This article describes:

  • 裝置對應項的結構:標籤所需屬性報告屬性The structure of the device twin: tags, desired and reported properties.
  • 裝置應用程式和後端可以對裝置對應項執行的作業。The operations that device apps and back ends can perform on device twins.

使用裝置對應項可以:Use device twins to:

  • 在雲端儲存裝置特定的中繼資料。Store device-specific metadata in the cloud. 例如,販賣機的部署位置。For example, the deployment location of a vending machine.

  • 從您的裝置應用程式報告目前狀態資訊,例如可用功能和狀況。Report current state information such as available capabilities and conditions from your device app. 例如,裝置會透過行動電話或 WiFi 連線到您的 IoT 中樞。For example, a device is connected to your IoT hub over cellular or WiFi.

  • 同步處理裝置與後端應用程式之間長時間執行之工作流程的狀態。Synchronize the state of long-running workflows between device app and back-end app. 例如,當解決方案後端指定要安裝的新韌體版本時,以及裝置應用程式報告更新處理程序的各個階段時。For example, when the solution back end specifies the new firmware version to install, and the device app reports the various stages of the update process.

  • 查詢裝置中繼資料、組態或狀態。Query your device metadata, configuration, or state.

請參閱裝置到雲端通訊指引,以取得有關使用報告屬性、裝置到雲端訊息或檔案上傳的指引。Refer to Device-to-cloud communication guidance for guidance on using reported properties, device-to-cloud messages, or file upload.

請參閱雲端對裝置通訊指引,以取得有關使用所需屬性、直接方法或雲端到裝置訊息的指引。Refer to Cloud-to-device communication guidance for guidance on using desired properties, direct methods, or cloud-to-device messages.

裝置對應項Device twins

裝置對應項會儲存裝置相關資訊,以供︰Device twins store device-related information that:

  • 裝置和後端用來同步處理裝置的狀況和組態。Device and back ends can use to synchronize device conditions and configuration.

  • 解決方案後端用來查詢和鎖定長時間執行的作業。The solution back end can use to query and target long-running operations.

裝置對應項的生命週期會連結至對應的裝置身分識別The lifecycle of a device twin is linked to the corresponding device identity. 在 IoT 中樞建立或刪除裝置身分識別時,會隱含地建立和刪除裝置對應項。Device twins are implicitly created and deleted when a device identity is created or deleted in IoT Hub.

裝置的兩個是 JSON 文件,其中含有︰A device twin is a JSON document that includes:

  • 標籤Tags. 解決方案後端可以讀取及寫入的 JSON 文件區段。A section of the JSON document that the solution back end can read from and write to. 裝置應用程式看不到標籤。Tags are not visible to device apps.

  • 所需屬性Desired properties. 搭配報告屬性使用,以便同步處理裝置的組態或狀況。Used along with reported properties to synchronize device configuration or conditions. 解決方案後端可以設定所需的屬性,以及裝置應用程式可以讀取它們。The solution back end can set desired properties, and the device app can read them. 裝置應用程式也可以接收所需屬性中的變更通知。The device app can also receive notifications of changes in the desired properties.

  • 報告屬性Reported properties. 搭配所需屬性使用,以便同步處理裝置的組態或狀況。Used along with desired properties to synchronize device configuration or conditions. 裝置應用程式可以設定報告的屬性,以及解決方案後端可以讀取並查詢它們。The device app can set reported properties, and the solution back end can read and query them.

  • 裝置身分識別屬性Device identity properties. 裝置對應項 JSON 文件的根目錄包含來自對應之裝置身分識別的唯讀屬性,此身分識別儲存在身分識別登錄中。The root of the device twin JSON document contains the read-only properties from the corresponding device identity stored in the identity registry.

裝置對應項屬性的螢幕擷取畫面

以下範例顯示裝置對應項 JSON 文件︰The following example shows a device twin JSON document:

{
    "deviceId": "devA",
    "etag": "AAAAAAAAAAc=", 
    "status": "enabled",
    "statusReason": "provisioned",
    "statusUpdateTime": "0001-01-01T00:00:00",
    "connectionState": "connected",
    "lastActivityTime": "2015-02-30T16:24:48.789Z",
    "cloudToDeviceMessageCount": 0, 
    "authenticationType": "sas",
    "x509Thumbprint": {     
        "primaryThumbprint": null, 
        "secondaryThumbprint": null 
    }, 
    "version": 2, 
    "tags": {
        "$etag": "123",
        "deploymentLocation": {
            "building": "43",
            "floor": "1"
        }
    },
    "properties": {
        "desired": {
            "telemetryConfig": {
                "sendFrequency": "5m"
            },
            "$metadata" : {...},
            "$version": 1
        },
        "reported": {
            "telemetryConfig": {
                "sendFrequency": "5m",
                "status": "success"
            },
            "batteryLevel": 55,
            "$metadata" : {...},
            "$version": 4
        }
    }
}

根物件中包含的是裝置身分識別屬性,以及 tagsreporteddesired 兩屬性的容器物件。In the root object are the device identity properties, and container objects for tags and both reported and desired properties. properties 容器包含一些唯讀元素 ($metadata$etag$version),其說明位於裝置對應項中繼資料開放式並行存取章節。The properties container contains some read-only elements ($metadata, $etag, and $version) described in the Device twin metadata and Optimistic concurrency sections.

報告屬性範例Reported property example

在上述範例中,裝置對應項包含由裝置應用程式所報告的 batteryLevel 屬性。In the previous example, the device twin contains a batteryLevel property that is reported by the device app. 此屬性可讓您根據最後一次報告的電池電量對裝置進行查詢和操作。This property makes it possible to query and operate on devices based on the last reported battery level. 其他範例包含裝置應用程式報告功能或連線能力選項。Other examples include the device app reporting device capabilities or connectivity options.

注意

當解決方案後端想要取得屬性的最後已知值時,報告屬性如何簡化這種情況。Reported properties simplify scenarios where the solution back end is interested in the last known value of a property. 如果解決方案後端需要以一連串時間戳記事件 (例如時間序列) 的形式處理裝置遙測,請使用裝置到雲端訊息Use device-to-cloud messages if the solution back end needs to process device telemetry in the form of sequences of timestamped events, such as time series.

所需屬性範例Desired property example

在上述範例中,解決方案後端和裝置應用程式會使用 telemetryConfig 裝置對應項的所需屬性和報告屬性,以同步處理此裝置的遙測組態。In the previous example, the telemetryConfig device twin desired and reported properties are used by the solution back end and the device app to synchronize the telemetry configuration for this device. 例如:For example:

  1. 解決方案後端會以所需組態值來設定所需屬性。The solution back end sets the desired property with the desired configuration value. 以下是含有所需屬性集的文件部分︰Here is the portion of the document with the desired property set:

    "desired": {
        "telemetryConfig": {
            "sendFrequency": "5m"
        },
        ...
    },
    
  2. 裝置應用程式會在已連線或第一次重新連線時,立即收到變更通知。The device app is notified of the change immediately if connected, or at the first reconnect. 裝置應用程式接著會報告更新的組態 (或使用 status 屬性的錯誤狀況)。The device app then reports the updated configuration (or an error condition using the status property). 以下是報告屬性的部分︰Here is the portion of the reported properties:

    "reported": {
        "telemetryConfig": {
            "sendFrequency": "5m",
            "status": "success"
        }
        ...
    }
    
  3. 解決方案後端可以查詢裝置對應項,以追蹤組態作業在許多裝置上的結果。The solution back end can track the results of the configuration operation across many devices by querying device twins.

注意

上述程式碼片段舉例說明了用來編碼裝置組態和其狀態的方式,為了方便閱讀,其內容已經過最佳化。The preceding snippets are examples, optimized for readability, of one way to encode a device configuration and its status. IoT 中樞不會對裝置對應項中的裝置對應項所需屬性和報告屬性強制實行特定結構描述。IoT Hub does not impose a specific schema for the device twin desired and reported properties in the device twins.

您可以使用裝置對應項來同步處理長時間執行的作業,例如韌體更新。You can use twins to synchronize long-running operations such as firmware updates. 如需如何使用屬性來跨裝置同步處理及追蹤長時間執行的作業,請參閱使用所需屬性來設定裝置For more information on how to use properties to synchronize and track a long running operation across devices, see Use desired properties to configure devices.

後端作業Back-end operations

解決方案後端會使用下列不可部分完成的作業 (透過 HTTPS 公開) 來對裝置對應項進行操作︰The solution back end operates on the device twin using the following atomic operations, exposed through HTTPS:

  • 依識別碼擷取裝置對應項Retrieve device twin by ID. 此作業會傳回裝置對應項文件,包括標籤以及所需屬性、報告屬性和系統屬性。This operation returns the device twin document, including tags and desired and reported system properties.

  • 部份更新裝置對應項Partially update device twin. 此作業可讓解決方案後端局部地更新裝置對應項中的標籤或所需屬性。This operation enables the solution back end to partially update the tags or desired properties in a device twin. 部分更新會以 JSON 文件的形式來表示,以新增或更新任何屬性。The partial update is expressed as a JSON document that adds or updates any property. 設定為 null 的屬性會遭到移除。Properties set to null are removed. 下列範例會以 {"newProperty": "newValue"} 值建立新的所需屬性、以 "otherNewValue" 覆寫 existingProperty 的現有值,並移除 otherOldPropertyThe following example creates a new desired property with value {"newProperty": "newValue"}, overwrites the existing value of existingProperty with "otherNewValue", and removes otherOldProperty. 不會對現有的所需屬性或標籤進行任何變更︰No other changes are made to existing desired properties or tags:

    {
         "properties": {
             "desired": {
                 "newProperty": {
                     "nestedProperty": "newValue"
                 },
                 "existingProperty": "otherNewValue",
                 "otherOldProperty": null
             }
         }
    }
    
  • 取代所需屬性Replace desired properties. 此作業可讓解決方案後端完全覆寫所有現有的所需屬性,並以新的 JSON 文件取代 properties/desiredThis operation enables the solution back end to completely overwrite all existing desired properties and substitute a new JSON document for properties/desired.

  • 取代標籤Replace tags. 此作業可讓解決方案後端完全覆寫所有現有的標籤,並以新的 JSON 文件取代 tagsThis operation enables the solution back end to completely overwrite all existing tags and substitute a new JSON document for tags.

  • 接收對應項通知Receive twin notifications. 這項作業可以在對應項修改時通知方案後端。This operation allows the solution back end to be notified when the twin is modified. 若要這樣做,您的 IoT 解決方案必須建立路由,並將資料來源設為等於 twinChangeEventsTo do so, your IoT solution needs to create a route and to set the Data Source equal to twinChangeEvents. 根據預設,預先不存在這類路由,因此不會傳送任何對應項通知。By default, no such routes pre-exist, so no twin notifications are sent. 如果變更率太高,或基於其他原因,例如內部失敗,IoT 中樞可能只會傳送一個包含所有變更的通知。If the rate of change is too high, or for other reasons such as internal failures, the IoT Hub might send only one notification that contains all changes. 因此,如果您的應用程式需要可靠地稽核和記錄所有中間狀態,您應該使用裝置到雲端的訊息。Therefore, if your application needs reliable auditing and logging of all intermediate states, you should use device-to-cloud messages. 對應項通知訊息包含屬性和內文。The twin notification message includes properties and body.

    • PropertiesProperties

      名稱Name Value
      $content-type$content-type application/jsonapplication/json
      $iothub-enqueuedtime$iothub-enqueuedtime 傳送通知的時間Time when the notification was sent
      $iothub-message-source$iothub-message-source twinChangeEventstwinChangeEvents
      $content-encoding$content-encoding utf-8utf-8
      deviceIddeviceId 裝置的識別碼ID of the device
      hubNamehubName IoT 中樞名稱Name of IoT Hub
      operationTimestampoperationTimestamp 作業的 ISO8601 時間戳記ISO8601 timestamp of operation
      iothub-message-schemaiothub-message-schema deviceLifecycleNotificationdeviceLifecycleNotification
      opTypeopType "replaceTwin" 或 "updateTwin""replaceTwin" or "updateTwin"

      訊息系統屬性前面會加上 $ 符號。Message system properties are prefixed with the $ symbol.

    • bodyBody

      本節包含所有對應項變更 (JSON 格式)。This section includes all the twin changes in a JSON format. 它使用的格式與修補程式的格式相同,差別在於它可以包含所有對應項區段︰tags、properties.reported、properties.desired,而且包含 “$metadata” 項目。It uses the same format as a patch, with the difference that it can contain all twin sections: tags, properties.reported, properties.desired, and that it contains the “$metadata” elements. 例如,For example,

      {
        "properties": {
            "desired": {
                "$metadata": {
                    "$lastUpdated": "2016-02-30T16:24:48.789Z"
                },
                "$version": 1
            },
            "reported": {
                "$metadata": {
                    "$lastUpdated": "2016-02-30T16:24:48.789Z"
                },
                "$version": 1
            }
        }
      }
      

上述所有作業皆支援開放式並行存取,而且需要 ServiceConnect 權限,如控制 IoT 中樞的存取權中所定義。All the preceding operations support Optimistic concurrency and require the ServiceConnect permission, as defined in Control access to IoT Hub.

除了這些作業,解決方案後端還可以︰In addition to these operations, the solution back end can:

裝置作業Device operations

裝置應用程式會使用下列不可部分完成的作業來操作裝置對應項︰The device app operates on the device twin using the following atomic operations:

  • 擷取裝置對應項Retrieve device twin. 這項作業會針對目前連線的裝置傳回裝置對應項檔 (包括所需和報告的系統屬性)。This operation returns the device twin document (including desired and reported system properties) for the currently connected device. (裝置應用程式看不到標記)。(Tags are not visible to device apps.)

  • 部分更新的報告屬性Partially update reported properties. 此作業可針對目前連線裝置的報告屬性進行部分更新。This operation enables the partial update of the reported properties of the currently connected device. 此作業使用的 JSON 更新格式,與解決方案後端用於局部更新所需屬性的格式相同。This operation uses the same JSON update format that the solution back end uses for a partial update of desired properties.

  • 觀察所需屬性Observe desired properties. 目前連線的裝置可以選擇在所需屬性進行更新時收到通知。The currently connected device can choose to be notified of updates to the desired properties when they happen. 裝置會收到由解決方案後端執行的相同更新形式 (部分或完整取代)。The device receives the same form of update (partial or full replacement) executed by the solution back end.

上述所有作業都需要 DeviceConnect 權限,如控制 IoT 中樞的存取權中所定義。All the preceding operations require the DeviceConnect permission, as defined in Control Access to IoT Hub.

Azure IoT 裝置 SDK 可讓您透過許多語言和平台輕鬆使用上述作業。The Azure IoT device SDKs make it easy to use the preceding operations from many languages and platforms. 如需 IoT 中樞之所需屬性同步處理基元的詳細資訊,請參閱裝置重新連線流程For more information on the details of IoT Hub primitives for desired properties synchronization, see Device reconnection flow.

標籤和屬性格式Tags and properties format

標籤、所需屬性和報告屬性是具有下列限制的 JSON 物件:Tags, desired properties, and reported properties are JSON objects with the following restrictions:

  • JSON 物件中的所有索引鍵是區分大小寫的 64 個位元組的 UTF-8 UNICODE 字串。All keys in JSON objects are case-sensitive 64 bytes UTF-8 UNICODE strings. 允許的字元會排除 UNICODE 控制字元 (區段 C0 和 C1),以及 .$ 和 SP。Allowed characters exclude UNICODE control characters (segments C0 and C1), and ., $, and SP.

  • JSON 物件中的所有值可以屬於下列 JSON 類型︰布林值、數字、字串、物件。All values in JSON objects can be of the following JSON types: boolean, number, string, object. 不允許使用陣列。Arrays are not allowed. 整數的最大值是 4503599627370495 和整數的最小值是 -4503599627370496。The maximum value for integers is 4503599627370495 and the minimum value for integers is -4503599627370496.

  • 標籤、所需屬性和報告屬性中所有 JSON 物件的深度上限為 5。All JSON objects in tags, desired, and reported properties can have a maximum depth of 5. 例如,下列物件有效:For instance, the following object is valid:

    {
         ...
         "tags": {
             "one": {
                 "two": {
                     "three": {
                         "four": {
                             "five": {
                                 "property": "value"
                             }
                         }
                     }
                 }
             }
         },
         ...
    }
    
  • 所有字串值的最大長度為 512 個位元組。All string values can be at most 512 bytes in length.

裝置對應項大小Device twin size

「IoT 中樞」會對 tagsproperties/desiredproperties/reported 的個別總計值 (排除唯讀元素) 分別強制執行 8 KB 大小的限制。IoT Hub enforces an 8KB size limitation on each of the respective total values of tags, properties/desired, and properties/reported, excluding read-only elements.

大小的計算方式是計算所有字元的數量,並排除在字串常數之外的 UNICODE 控制字元 (區段 C0 和 C1) 和空格。The size is computed by counting all characters, excluding UNICODE control characters (segments C0 and C1) and spaces that are outside of string constants.

IoT 中樞會拒絕 (並出現錯誤) 將會讓這些文件的大小增加到超過限制的所有作業。IoT Hub rejects with an error all operations that would increase the size of those documents above the limit.

裝置對應項中繼資料Device twin metadata

IoT 中樞會為裝置對應項所需屬性和報告屬性的每個 JSON 物件保有上次更新的時間戳記。IoT Hub maintains the timestamp of the last update for each JSON object in device twin desired and reported properties. 時間戳記採用 UTC 格式,並以 ISO8601 格式 YYYY-MM-DDTHH:MM:SS.mmmZ 進行編碼。The timestamps are in UTC and encoded in the ISO8601 format YYYY-MM-DDTHH:MM:SS.mmmZ.

例如:For example:

{
    ...
    "properties": {
        "desired": {
            "telemetryConfig": {
                "sendFrequency": "5m"
            },
            "$metadata": {
                "telemetryConfig": {
                    "sendFrequency": {
                        "$lastUpdated": "2016-03-30T16:24:48.789Z"
                    },
                    "$lastUpdated": "2016-03-30T16:24:48.789Z"
                },
                "$lastUpdated": "2016-03-30T16:24:48.789Z"
            },
            "$version": 23
        },
        "reported": {
            "telemetryConfig": {
                "sendFrequency": "5m",
                "status": "success"
            },
            "batteryLevel": "55%",
            "$metadata": {
                "telemetryConfig": {
                    "sendFrequency": "5m",
                    "status": {
                        "$lastUpdated": "2016-03-31T16:35:48.789Z"
                    },
                    "$lastUpdated": "2016-03-31T16:35:48.789Z"
                },
                "batteryLevel": {
                    "$lastUpdated": "2016-04-01T16:35:48.789Z"
                },
                "$lastUpdated": "2016-04-01T16:24:48.789Z"
            },
            "$version": 123
        }
    }
    ...
}

此資訊會保留在每個層級 (而不只是 JSON 結構的分葉),以保留可移除物件索引鍵的更新。This information is kept at every level (not just the leaves of the JSON structure) to preserve updates that remove object keys.

開放式並行存取Optimistic concurrency

標籤、所需屬性和報告屬性全都支援開放式並行存取。Tags, desired, and reported properties all support optimistic concurrency. 依據 RFC7232,標籤會有一個 ETag 來表示該標籤的 JSON 表示法。Tags have an ETag, as per RFC7232, that represents the tag's JSON representation. 您可以從解決方案後端在條件式更新作業中使用 ETag,以確保一致性。You can use ETags in conditional update operations from the solution back end to ensure consistency.

裝置對應項所需屬性和報告屬性沒有 ETag,但是有一定會遞增的 $version 值。Device twin desired and reported properties do not have ETags, but have a $version value that is guaranteed to be incremental. 類似於 ETag,更新端可以使用版本強制達到更新的一致性。Similarly to an ETag, the version can be used by the updating party to enforce consistency of updates. 例如,報告屬性的裝置應用程式或所需屬性的解決方案後端。For example, a device app for a reported property or the solution back end for a desired property.

當觀察端代理程式 (例如,觀察所需屬性的裝置應用程式) 必須協調擷取作業結果與更新通知之間的競爭情況時,版本也相當有用。Versions are also useful when an observing agent (such as the device app observing the desired properties) must reconcile races between the result of a retrieve operation and an update notification. 裝置重新連線流程一節會提供詳細資訊。The Device reconnection flow section provides more information.

裝置重新連線流程Device reconnection flow

IoT 中樞不會保留已中斷連線之裝置的所需屬性更新通知。IoT Hub does not preserve desired properties update notifications for disconnected devices. 因此,連線的裝置必須擷取完整的所需屬性文件,並訂閱更新通知。It follows that a device that is connecting must retrieve the full desired properties document, in addition to subscribing for update notifications. 由於更新通知和完整擷取之間可能會有競爭情況,因此必須確保下列流程︰Given the possibility of races between update notifications and full retrieval, the following flow must be ensured:

  1. 裝置應用程式連線到 IoT 中樞。Device app connects to an IoT hub.
  2. 裝置應用程式訂閱所需屬性更新通知。Device app subscribes for desired properties update notifications.
  3. 裝置應用程式擷取所需屬性的完整文件。Device app retrieves the full document for desired properties.

裝置應用程式可以忽略 $version 小於或等於完整擷取文件版本的所有通知。The device app can ignore all notifications with $version less or equal than the version of the full retrieved document. IoT 中樞保證版本一定會遞增,因此這是可行的方法。This approach is possible because IoT Hub guarantees that versions always increment.

注意

Azure IoT 裝置 SDK 中已實作此邏輯。This logic is already implemented in the Azure IoT device SDKs. 只有當裝置應用程式無法使用任何 Azure IoT 裝置 SDK,因而必須直接為 MQTT 介面編寫程式時,此說明才有用。This description is useful only if the device app cannot use any of Azure IoT device SDKs and must program the MQTT interface directly.

其他參考資料Additional reference material

IoT 中樞開發人員指南中的其他參考主題包括︰Other reference topics in the IoT Hub developer guide include:

後續步驟Next steps

現在您已了解裝置對應項,接下來您可能會對下列 IoT 中樞開發人員指南主題感興趣︰Now you have learned about device twins, you may be interested in the following IoT Hub developer guide topics:

若要嘗試本文所述的一些概念,請參閱下列「IoT 中樞」教學課程:To try out some of the concepts described in this article, see the following IoT Hub tutorials: