设备孪生入门 (Java)Get started with device twins (Java)

设备孪生是存储设备状态信息(元数据、配置和条件)的 JSON 文档。Device twins are JSON documents that store device state information (metadata, configurations, and conditions). IoT 中心为连接到它的每台设备保留一个设备孪生。IoT Hub persists a device twin for each device that connects to it.

Note

本文中所述的功能仅可在 IoT 中心的标准层中使用。The features described in this article are only available in the standard tier of IoT hub. 有关基本和标准 IoT 中心层的详细信息,请参阅如何选择合适的 IoT 中心层For more information about the basic and standard IoT Hub tiers, see How to choose the right IoT Hub tier.

使用设备孪生可以:Use device twins to:

  • 存储来自解决方案后端的设备元数据。Store device metadata from your solution back end.
  • 通过设备应用报告当前状态信息,例如可用功能和条件(例如,使用的连接方法)。Report current state information such as available capabilities and conditions (for example, the connectivity method used) from your device app.
  • 同步设备应用和后端应用之间的长时间运行的工作流的状态(例如固件和配置更新)。Synchronize the state of long-running workflows (such as firmware and configuration updates) between a device app and a back-end app.
  • 查询设备的元数据、配置或状态。Query your device metadata, configuration, or state.

设备孪生旨在执行同步以及查询设备的配置和条件。Device twins are designed for synchronization and for querying device configurations and conditions. 了解设备孪生中提供了有关何时使用设备孪生的详细信息。More information on when to use device twins can be found in Understand device twins.

设备孪生存储在 IoT 中心内,其中包含:Device twins are stored in an IoT hub and contain:

  • 标记,仅可由解决方案后端访问的设备元数据;tags, device metadata accessible only by the solution back end;
  • 所需属性,可以由解决方案后端修改以及由设备应用观察的 JSON 对象;以及desired properties, JSON objects modifiable by the solution back end and observable by the device app; and
  • 报告属性,可由设备应用修改以及由解决方案后端读取的 JSON 对象。reported properties, JSON objects modifiable by the device app and readable by the solution back end. 标记和属性不能包含数组,但可以嵌套对象。Tags and properties cannot contain arrays, but objects can be nested.

显示功能的设备孪生图像

此外,解决方案后端可以根据上述所有数据查询设备孪生。Additionally, the solution back end can query device twins based on all the above data. 有关设备孪生的详细信息,请参阅了解设备孪生,有关查询的信息,请参阅 IoT 中心查询语言参考。Refer to Understand device twins for more information about device twins, and to the IoT Hub query language reference for querying.

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

  • 创建将标记添加到设备孪生的后端应用,以及将其连接通道作为设备孪生上的报告属性进行报告的模拟设备应用。Create a back-end app that adds tags to a device twin, and a simulated device app that reports its connectivity channel as a reported property on the device twin.
  • 使用标记上的筛选器和之前创建的属性通过后端应用查询设备。Query devices from your back-end app using filters on the tags and properties previously created.

在本教程中,你将创建两个 Java 控制台应用:In this tutorial, you create two Java console apps:

  • add-tags-query:一个 Java 后端应用,用于添加标记并查询设备孪生。add-tags-query, a Java back-end app that adds tags and queries device twins.
  • simulated-device:Java 设备应用,它连接到 IoT 中心,并使用报告的属性报告其连接状态。simulated-device, a Java device app that connects to your IoT hub and reports its connectivity condition using a reported property.

Note

Azure IoT SDK 一文介绍了可用于构建设备和后端应用的 Azure IoT SDK。The article Azure IoT SDKs provides information about the Azure IoT SDKs that you can use to build both device and back-end apps.

要完成本教程,需要:To complete this tutorial, you need:

创建 IoT 中心Create an IoT hub

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

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

  2. 选择“+创建资源”,然后搜索市场,寻找 IoT 中心Choose +Create a resource, then Search the Marketplace for the IoT Hub.

  3. 选择“IoT 中心”,然后单击“创建”按钮 。Select IoT Hub and click the Create button. 随即显示 IoT 中心创建过程的第一个屏幕。You see the first screen for creating an IoT hub.

    在 Azure 门户中创建中心

    填充字段。Fill in the fields.

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

    资源组:可创建新的资源组或使用现有资源组。Resource Group: You can create a new resource group or use an existing one. 若要新建一个,请单击“新建” ,并填写要使用的名称。To create a new one, click Create new and fill in the name you want to use. 若要使用现有资源组,请单击“使用现有资源组” 并从下拉列表中选择该组。To use an existing resource group, click Use existing and select the resource group from the dropdown list. 有关详细信息,请参阅管理 Azure 资源管理器资源组For more information, see Manage Azure Resource Manager resource groups.

    区域:这是要在其中设置中心的区域。Region: This is the region in which you want your hub to be located. 从下拉列表中选择最靠近自己的位置。Select the location closest to you from the dropdown list.

    IoT 中心名称:输入 IoT 中心的名称。IoT Hub Name: Put in the name for your IoT 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.

  4. 单击“下一步: 大小和规模”,以便继续创建 IoT 中心。Click Next: Size and scale to continue creating your IoT hub.

    使用 Azure 门户为新的 IoT 中心设置大小和缩放级别

    在此屏幕上,可以采用默认值,只需在底部单击“查看+创建”即可 。On this screen, you can take the defaults and just click Review + create at the bottom.

    定价和缩放层:可以根据你需要的功能数以及每天通过解决方案发送的消息数从多个层中进行选择。Pricing and scale 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 台设备连接到 IoT 中心,并且每天最多传输 8,000 条信息。It allows 500 devices to be connected to the IoT 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. 例如,如果希望 IoT 中心支持 700,000 条消息输入,则选择两个 S1 层单位。For example, if you want the IoT 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 / Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. 大多数 IoT 中心只需要 4 个分区。Most IoT hubs only need four partitions.

  5. 单击“查看+创建” 可查看选择。Click Review + create to review your choices. 会显示类似于以下的屏幕。You see something similar to this screen.

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

  6. 单击“创建”以创建新的 IoT 中心 。Click Create to create your new IoT hub. 创建中心需要几分钟时间。Creating the hub takes a few minutes.

检索 IoT 中心的连接字符串Retrieve connection string for IoT hub

创建中心以后,请检索中心的连接字符串。After your hub has been created, retrieve the connection string for the hub. 该字符串用于将设备和应用程序连接到中心。This is used to connect devices and applications to your hub.

  1. 单击中心,查看“IoT 中心”窗格,其中包含“设置”等内容。Click on your hub to see the IoT Hub pane with Settings, and so on. 单击“共享访问策略”。Click Shared access policies.

  2. 在“共享访问策略”中,选择 iothubowner 策略。In Shared access policies, select the iothubowner policy.

  3. 在“共享访问密钥”下,复制“连接字符串 -- 主密钥”供以后使用。Under Shared access keys, copy the Connection string -- primary key to be used later.

    显示如何检索连接字符串

    有关详细信息,请参阅“IoT 中心开发人员指南”中的访问控制For more information, see Access control in the "IoT Hub developer guide."

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

本部分在 IoT 中心的标识注册表中创建设备标识。In this section, you create a device identity in the identity registry in your IoT hub. 设备无法连接到 IoT 中心,除非它在标识注册表中具有条目。A device cannot connect to IoT hub unless it has an entry in the identity registry. 有关详细信息,请参阅 IoT 中心开发人员指南的“标识注册表”部分For more information, see the "Identity registry" section of the IoT Hub developer guide

  1. 在 IoT 中心导航菜单中,打开“IoT 设备”,然后单击“添加”,在 IoT 中心注册新设备。In your IoT hub navigation menu, open IoT Devices, then click Add to register a new device in your IoT hub.

    在门户中创建设备标识

  2. 提供新设备的名称(例如 myDeviceId),然后单击“保存”。Provide a name for your new device, such as myDeviceId, and click Save. 此操作会为 IoT 中心创建新设备标识。This action creates a new device identity for your IoT hub.

    添加新设备

    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.

  3. 创建设备后,在“IoT 设备”窗格的列表中打开该设备。After the device is created, open the device from the list in the IoT devices pane. 复制“连接字符串 ---主密钥”供以后使用。Copy the Connection string---primary key to use later.

    设备连接字符串

Note

IoT 中心标识注册表仅存储用于实现 IoT 中心安全访问的设备标识。The IoT Hub identity registry only stores device identities to enable secure access to the IoT hub. 它存储设备 ID 和密钥作为安全凭据,以及启用/禁用标志让你禁用对单个设备的访问。It stores device IDs and keys to use as security credentials, and an enabled/disabled flag that you can use to disable access for an individual device. 如果应用程序需要存储其他特定于设备的元数据,则应使用特定于应用程序的存储。If your application needs to store other device-specific metadata, it should use an application-specific store. 有关详细信息,请参阅 IoT 中心开发人员指南For more information, see IoT Hub developer guide.

创建服务应用Create the service app

本部分将创建一个 Java 应用,用于将位置元数据作为标记添加到 IoT 中心内与 myDeviceId 关联的设备孪生。In this section, you create a Java app that adds location metadata as a tag to the device twin in IoT Hub associated with myDeviceId. 该应用首先在 IoT 中心查询位于美国的设备,然后查询报告已建立移动电话网络连接的设备。The app first queries IoT hub for devices located in the US, and then for devices that report a cellular network connection.

  1. 在开发计算机上,创建名为 iot-java-twin-getstarted 的空文件夹。On your development machine, create an empty folder called iot-java-twin-getstarted.

  2. iot-java-twin-getstarted 文件夹中,通过命令提示符使用以下命令创建名为 add-tags-query 的 Maven 项目。In the iot-java-twin-getstarted folder, create a Maven project called add-tags-query using the following command at your command prompt. 请注意,这是一条很长的命令:Note this is a single, long command:

    mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=add-tags-query -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
    
  3. 在命令提示符下,导航到 add-tags-query 文件夹。At your command prompt, navigate to the add-tags-query folder.

  4. 使用文本编辑器打开 add-tags-query 文件夹中的 pom.xml 文件,在 dependencies 节点中添加以下依赖项。Using a text editor, open the pom.xml file in the add-tags-query folder and add the following dependency to the dependencies node. 通过此依赖项可以使用应用中的 iot-service-client 包来与 IoT 中心通信:This dependency enables you to use the iot-service-client package in your app to communicate with your IoT hub:

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

    Note

    可以使用 Maven 搜索检查是否有最新版本的 iot-service-clientYou can check for the latest version of iot-service-client using Maven search.

  5. dependencies 节点后添加以下 build 节点。Add the following build node after the dependencies node. 此配置指示 Maven 使用 Java 1.8 来生成应用:This configuration instructs Maven to use Java 1.8 to build the app:

    <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 文件。Save and close the pom.xml file.

  7. 使用文本编辑器打开 add-tags-query\src\main\java\com\mycompany\app\App.java 文件。Using a text editor, open the add-tags-query\src\main\java\com\mycompany\app\App.java file.

  8. 在该文件中添加以下 import 语句:Add the following import statements to the file:

    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 类。Add the following class-level variables to the App class. {youriothubconnectionstring} 替换为在“创建 IoT 中心”部分记下的 IoT 中心连接字符串:Replace {youriothubconnectionstring} with your IoT hub connection string you noted in the Create an IoT Hub section:

    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 子句:Update the main method signature to include the following throws clause:

    public static void main( String[] args ) throws IOException
    
  11. 将以下代码添加到 main 方法,以创建 DeviceTwinDeviceTwinDevice 对象。Add the following code to the main method to create the DeviceTwin and DeviceTwinDevice objects. DeviceTwin 对象处理与 IoT 中心之间的通信。The DeviceTwin object handles the communication with your IoT hub. DeviceTwinDevice 对象使用设备孪生的属性和标记来表示设备孪生:The DeviceTwinDevice object represents the device twin with its properties and tags:

    // Get the DeviceTwin and DeviceTwinDevice objects
    DeviceTwin twinClient = DeviceTwin.createFromConnectionString(iotHubConnectionString);
    DeviceTwinDevice device = new DeviceTwinDevice(deviceId);
    
  12. 将以下 try/catch 块添加到 main 方法:Add the following try/catch block to the main method:

    try {
      // Code goes here
    } catch (IotHubException e) {
      System.out.println(e.getMessage());
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
    
  13. 若要更新设备孪生中的 regionplant 设备孪生标记,请在 try 块中添加以下代码:To update the region and plant device twin tags in your device twin, add the following code in the try block:

    // 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 块(添加到上一步骤中添加的代码后面)。To query the device twins in IoT hub, add the following code to the try block after the code you added in the previous step. 该代码运行两个查询。The code runs two queries. 每个查询最多返回 100 个设备:Each query returns a maximum of 100 devices:

    // 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 文件Save and close the add-tags-query\src\main\java\com\mycompany\app\App.java file

  16. 生成 add-tags-query 应用并更正任何错误。Build the add-tags-query app and correct any errors. 在命令提示符下,导航到 add-tags-query 文件夹并运行以下命令:At your command prompt, navigate to the add-tags-query folder and run the following command:

    mvn clean package -DskipTests

创建设备应用Create a device app

本部分创建一个 Java 控制台应用,用于设置要发送到 IoT 中心的报告属性值。In this section, you create a Java console app that sets a reported property value that is sent to IoT Hub.

  1. 在命令提示符下使用以下命令,在 iot-java-twin-getstarted 文件夹中创建名为 simulated-device 的 Maven 项目。In the iot-java-twin-getstarted folder, create a Maven project called simulated-device using the following command at your command prompt. 请注意,这是一条很长的命令:Note this is a single, long command:

    mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=simulated-device -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

  2. 在命令提示符下,导航到 simulated-device 文件夹。At your command prompt, navigate to the simulated-device folder.

  3. 使用文本编辑器打开 simulated-device 文件夹中的 pom.xml 文件,在 dependencies 节点中添加以下依赖项。Using a text editor, open the pom.xml file in the simulated-device folder and add the following dependencies to the dependencies node. 通过此依赖项可以使用应用中的 iot-device-client 包来与 IoT 中心进行通信:This dependency enables you to use the iot-device-client package in your app to communicate with your IoT hub:

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

    Note

    可以使用 Maven 搜索检查是否有最新版本的 iot-device-clientYou can check for the latest version of iot-device-client using Maven search.

  4. dependencies 节点后添加以下 build 节点。Add the following build node after the dependencies node. 此配置指示 Maven 使用 Java 1.8 来生成应用:This configuration instructs Maven to use Java 1.8 to build the app:

    <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>
    
  5. 保存并关闭 pom.xml 文件。Save and close the pom.xml file.

  6. 使用文本编辑器打开 simulated-device\src\main\java\com\mycompany\app\App.java 文件。Using a text editor, open the simulated-device\src\main\java\com\mycompany\app\App.java file.

  7. 在该文件中添加以下 import 语句:Add the following import statements to the file:

    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;
    
  8. 将以下类级变量添加到 App 类。Add the following class-level variables to the App class. {youriothubname} 替换为 IoT 中心名称,将 {yourdevicekey} 替换为在“创建设备标识”部分中生成的设备密钥值:Replacing {youriothubname} with your IoT hub name, and {yourdevicekey} with the device key value you generated in the Create a device identity section:

    private static String connString = "HostName={youriothubname}.azure-devices.cn;DeviceId=myDeviceID;SharedAccessKey={yourdevicekey}";
    private static IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
    private static String deviceId = "myDeviceId";
    

    本示例应用在实例化 DeviceClient 对象时使用 protocol 变量。This sample app uses the protocol variable when it instantiates a DeviceClient object.

  9. 将以下方法添加到 App 类以输出有关孪生更新的信息:Add the following method to the App class to print information about twin updates:

    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());
        }
      }
    
  10. 将以下代码添加到 main 方法,以便:Add the following code to the main method to:

    • 创建用来与 IoT 中心通信的设备客户端。Create a device client to communicate with IoT Hub.

    • 创建一个 Device 对象用于存储设备孪生属性。Create a Device object to store the device twin properties.

      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);
      }
      };
      
  11. 将以下代码添加到 main 方法,创建 connectivityType 报告属性并将其发送到 IoT 中心:Add the following code to the main method to create a connectivityType reported property and send it to IoT Hub:

    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...");
    }
    
  12. 将以下代码添加到 main 方法的末尾。Add the following code to the end of the main method. Enter 键,等待一段时间让 IoT 中心报告设备孪生操作的状态:Waiting for the Enter key allows time for IoT Hub to report the status of the device twin operations:

    System.out.println("Press any key to exit...");
    
    Scanner scanner = new Scanner(System.in);
    scanner.nextLine();
    
    dataCollector.clean();
    client.close();
    
  13. 修改 main 方法的签名,包含如下所示的异常:Modify the signature of the main method to include the exceptions as follows:

    public static void main(String[] args) throws URISyntaxException, IOException
    
  14. 保存并关闭 simulated-device\src\main\java\com\mycompany\app\App.java 文件。Save and close the simulated-device\src\main\java\com\mycompany\app\App.java file.

  15. 生成 simulated-device 应用并更正任何错误。Build the simulated-device app and correct any errors. 在命令提示符下,导航到 simulated-device 文件夹并运行以下命令:At your command prompt, navigate to the simulated-device folder and run the following command:

    mvn clean package -DskipTests

运行应用Run the apps

现在可以运行控制台应用了。You are now ready to run the console apps.

  1. add-tags-query 文件夹中的命令提示符下,运行以下命令以运行 add-tags-query 服务应用:At a command prompt in the add-tags-query folder, run the following command to run the add-tags-query service app:

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

    Java IoT 中心服务应用会更新标记值并运行设备查询

    可以看到,plantregion 标记已添加到设备孪生。You can see the plant and region tags added to the device twin. 第一个查询返回设备,但第二个查询则不会。The first query returns your device, but the second does not.

  2. simulated-device 文件夹中的命令提示符下,运行以下命令将 connectivityType 报告属性添加到设备孪生:At a command prompt in the simulated-device folder, run the following command to add the connectivityType reported property to the device twin:

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

    设备客户端会添加 connectivityType 报告属性

  3. add-tags-query 文件夹中的命令提示符下,再次运行以下命令以运行 add-tags-query 服务应用:At a command prompt in the add-tags-query folder, run the following command to run the add-tags-query service app a second time:

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

    Java IoT 中心服务应用会更新标记值并运行设备查询

    现在,设备已将 connectivityType 属性发送到 IoT 中心,第二个查询返回了设备。Now your device has sent the connectivityType property to IoT Hub, the second query returns your device.

后续步骤Next steps

本教程中,在 Azure 门户中配置了新的 IoT 中心,并在 IoT 中心的标识注册表中创建了设备标识。In this tutorial, you configured a new IoT hub in the Azure portal, and then created a device identity in the IoT hub's identity registry. 已从后端应用以标记形式添加了设备元数据,并编写了一个设备应用用于报告设备孪生中的设备连接信息。You added device metadata as tags from a back-end app, and wrote a device app to report device connectivity information in the device twin. 此外,还学习了如何使用类似于 SQL 的 IoT 中心查询语言查询设备孪生信息。You also learned how to query the device twin information using the SQL-like IoT Hub query language.

充分利用以下资源:Use the following resources to learn how to:

  • 通过 IoT 中心入门教程学习如何从设备发送遥测数据。Send telemetry from devices with the Get started with IoT Hub tutorial.
  • 通过使用直接方法教程学习如何以交互方式控制设备(例如从用户控制的应用打开风扇)。Control devices interactively (such as turning on a fan from a user-controlled app) with the Use direct methods tutorial.