共用方式為


開始使用裝置對應項目 (Java)

裝置對應項是存放裝置狀態資訊的 JSON 文件,包括中繼資料、設定和條件。 IoT 中樞 會保存每個連線裝置的裝置對應項。

注意

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

使用裝置對應項以:

  • 從解決方案後端儲存裝置元數據。

  • 從您的裝置應用程式報告目前的狀態資訊,例如可用的功能和條件,例如所使用的連線方法。

  • 同步處理裝置應用程式與後端應用程式之間長時間執行的工作流程狀態,例如韌體和組態更新。

  • 查詢您的裝置中繼資料、設定或狀態。

裝置對應項是針對同步處理和查詢裝置組態和條件所設計。 如需裝置對應項的詳細資訊,包括何時使用裝置對應項,請參閱 瞭解裝置對應項

IoT 中樞會儲存裝置對應項,其中包含下列元素:

  • 標籤。 裝置元數據只能由解決方案後端存取。

  • 預期屬性。 解決方案後端可修改的 JSON 物件,並可由裝置應用程式觀察。

  • 回報的屬性。 裝置應用程式可修改的 JSON 物件,並可由解決方案後端讀取。

標記和屬性不能包含數位,但可以包含巢狀物件。

下圖顯示裝置對應項組織:

裝置對應項概念圖表的螢幕快照。

此外,解決方案後端可以根據上述所有數據來查詢裝置對應項。 如需裝置對應項的詳細資訊,請參閱 瞭解裝置對應項。 如需查詢的詳細資訊,請參閱 IoT 中樞 查詢語言

本文章說明如何:

  • 使用模擬裝置應用程式,將其連線通道報告為裝置對應項上的報告屬性。

  • 使用先前建立之標籤和屬性的篩選,從後端應用程式查詢裝置。

在本文中,您會建立兩個 Java 控制台應用程式:

  • add-tags-query:可新增標籤和查詢裝置對應項的後端應用程式。
  • simulated-device:連線到 IoT 中樞的模擬裝置應用程式,並報告其連線狀況。

注意

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

必要條件

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

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

  • Java SE 開發套件 8。 請務必選取 [長期支援] 下的 [Java 8],以取得 JDK 8 的下載。

  • Maven 3

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

取得 IoT 中樞連接字串

在本文中,您會建立後端服務,以將所需的屬性新增至裝置對應項,然後查詢身分識別登錄,以尋找已據此更新之報告屬性的所有裝置。 您的服務需要 服務連線 許可權,才能修改裝置對應項的所需屬性,而且需要 登錄讀取 許可權才能查詢身分識別登錄。 沒有預設的共用存取原則只包含這兩個許可權,因此您需要建立一個許可權。

若要建立共用存取原則,授與服務連線和登錄讀取許可權,並取得此原則的 連接字串,請遵循下列步驟:

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

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

  3. 從原則清單上方的頂端功能表中,選取 [ 新增共用原則存取原則]。

  4. 在右側的 [ 新增共用存取原則 ] 窗格中,輸入原則的描述性名稱,例如 serviceAndRegistryRead。 在 [許可權] 底下,選取 [登錄讀取和服務 連線],然後選取 [新增]。

    顯示如何新增共用存取原則的螢幕快照。

  5. 從原則清單中選取您的新原則。

  6. 選取主要 連接字串複製圖示,然後儲存值。

    顯示如何擷取 連接字串的螢幕快照。

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

建立更新報告屬性的裝置應用程式

在本節中,您會建立 Java 控制台應用程式,以 myDeviceId 連線到您的中樞,然後更新其裝置對應項的報告屬性,以確認其已使用行動數據網路連線。

  1. iot-java-twin-getstarted 資料夾中,於命令提示字元使用下列命令建立名為 simulated-device 的 Maven 專案:

    mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=simulated-device -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
    
  2. 在命令提示字元中,流覽至 simulated-device 資料夾。

  3. 使用文本編輯器,開啟 simulated-device 資料夾中的 pom.xml 檔案,並將下列相依性新增至相依性節點。 此相依性可讓您在應用程式中使用 iot-device-client 套件來與 IoT 中樞通訊。

    <dependency>
      <groupId>com.microsoft.azure.sdk.iot</groupId>
      <artifactId>iot-device-client</artifactId>
      <version>1.17.5</version>
    </dependency>
    

    注意

    您可以使用 Maven 搜尋來檢查最新版本的 iot-device-client。

  4. 將下列相依性新增至 相依性 節點。 此相依性會設定 Apache SLF4J 記錄外觀的 NOP,由裝置用戶端 SDK 用來實作記錄。 此設定是選擇性的,但是,如果您省略它,當您執行應用程式時,可能會在控制台中看到警告。 如需在裝置用戶端 SDK 中記錄的詳細資訊,請參閱 Azure IoT 裝置 SDK for Java 自述檔範例中的記錄

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-nop</artifactId>
      <version>1.7.28</version>
    </dependency>
    
  5. 在相依性節點之後新增下列組建節點。 這個設定會指示 Maven 使用 Java 1.8 建置應用程式:

    <build>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.3</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
          </configuration>
        </plugin>
      </plugins>
    </build>
    
  6. 儲存並關閉 pom.xml 檔案。

  7. 使用文本編輯器,開啟 simulated-device\src\main\java\com\mycompany\app\App.java 檔案。

  8. 將下列 import 語句新增至 檔案:

    import com.microsoft.azure.sdk.iot.device.*;
    import com.microsoft.azure.sdk.iot.device.DeviceTwin.*;
    
    import java.io.IOException;
    import java.net.URISyntaxException;
    import java.util.Scanner;
    
  9. 將下列類別層級變數新增至 App 類別。 將 取代{yourdeviceconnectionstring}為您在 IoT 中樞 中註冊裝置時看到的裝置 連接字串:

    private static String connString = "{yourdeviceconnectionstring}";
    private static IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
    private static String deviceId = "myDeviceId";
    

    此範例應用程式會在具現化 DeviceClient 物件時使用通訊協定變數。

  10. 將下列方法新增至 App 類別,以列印對應項更新的相關信息:

    protected static class DeviceTwinStatusCallBack implements IotHubEventCallback {
        @Override
        public void execute(IotHubStatusCode status, Object context) {
          System.out.println("IoT Hub responded to device twin operation with status " + status.name());
        }
      }
    
  11. 將 main 方法中的程式代碼取代為下列程式代碼:

    • 建立裝置用戶端以與 IoT 中樞 通訊。

    • 建立 Device 對象來儲存裝置對應項屬性。

    DeviceClient client = new DeviceClient(connString, protocol);
    
    // Create a Device object to store the device twin properties
    Device dataCollector = new Device() {
      // Print details when a property value changes
      @Override
      public void PropertyCall(String propertyKey, Object propertyValue, Object context) {
        System.out.println(propertyKey + " changed to " + propertyValue);
      }
    };
    
  12. 將下列程式代碼新增至main方法,以建立 connectivityType 報告屬性,並將它傳送至 IoT 中樞:

    try {
      // Open the DeviceClient and start the device twin services.
      client.open();
      client.startDeviceTwin(new DeviceTwinStatusCallBack(), null, dataCollector, null);
    
      // Create a reported property and send it to your IoT hub.
      dataCollector.setReportedProp(new Property("connectivityType", "cellular"));
      client.sendReportedProperties(dataCollector.getReportedProp());
    }
    catch (Exception e) {
      System.out.println("On exception, shutting down \n" + " Cause: " + e.getCause() + " \n" + e.getMessage());
      dataCollector.clean();
      client.closeNow();
      System.out.println("Shutting down...");
    }
    
  13. 將下列程式代碼新增至main方法的結尾。 等候 Enter 鍵可讓 IoT 中樞 時間報告裝置對應項作業的狀態。

    System.out.println("Press any key to exit...");
    
    Scanner scanner = new Scanner(System.in);
    scanner.nextLine();
    
    dataCollector.clean();
    client.close();
    
  14. 修改 main 方法的簽章,以包含例外狀況,如下所示:

    public static void main(String[] args) throws URISyntaxException, IOException
    
  15. 儲存並關閉 simulated-device\src\main\java\com\mycompany\app\App.java 檔案。

  16. 建置 simulated-device 應用程式並更正任何錯誤。 在命令提示字元中,流覽至 simulated-device 資料夾,然後執行下列命令:

    mvn clean package -DskipTests
    

建立可更新所需屬性和查詢對應項的服務應用程式

在本節中,您會建立 Java 應用程式,將位置元數據新增為標籤至與 myDeviceId 相關聯的裝置對應項 IoT 中樞。 應用程式會針對位於美國的裝置查詢IoT中樞,然後查詢報告行動數據網路連線的裝置。

  1. 在您的開發計算機上,建立名為 iot-java-twin-getstarted 的空白資料夾。

  2. iot-java-twin-getstarted 資料夾中,於命令提示字元使用下列命令建立名為 add-tags-query 的 Maven 專案:

    mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=add-tags-query -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
    
  3. 在命令提示字元中,流覽至 add-tags-query 資料夾。

  4. 使用文本編輯器,開啟 add-tags-query 資料夾中的 pom.xml 檔案,並將下列相依性新增至相依性節點。 此相依性可讓您在應用程式中使用 iot-service-client 套件來與 IoT 中樞通訊:

    <dependency>
      <groupId>com.microsoft.azure.sdk.iot</groupId>
      <artifactId>iot-service-client</artifactId>
      <version>1.17.1</version>
      <type>jar</type>
    </dependency>
    

    注意

    您可以使用 Maven 搜尋來檢查最新版的 iot-service-client

  5. 在相依性節點之後新增下列組建節點。 此設定會指示 Maven 使用 Java 1.8 來建置應用程式。

    <build>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.3</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
          </configuration>
        </plugin>
      </plugins>
    </build>
    
  6. 儲存並關閉 pom.xml 檔案。

  7. 使用文本編輯器,開啟 add-tags-query\src\main\java\com\mycompany\app\App.java 檔案。

  8. 將下列 import 語句新增至 檔案:

    import com.microsoft.azure.sdk.iot.service.devicetwin.*;
    import com.microsoft.azure.sdk.iot.service.exceptions.IotHubException;
    
    import java.io.IOException;
    import java.util.HashSet;
    import java.util.Set;
    
  9. 將下列類別層級變數新增至 App 類別。 將 取代{youriothubconnectionstring}為您在取得IoT中樞 連接字串 中複製的IoT中樞 連接字串

    public static final String iotHubConnectionString = "{youriothubconnectionstring}";
    public static final String deviceId = "myDeviceId";
    
    public static final String region = "US";
    public static final String plant = "Redmond43";
    
  10. 更新 main 方法簽章以包含下列throws子句:

    public static void main( String[] args ) throws IOException
    
  11. 使用下列程序代碼取代 main 方法中的程式代碼,以建立 DeviceTwin 和 DeviceTwinDevice 物件。 DeviceTwin 物件會處理與 IoT 中樞的通訊。 DeviceTwinDevice 物件代表裝置對應項及其屬性和標記:

    // Get the DeviceTwin and DeviceTwinDevice objects
    DeviceTwin twinClient = DeviceTwin.createFromConnectionString(iotHubConnectionString);
    DeviceTwinDevice device = new DeviceTwinDevice(deviceId);
    
  12. 將下列 try/catch 區塊新增至 main 方法:

    try {
      // Code goes here
    } catch (IotHubException e) {
      System.out.println(e.getMessage());
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
    
  13. 若要更新 裝置對應項中的區域植物 裝置對應項標籤,請在 區塊中 try 新增下列程序代碼:

    // Get the device twin from IoT Hub
    System.out.println("Device twin before update:");
    twinClient.getTwin(device);
    System.out.println(device);
    
    // Update device twin tags if they are different
    // from the existing values
    String currentTags = device.tagsToString();
    if ((!currentTags.contains("region=" + region) && !currentTags.contains("plant=" + plant))) {
      // Create the tags and attach them to the DeviceTwinDevice object
      Set<Pair> tags = new HashSet<Pair>();
      tags.add(new Pair("region", region));
      tags.add(new Pair("plant", plant));
      device.setTags(tags);
    
      // Update the device twin in IoT Hub
      System.out.println("Updating device twin");
      twinClient.updateTwin(device);
    }
    
    // Retrieve the device twin with the tag values from IoT Hub
    System.out.println("Device twin after update:");
    twinClient.getTwin(device);
    System.out.println(device);
    
  14. 若要查詢 IoT 中樞中的裝置對應項,請在您在上一個步驟中新增的程式代碼之後,將下列程式代碼新增至 try 區塊。 程式代碼會執行兩個查詢。 每個查詢最多會傳回 100 部裝置。

    // Query the device twins in IoT Hub
    System.out.println("Devices in Redmond:");
    
    // Construct the query
    SqlQuery sqlQuery = SqlQuery.createSqlQuery("*", SqlQuery.FromType.DEVICES, "tags.plant='Redmond43'", null);
    
    // Run the query, returning a maximum of 100 devices
    Query twinQuery = twinClient.queryTwin(sqlQuery.getQuery(), 100);
    while (twinClient.hasNextDeviceTwin(twinQuery)) {
      DeviceTwinDevice d = twinClient.getNextDeviceTwin(twinQuery);
      System.out.println(d.getDeviceId());
    }
    
    System.out.println("Devices in Redmond using a cellular network:");
    
    // Construct the query
    sqlQuery = SqlQuery.createSqlQuery("*", SqlQuery.FromType.DEVICES, "tags.plant='Redmond43' AND properties.reported.connectivityType = 'cellular'", null);
    
    // Run the query, returning a maximum of 100 devices
    twinQuery = twinClient.queryTwin(sqlQuery.getQuery(), 3);
    while (twinClient.hasNextDeviceTwin(twinQuery)) {
      DeviceTwinDevice d = twinClient.getNextDeviceTwin(twinQuery);
      System.out.println(d.getDeviceId());
    }
    
  15. 儲存並關閉 add-tags-query\src\main\java\com\mycompany\app\App.java 檔案

  16. 建置 add-tags-query 應用程式並更正任何錯誤。 在命令提示字元中,流覽至 add-tags-query 資料夾,然後執行下列命令:

    mvn clean package -DskipTests
    

執行應用程式

您現在已準備好執行主控台應用程式。

  1. 在 add-tags-query 資料夾中的命令提示字元中,執行下列命令以執行 add-tags-query 服務應用程式:

    mvn exec:java -Dexec.mainClass="com.mycompany.app.App"
    

    顯示命令輸出以執行新增標籤查詢服務應用程式的螢幕快照。

    您可以看到 新增至裝置對應項的工廠區域 標籤。 第一個查詢會傳回您的裝置,但第二個查詢不會傳回。

  2. 在 simulated-device 資料夾中的命令提示字元中,執行下列命令,將 connectivityType 報告屬性新增至裝置對應項:

    mvn exec:java -Dexec.mainClass="com.mycompany.app.App"
    

    裝置用戶端會新增連線類型報告屬性

  3. 在 add-tags-query 資料夾中的命令提示字元中,執行下列命令,第二次執行 add-tags-query 服務應用程式:

    mvn exec:java -Dexec.mainClass="com.mycompany.app.App"
    

    Java IoT 中樞 服務應用程式來更新標籤並執行裝置查詢

    現在您的裝置已將 connectivityType 屬性傳送至 IoT 中樞,第二個查詢會傳回您的裝置。

在本文章中,您將:

  • 已從後端應用程式新增裝置元數據作為標籤
  • 裝置對應項中回報的裝置連線資訊
  • 使用類似 SQL 的 IoT 中樞 查詢語言來查詢裝置對應項資訊

下一步

若要了解如何: