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

后端应用可以使用 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 implements a direct method to reboot the device. 直接方法是从云中调用的。Direct methods are invoked from the cloud.
  • 创建通过 IoT 中心在模拟设备应用上调用重启直接方法的应用。Create an app that invokes the reboot direct method in the simulated device app through your IoT hub. 之后此应用会监视设备的报告属性,查看重启操作何时完成。This app then monitors the reported properties from the device to see when the reboot operation is complete.

本教程结束时,将会创建两个 Java 控制台应用:At the end of this tutorial, you have two Java console apps:

simulated-device 。simulated-device. 此应用:This app:

  • 使用之前创建的设备标识连接到 IoT 中心。Connects to your IoT hub with the device identity created earlier.
  • 接收重启直接方法调用。Receives a reboot direct method call.
  • 模拟物理重启。Simulates a physical reboot.
  • 通过报告属性报告上次重启的时间。Reports the time of the last reboot through a reported property.

trigger-reboot 。trigger-reboot. 此应用:This app:

  • 在模拟设备应用中调用直接方法。Calls a direct method in the simulated device app.

  • 显示模拟设备发送的直接方法调用的响应。Displays the response to the direct method call sent by the simulated device.

  • 显示更新的报告属性。Displays the updated reported properties.

Note

有关 SDK 的信息(可以使用这些 SDK 构建在设备和解决方案后端上运行的应用程序),请参阅 Azure IoT SDKFor information about the SDKs that you can use to build applications to run on devices and your solution back end, see Azure IoT SDKs.

必备条件Prerequisites

  • Java SE 开发工具包 8Java SE Development Kit 8. 请确保在“长期支持” 下选择“Java 8” 以获取 JDK 8 的下载。Make sure you select Java 8 under Long-term support to get to downloads for JDK 8.

  • Maven 3Maven 3

  • 有效的 Azure 帐户。An active Azure account. (如果没有帐户,只需几分钟即可创建一个试用帐户。)(If you don't have an account, you can create a trial account in just a couple of minutes.)

  • 确保已在防火墙中打开端口 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.

获取 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

本部分将创建一个进行如下操作的 Java 控制台应用:In this section, you create a Java console app that:

  1. 在模拟设备应用中调用重启直接方法。Invokes the reboot direct method in the simulated device app.

  2. 显示响应。Displays the response.

  3. 轮询设备发送的报告属性,以确定重启的完成时间。Polls the reported properties sent from the device to determine when the reboot is complete.

此控制台应用连接到 IoT 中心,以便调用该直接方法并读取报告属性。This console app connects to your IoT Hub to invoke the direct method and read the reported properties.

  1. 创建名为 dm-get-started 的空文件夹。Create an empty folder called dm-get-started.

  2. 在命令提示符下使用以下命令,在 dm-get-started 文件夹中创建名为 trigger-reboot 的 Maven 项目:In the dm-get-started folder, create a Maven project called trigger-reboot using the following command at your command prompt:

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

  4. 使用文本编辑器,打开 trigger-reboot 文件夹中的 pom.xml 文件,并将以下依赖项添加到 dependencies 节点。Using a text editor, open the pom.xml file in the trigger-reboot 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.17.1</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. 使用文本编辑器打开 trigger-reboot\src\main\java\com\mycompany\app\App.java 源文件。Using a text editor, open the trigger-reboot\src\main\java\com\mycompany\app\App.java source file.

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

    import com.microsoft.azure.sdk.iot.service.devicetwin.DeviceMethod;
    import com.microsoft.azure.sdk.iot.service.devicetwin.MethodResult;
    import com.microsoft.azure.sdk.iot.service.exceptions.IotHubException;
    import com.microsoft.azure.sdk.iot.service.devicetwin.DeviceTwin;
    import com.microsoft.azure.sdk.iot.service.devicetwin.DeviceTwinDevice;
    
    import java.io.IOException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    
  9. 将以下类级变量添加到 App 类。Add the following class-level variables to the App class. {youriothubconnectionstring} 替换为先前在获取 IoT 中心连接字符串中复制的 IoT 中心连接字符串:Replace {youriothubconnectionstring} with the IoT Hub connection string you copied previously in Get the IoT hub connection string:

    public static final String iotHubConnectionString = "{youriothubconnectionstring}";
    public static final String deviceId = "myDeviceId";
    
    private static final String methodName = "reboot";
    private static final Long responseTimeout = TimeUnit.SECONDS.toSeconds(30);
    private static final Long connectTimeout = TimeUnit.SECONDS.toSeconds(5);
    
  10. 若要实现每隔 10 秒读取一次设备孪生提供的报告属性的线程,请将以下嵌套类添加到 App 类 :To implement a thread that reads the reported properties from the device twin every 10 seconds, add the following nested class to the App class:

    private static class ShowReportedProperties implements Runnable {
      public void run() {
        try {
          DeviceTwin deviceTwins = DeviceTwin.createFromConnectionString(iotHubConnectionString);
          DeviceTwinDevice twinDevice = new DeviceTwinDevice(deviceId);
          while (true) {
            System.out.println("Get reported properties from device twin");
            deviceTwins.getTwin(twinDevice);
            System.out.println(twinDevice.reportedPropertiesToString());
            Thread.sleep(10000);
          }
        } catch (Exception ex) {
          System.out.println("Exception reading reported properties: " + ex.getMessage());
        }
      }
    }
    
  11. 将 main 方法签名修改为抛出以下异常:Modify the signature of the main method to throw the following exception:

    public static void main(String[] args) throws IOException
    
  12. 若要在模拟设备上调用重新启动直接方法,请将 main 方法中的代码替换为以下代码:To invoke the reboot direct method on the simulated device, replace the code in the main method with the following code:

    System.out.println("Starting sample...");
    DeviceMethod methodClient = DeviceMethod.createFromConnectionString(iotHubConnectionString);
    
    try
    {
      System.out.println("Invoke reboot direct method");
      MethodResult result = methodClient.invoke(deviceId, methodName, responseTimeout, connectTimeout, null);
    
      if(result == null)
      {
        throw new IOException("Invoke direct method reboot returns null");
      }
      System.out.println("Invoked reboot on device");
      System.out.println("Status for device:   " + result.getStatus());
      System.out.println("Message from device: " + result.getPayload());
    }
    catch (IotHubException e)
    {
        System.out.println(e.getMessage());
    }
    
  13. 若要启动轮询模拟设备提供的报告属性的线程,请将以下代码添加到 main 方法 :To start the thread to poll the reported properties from the simulated device, add the following code to the main method:

    ShowReportedProperties showReportedProperties = new ShowReportedProperties();
    ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.execute(showReportedProperties);
    
  14. 若要能够停止应用,请将以下代码添加到 main 方法 :To enable you to stop the app, add the following code to the main method:

    System.out.println("Press ENTER to exit.");
    System.in.read();
    executor.shutdownNow();
    System.out.println("Shutting down sample...");
    
  15. 保存并关闭 trigger-reboot\src\main\java\com\mycompany\app\App.java 文件。Save and close the trigger-reboot\src\main\java\com\mycompany\app\App.java file.

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

    mvn clean package -DskipTests
    

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

本部分中将创建一个模拟设备的 Java 控制台应用。In this section, you create a Java console app that simulates a device. 该应用侦听 IoT 中心发出的重启直接方法调用并快速响应该调用。The app listens for the reboot direct method call from your IoT hub and immediately responds to that call. 然后该应用会休眠一段时间,以模拟重启过程,之后该应用会使用报告属性通知 trigger-reboot 后端应用重启已完成 。The app then sleeps for a while to simulate the reboot process before it uses a reported property to notify the trigger-reboot back-end app that the reboot is complete.

  1. 在命令提示符下使用以下命令,在 dm-get-started 文件夹中创建名为 simulated-device 的 Maven 项目:In the dm-get-started folder, create a Maven project called simulated-device using the following command at your command prompt:

    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 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-device-client</artifactId>
      <version>1.17.5</version>
    </dependency>
    

    Note

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

  4. 将以下依赖项添加到 dependencies 节点。Add the following dependency to the dependencies node. 此依赖项为 Apache SLF4J 日志记录外观配置 NOP,设备客户端 SDK 使用它来实现日志记录。This dependency configures a NOP for the Apache SLF4J logging facade, which is used by the device client SDK to implement logging. 此配置是可选的,但如果省略此配置,则在运行应用时,可能会在控制台中看到一条警告。This configuration is optional, but, if you omit it, you may see a warning in the console when you run the app. 有关设备客户端 SDK 中的日志记录的详细信息,请参阅适用于 Java 的 Azure IoT 设备 SDK 的示例自述文件中的日志记录For more information about logging in the device client SDK, see Logging in the Samples for the Azure IoT device SDK for Java readme file.

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-nop</artifactId>
      <version>1.7.28</version>
    </dependency>
    
  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. 使用文本编辑器打开 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 source file.

  8. 在该文件中添加以下 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.time.LocalDateTime;
    import java.util.Scanner;
    import java.util.Set;
    import java.util.HashSet;
    
  9. 将以下类级变量添加到 App 类。Add the following class-level variables to the App class. 使用“创建设备标识”部分所述的设备连接字符串替换 {yourdeviceconnectionstring}Replace {yourdeviceconnectionstring} with the device connection string you noted in the Create a device identity section:

    private static final int METHOD_SUCCESS = 200;
    private static final int METHOD_NOT_DEFINED = 404;
    
    private static IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
    private static String connString = "{yourdeviceconnectionstring}";
    private static DeviceClient client;
    
  10. 若要为直接方法状态事件实现回调处理程序,请将以下嵌套类添加到 App 类 :To implement a callback handler for direct method status events, add the following nested class to the App class:

    protected static class DirectMethodStatusCallback implements IotHubEventCallback
    {
      public void execute(IotHubStatusCode status, Object context)
      {
        System.out.println("IoT Hub responded to device method operation with status " + status.name());
      }
    }
    
  11. 若要为设备孪生状态事件实现回调处理程序,请将以下嵌套类添加到 App 类 :To implement a callback handler for device twin status events, add the following nested class to the App class:

    protected static class DeviceTwinStatusCallback implements IotHubEventCallback
    {
        public void execute(IotHubStatusCode status, Object context)
        {
            System.out.println("IoT Hub responded to device twin operation with status " + status.name());
        }
    }
    
  12. 若要为属性事件实现回调处理程序,请将以下嵌套类添加到 App 类 :To implement a callback handler for property events, add the following nested class to the App class:

    protected static class PropertyCallback implements PropertyCallBack<String, String>
    {
      public void PropertyCall(String propertyKey, String propertyValue, Object context)
      {
        System.out.println("PropertyKey:     " + propertyKey);
        System.out.println("PropertyKvalue:  " + propertyKey);
      }
    }
    
  13. 若要实现一个模拟设备重启的线程,请将以下嵌套类添加到 App 类 。To implement a thread to simulate the device reboot, add the following nested class to the App class. 线程会休眠五秒,然后设置 lastReboot 报告属性 :The thread sleeps for five seconds and then sets the lastReboot reported property:

    protected static class RebootDeviceThread implements Runnable {
      public void run() {
        try {
          System.out.println("Rebooting...");
          Thread.sleep(5000);
          Property property = new Property("lastReboot", LocalDateTime.now());
          Set<Property> properties = new HashSet<Property>();
          properties.add(property);
          client.sendReportedProperties(properties);
          System.out.println("Rebooted");
        }
        catch (Exception ex) {
          System.out.println("Exception in reboot thread: " + ex.getMessage());
        }
      }
    }
    
  14. 若要在设备上实现直接方法,请将以下嵌套类添加到 App 类 。To implement the direct method on the device, add the following nested class to the App class. 模拟应用接收到重启直接方法的调用时,会向调用方返回确认,然后启动处理重启的线程 :When the simulated app receives a call to the reboot direct method, it returns an acknowledgement to the caller and then starts a thread to process the reboot:

    protected static class DirectMethodCallback implements com.microsoft.azure.sdk.iot.device.DeviceTwin.DeviceMethodCallback
    {
      @Override
      public DeviceMethodData call(String methodName, Object methodData, Object context)
      {
        DeviceMethodData deviceMethodData;
        switch (methodName)
        {
          case "reboot" :
          {
            int status = METHOD_SUCCESS;
            System.out.println("Received reboot request");
            deviceMethodData = new DeviceMethodData(status, "Started reboot");
            RebootDeviceThread rebootThread = new RebootDeviceThread();
            Thread t = new Thread(rebootThread);
            t.start();
            break;
          }
          default:
          {
            int status = METHOD_NOT_DEFINED;
            deviceMethodData = new DeviceMethodData(status, "Not defined direct method " + methodName);
          }
        }
        return deviceMethodData;
      }
    }
    
  15. 修改 main 方法的签名以引发以下异常 :Modify the signature of the main method to throw the following exceptions:

    public static void main(String[] args) throws IOException, URISyntaxException
    
  16. 若要实例化 DeviceClient,请将 main 方法中的代码替换为以下代码:To instantiate a DeviceClient, replace the code in the main method with the following code:

    System.out.println("Starting device client sample...");
    client = new DeviceClient(connString, protocol);
    
  17. 若要开始侦听直接方法调用,请将以下代码添加到 main 方法 :To start listening for direct method calls, add the following code to the main method:

    try
    {
      client.open();
      client.subscribeToDeviceMethod(new DirectMethodCallback(), null, new DirectMethodStatusCallback(), null);
      client.startDeviceTwin(new DeviceTwinStatusCallback(), null, new PropertyCallback(), null);
      System.out.println("Subscribed to direct methods and polling for reported properties. Waiting...");
    }
    catch (Exception e)
    {
      System.out.println("On exception, shutting down \n" + " Cause: " + e.getCause() + " \n" +  e.getMessage());
      client.close();
      System.out.println("Shutting down...");
    }
    
  18. 若要关闭设备模拟器,请将以下代码添加到 main 方法 :To shut down the device simulator, add the following code to the main method:

    System.out.println("Press any key to exit...");
    Scanner scanner = new Scanner(System.in);
    scanner.nextLine();
    scanner.close();
    client.close();
    System.out.println("Shutting down...");
    
  19. 保存并关闭 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.

  20. 生成 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're now ready to run the apps.

  1. simulated-device 文件夹的命令提示符下,运行以下命令,开始侦听从 IoT 中心发出的重新启动方法调用:At a command prompt in the simulated-device folder, run the following command to begin listening for reboot method calls from your IoT hub:

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

    侦听重启直接方法调用的 Java IoT 中心模拟设备应用

  2. trigger-reboot 文件夹的命令提示符下,运行以下命令,从 IoT 中心调用模拟设备上的重新启动方法:At a command prompt in the trigger-reboot folder, run the following command to call the reboot method on your simulated device from your IoT hub:

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

    调用重启直接方法的 Java IoT 中心服务应用

  3. 模拟设备对重启直接方法调用做出响应:The simulated device responds to the reboot direct method call:

    对直接方法调用进行响应的 Java IoT 中心模拟设备应用

自定义和扩展设备管理操作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.