快速入门:使用 Java 控制连接到 Azure IoT 中心的设备Quickstart: Control a device connected to an Azure IoT hub with Java

IoT 中心是一项 Azure 服务,使你可以从云管理 IoT 设备,并将大量设备遥测引入云以进行存储或处理。IoT Hub is an Azure service that enables you to manage your IoT devices from the cloud, and ingest high volumes of device telemetry to the cloud for storage or processing. 在本快速入门中,会使用直接方法通过Java 应用程序来控制连接到 Azure IoT 中心的模拟设备 。In this quickstart, you use a direct method to control a simulated device connected to your Azure IoT hub with a Java application. 可使用直接方法远程更改连接到 IoT 中心的设备的行为。You can use direct methods to remotely change the behavior of a device connected to your IoT hub.

本快速入门使用两个预先编写的 Java 应用程序:The quickstart uses two pre-written Java applications:

  • 从后端应用程序调用的可响应直接方法的模拟设备应用程序。A simulated device application that responds to direct methods called from a back-end application. 为了接收直接方法调用,此应用程序会连接到 IoT 中心上特定于设备的终结点。To receive the direct method calls, this application connects to a device-specific endpoint on your IoT hub.
  • 后端应用程序,可在模拟设备上调用直接方法。A back-end application that calls the direct methods on the simulated device. 为了在设备上调用直接方法,此应用程序会连接到 IoT 中心上的服务端终结点。To call a direct method on a device, this application connects to service-side endpoint on your IoT hub.

如果没有 Azure 订阅,请在开始前创建一个试用帐户If you don’t have an Azure subscription, create a trial account before you begin.

先决条件Prerequisites

本快速入门中运行的两个示例应用程序是使用 Java 编写的。The two sample applications you run in this quickstart are written using Java. 开发计算机上需要安装 Java SE 8。You need Java SE 8 on your development machine.

可以从 Java 对 Azure 和 Azure Stack 的长期支持下载适用于多个平台的 Java SE 开发工具包 8。You can download Java SE Development Kit 8 for multiple platforms from Java long-term support for Azure and Azure Stack. 请确保在“长期支持” 下选择“Java 8” 以获取 JDK 8 的下载。Make sure you select Java 8 under Long-term support to get to downloads for JDK 8.

可以使用以下命令验证开发计算机上 Java 的当前版本:You can verify the current version of Java on your development machine using the following command:

java -version

若要生成示例,需安装 Maven 3。To build the samples, you need to install Maven 3. 可从 Apache Maven 为多个平台下载 Maven。You can download Maven for multiple platforms from Apache Maven.

可以使用以下命令验证开发计算机上 Maven 的当前版本:You can verify the current version of Maven on your development machine using the following command:

mvn --version

运行以下命令将用于添加 Azure CLI 的 Azure IoT 扩展。Run the following command to add the Azure IoT Extension for Azure CLI. IOT 扩展会将 IoT 中心、IoT Edge 和 IoT 设备预配服务 (DPS) 特定的命令添加到 Azure CLI。The IOT Extension adds IoT Hub, IoT Edge, and IoT Device Provisioning Service (DPS) specific commands to Azure CLI.

az extension add --name azure-cli-iot-ext

如果尚未进行此操作,请从 https://github.com/Azure-Samples/azure-iot-samples-java/archive/master.zip 下载示例 Java 项目并提取 ZIP 存档。If you haven't already done so, download the sample Java project from https://github.com/Azure-Samples/azure-iot-samples-java/archive/master.zip and extract the ZIP archive.

创建 IoT 中心Create an IoT hub

如果已完成上一快速入门:将遥测数据从设备发送到 IoT 中心,可以跳过此步骤。If you completed the previous Quickstart: Send telemetry from a device to an IoT hub, you can skip this step.

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

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

  2. 选择“创建资源”,然后在“搜索市场”字段中输入“IoT 中心”。 Choose Create a resource, 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.

注册设备Register a device

如果已完成上一快速入门:将遥测数据从设备发送到 IoT 中心,可以跳过此步骤。If you completed the previous Quickstart: Send telemetry from a device to an IoT hub, you can skip this step.

必须先将设备注册到 IoT 中心,然后该设备才能进行连接。A device must be registered with your IoT hub before it can connect. 在本快速入门中,请使用 Azure CLI 来注册模拟设备。In this quickstart, you use the Azure CLI to register a simulated device.

  1. 运行以下命令,以创建设备标识。Run the following command to create the device identity.

    YourIoTHubName:将下面的占位符替换为你为 IoT 中心选择的名称。YourIoTHubName : Replace this placeholder below with the name you chose for your IoT hub.

    MyJavaDevice:这是所注册的设备的名称。MyJavaDevice: This is the name of the device you're registering. 建议使用 MyJavaDevice,如图所示。It's recommended to use MyJavaDevice as shown. 如果为设备选择不同名称,则可能还需要在本文中从头至尾使用该名称,并在运行示例应用程序之前在其中更新设备名称。If you choose a different name for your device, you also need to use that name throughout this article, and update the device name in the sample applications before you run them.

    az iot hub device-identity create \
      --hub-name {YourIoTHubName} --device-id MyJavaDevice
    
  2. 运行以下命令,获取刚注册设备的_设备连接字符串_:Run the following commands to get the device connection string for the device you just registered:

    YourIoTHubName:将下面的占位符替换为你为 IoT 中心选择的名称。YourIoTHubName : Replace this placeholder below with the name you choose for your IoT hub.

    az iot hub device-identity show-connection-string \
      --hub-name {YourIoTHubName} \
      --device-id MyJavaDevice \
      --output table
    

    记下如下所示的设备连接字符串:Make a note of the device connection string, which looks like:

    HostName={YourIoTHubName}.azure-devices.cn;DeviceId=MyNodeDevice;SharedAccessKey={YourSharedAccessKey}

    稍后会在快速入门中用到此值。You use this value later in the quickstart.

检索服务连接字符串Retrieve the service connection string

还需一个服务连接字符串,以便后端应用程序能够连接到 IoT 中心并检索消息 。You also need a service connection string to enable the back-end application to connect to your IoT hub and retrieve the messages. 以下命令检索 IoT 中心的服务连接字符串:The following command retrieves the service connection string for your IoT hub:

YourIoTHubName:将下面的占位符替换为你为 IoT 中心选择的名称。YourIoTHubName : Replace this placeholder below with the name you chose for your IoT hub.

az iot hub show-connection-string --policy-name service --name {YourIoTHubName} --output table

记下如下所示的服务连接字符串:Make a note of the service connection string, which looks like:

HostName={YourIoTHubName}.azure-devices.cn;SharedAccessKeyName=service;SharedAccessKey={YourSharedAccessKey}

稍后会在快速入门中用到此值。You use this value later in the quickstart. 此服务连接字符串与你在上一步中记录的设备连接字符串不同。This service connection string is different from the device connection string you noted in the previous step.

侦听直接方法调用Listen for direct method calls

模拟设备应用程序会连接到 IoT 中心上特定于设备的终结点,发送模拟遥测数据,并侦听中心的直接方法调用。The simulated device application connects to a device-specific endpoint on your IoT hub, sends simulated telemetry, and listens for direct method calls from your hub. 在本快速入门中,中心的直接方法调用告知设备对其发送遥测的间隔进行更改。In this quickstart, the direct method call from the hub tells the device to change the interval at which it sends telemetry. 执行直接方法后,模拟设备会将确认发送回中心。The simulated device sends an acknowledgement back to your hub after it executes the direct method.

  1. 在本地终端窗口中,导航到示例 Java 项目的根文件夹。In a local terminal window, navigate to the root folder of the sample Java project. 然后导航到 iot-hub\Quickstarts\simulated-device-2 文件夹。Then navigate to the iot-hub\Quickstarts\simulated-device-2 folder.

  2. 在所选文本编辑器中打开 src/main/java/com/microsoft/docs/iothub/samples/SimulatedDevice.java 文件 。Open the src/main/java/com/microsoft/docs/iothub/samples/SimulatedDevice.java file in a text editor of your choice.

    connString 变量的值替换为之前记下的设备连接字符串。Replace the value of the connString variable with the device connection string you made a note of earlier. 然后将更改保存到 SimulatedDevice.javaThen save your changes to SimulatedDevice.java.

  3. 在本地终端窗口中,运行以下命令以安装所需的库,并生成模拟设备应用程序:In the local terminal window, run the following commands to install the required libraries and build the simulated device application:

    mvn clean package
    
  4. 在本地终端窗口中,运行以下命令,以便运行模拟设备应用程序:In the local terminal window, run the following commands to run the simulated device application:

    java -jar target/simulated-device-2-1.0.0-with-deps.jar
    

    以下屏幕截图显示了模拟设备应用程序将遥测数据发送到 IoT 中心后的输出:The following screenshot shows the output as the simulated device application sends telemetry to your IoT hub:

    设备发送到 IoT 中心的遥测的输出

调用直接方法Call the direct method

后端应用程序会连接到 IoT 中心上的服务端终结点。The back-end application connects to a service-side endpoint on your IoT Hub. 应用程序通过 IoT 中心对设备进行直接方法调用,并侦听确认。The application makes direct method calls to a device through your IoT hub and listens for acknowledgements. IoT 中心后端应用程序通常在云中运行。An IoT Hub back-end application typically runs in the cloud.

  1. 在另一个本地终端窗口中,导航到示例 Java 项目的根文件夹。In another local terminal window, navigate to the root folder of the sample Java project. 然后导航到 iot-hub\Quickstarts\back-end-application 文件夹。Then navigate to the iot-hub\Quickstarts\back-end-application folder.

  2. 在所选文本编辑器中打开 src/main/java/com/microsoft/docs/iothub/samples/BackEndApplication.java 文件 。Open the src/main/java/com/microsoft/docs/iothub/samples/BackEndApplication.java file in a text editor of your choice.

    iotHubConnectionString 变量的值替换为以前记下的服务连接字符串。Replace the value of the iotHubConnectionString variable with the service connection string you made a note of earlier. 然后将更改保存到 BackEndApplication.javaThen save your changes to BackEndApplication.java.

  3. 在本地终端窗口中运行以下命令,以安装所需的库并生成后端应用程序:In the local terminal window, run the following commands to install the required libraries and build the back-end application:

    mvn clean package
    
  4. 在本地终端窗口中,运行以下命令,以便运行终端应用程序:In the local terminal window, run the following commands to run the back-end application:

    java -jar target/back-end-application-1.0.0-with-deps.jar
    

    以下屏幕截图显示了应用程序对设备进行直接方法调用并接收确认后的输出:The following screenshot shows the output as the application makes a direct method call to the device and receives an acknowledgment:

    应用程序通过 IoT 中心进行直接方法调用时的输出

    运行后端应用程序后,在运行模拟设备的控制台窗口中会出现一条消息,且其发送消息的速率也会发生变化:After you run the back-end application, you see a message in the console window running the simulated device, and the rate at which it sends messages changes:

    来自设备的控制台消息显示它的变化速率

清理资源Clean up resources

如果想要继续学习下一篇建议的文章,可以保留已创建的资源,以便重复使用。If you will be continuing to the next recommended article, you can keep the resources you've already created and reuse them.

否则,可删除本文中创建的 Azure 资源,避免收费。Otherwise, you can delete the Azure resources created in this article to avoid charges.

Important

删除资源组的操作不可逆。Deleting a resource group is irreversible. 资源组以及包含在其中的所有资源将被永久删除。The resource group and all the resources contained in it are permanently deleted. 请确保不会意外删除错误的资源组或资源。Make sure that you do not accidentally delete the wrong resource group or resources. 如果在现有的包含要保留资源的资源组中创建了 IoT 中心,则只删除 IoT 中心资源本身,而不要删除资源组。If you created the IoT Hub inside an existing resource group that contains resources you want to keep, only delete the IoT Hub resource itself instead of deleting the resource group.

若要按名称删除资源组,请执行以下操作:To delete a resource group by name:

  1. 登录到 Azure 门户,然后选择“资源组”。 Sign in to the Azure portal and select Resource groups.

  2. 在“按名称筛选”文本框中,键入包含 IoT 中心的资源组的名称 。In the Filter by name textbox, type the name of the resource group containing your IoT Hub.

  3. 在结果列表中的资源组右侧,选择“...”,然后选择“删除资源组” 。To the right of your resource group in the result list, select ... then Delete resource group.

    Delete

  4. 系统会要求确认是否删除资源组。You will be asked to confirm the deletion of the resource group. 再次键入资源组的名称进行确认,然后选择“删除” 。Type the name of your resource group again to confirm, and then select Delete. 片刻之后,将会删除该资源组及其包含的所有资源。After a few moments, the resource group and all of its contained resources are deleted.

后续步骤Next steps

在本快速入门中,已从后端应用程序调用了设备上的直接方法,并在模拟设备应用程序中响应了直接方法调用。In this quickstart, you called a direct method on a device from a back-end application, and responded to the direct method call in a simulated device application.

若要了解如何将设备到云的消息路由到云中的不同目标,请继续学习下一教程。To learn how to route device-to-cloud messages to different destinations in the cloud, continue to the next tutorial.