您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:通过 IoT 中心设备流在 Node.js 中与设备应用程序通信(预览)Quickstart: Communicate to a device application in Node.js via IoT Hub device streams (preview)

Microsoft Azure IoT 中心目前支持设备流作为预览版功能Microsoft Azure IoT Hub currently supports device streams as a preview feature.

服务和设备应用程序可以使用 IoT 中心设备流以安全且防火墙友好的方式进行通信。IoT Hub device streams allow service and device applications to communicate in a secure and firewall-friendly manner. 在公共预览期,Node.js SDK 仅支持服务端的设备流。During public preview, Node.js SDK only supports device streams on the service side. 因此,本快速入门只介绍如何运行服务端应用程序。As a result, this quickstart only covers instructions to run the service-side application. 你应当运行下述快速入门之一附带的设备端应用程序:You should run an accompanying device-side application from one of the following quickstarts:

本快速入门中的服务端 Node.js 应用程序具有以下功能:The service-side Node.js application in this quickstart has the following functionalities:

  • 创建发往 IoT 设备的设备流。Creates a device stream to an IoT device.

  • 从命令行读取输入,将其发送到设备应用程序,后者会将其回显。Reads input from command line and sends it to the device application, which will echo it back.

代码将演示设备流的启动过程,以及如何用其来发送和接收数据。The code will demonstrate the initiation process of a device stream, as well as how to use it to send and receive data.

使用 Azure Cloud ShellUse Azure Cloud Shell

Azure 托管 Azure Cloud Shell(一个可通过浏览器使用的交互式 shell 环境)。Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. 通过 Cloud Shell 可以将 bashPowerShell 与 Azure 服务配合使用。Cloud Shell lets you use either bash or PowerShell to work with Azure services. 可以使用 Azure Cloud Shell 预安装的命令来运行本文中的代码,而不必在本地环境中安装任何内容。You can use the Cloud Shell pre-installed commands to run the code in this article without having to install anything on your local environment.

若要启动 Azure Cloud Shell,请执行以下操作:To launch Azure Cloud Shell:

选项Option 示例/链接Example/Link
选择代码块右上角的“试用”。 Select Try It in the upper-right corner of a code block. 选择“试用” 不会自动将代码复制到 Cloud Shell。Selecting Try It doesn't automatically copy the code to Cloud Shell. Azure Cloud Shell 的“试用”示例
转到 https://shell.azure.com 或选择“启动 Cloud Shell” 按钮可在浏览器中打开 Cloud Shell。Go to https://shell.azure.com or select the Launch Cloud Shell button to open Cloud Shell in your browser. 在新窗口中启动 Cloud ShellLaunch Cloud Shell in a new window
选择 Azure 门户右上方菜单栏中的“Cloud Shell” 按钮。Select the Cloud Shell button on the top-right menu bar in the Azure portal. Azure 门户中的“Cloud Shell”按钮

若要在 Azure Cloud Shell 中运行本文中的代码,请执行以下操作:To run the code in this article in Azure Cloud Shell:

  1. 启动 Cloud Shell。Launch Cloud Shell.
  2. 选择代码块上的“复制”按钮 以复制代码。Select the Copy button on a code block to copy the code.
  3. 在 Windows 和 Linux 上使用 Ctrl+Shift+V 将代码粘贴到 Cloud Shell 会话中,或在 macOS 上使用 Cmd+Shift+V 将代码粘贴到 Cloud Shell 会话中。Paste the code into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS.
  4. Enter 运行此代码。Press Enter to run the code.

如果还没有 Azure 订阅,可以在开始前创建一个免费帐户If you don’t have an Azure subscription, create a free account before you begin.

先决条件Prerequisites

目前仅以下区域中创建的 IoT 中心支持设备流预览:The preview of device streams is currently only supported for IoT Hubs created in the following regions:

  • 美国中部 Central US

  • 美国中部 EUAPCentral US EUAP

若要运行本快速入门中所述的服务端应用程序,需要在开发计算机上安装 Node.js v10.x.x 或更高版本。To run the service-side application in this quickstart you need Node.js v10.x.x or later on your development machine.

可从 Nodejs.org 为下载适用于多个平台的 Node.js。You can download Node.js for multiple platforms from Nodejs.org.

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

node --version

运行以下命令将用于 Azure CLI 的 Microsoft Azure IoT 扩展添加到 Cloud Shell 实例。Run the following command to add the Microsoft Azure IoT Extension for Azure CLI to your Cloud Shell instance. 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-node/archive/streams-preview.zip 下载示例 Node.js 项目并提取 ZIP 存档。If you haven't already done so, download the sample Node.js project from https://github.com/Azure-Samples/azure-iot-samples-node/archive/streams-preview.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 by using the Azure portal.

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

  2. 选择“创建资源”,然后选择“物联网”。 Select Create a resource, and then select Internet of Things.

  3. 在右侧的列表中选择“IoT 中心”。 In the list at the right, select Iot Hub. 此时会打开用于创建 IoT 中心的第一个页面。The first page for creating an IoT hub opens.

    在 Azure 门户中创建 IoT 中心

    填写字段:Fill in the fields:

    a.a. 在“订阅”下拉列表中,选择要用于 IoT 中心的订阅。 In the Subscription drop-down list, select the subscription to use for your IoT hub.

    b.b. 对于“资源组”,请执行以下操作之一: For Resource Group, do either of the following:

    • 若要创建新的资源组,请选择“新建”,然后输入所需的名称 。To create a new resource group, select Create new and enter the name you want to use.

    • 若要使用现有资源组,请选择“使用现有项”,然后在下拉列表中选择该资源组。 To use an existing resource group, select Use existing and then, in the drop-down list, select the resource group.

      有关详细信息,请参阅管理 Azure 资源管理器资源组For more information, see Manage Azure Resource Manager resource groups.

    c.c. 在“区域”下拉列表中,选择要在其中创建中心的区域。 In the Region drop-down list, select the region in which you want your hub to be located. 选择支持 IoT 中心设备流预览版的区域:“美国中部”或“美国中部 EUAP”。 Select a region that supports the IoT Hub device streams preview, either Central US or Central US EUAP.

    d.d. 在“IoT 中心名称”框中,输入 IoT 中心的名称。 In the IoT Hub Name box, enter the name for your IoT hub. 该名称必须全局唯一。The name must be globally unique. 如果输入的名称可用,会显示一个绿色复选标记。If the name you enter is available, a green check mark appears.

    重要

    由于 IoT 中心将作为 DNS 终结点公开可发现,因此请务必避免在命名它时输入任何敏感信息或个人身份信息。Because the IoT hub will be publicly discoverable as a DNS endpoint, be sure to avoid entering any sensitive or personally identifiable information when you name it.

  4. 若要继续创建 IoT 中心,请选择“下一步: 大小和规模”。To continue creating your IoT hub, select Next: Size and scale.

    使用 Azure 门户为新的 IoT 中心设置大小和规模

    在此窗格中,可以接受默认设置并选择底部的“查看 + 创建”。 In this pane, you can accept the default settings and select Review + create at the bottom. 请考虑以下选项:Consider the following options:

    • 在“定价和规模层”下拉列表中,选择一个标准层(“S1”、“S2”或“S3”),或选择“F1: 免费层”。In the Pricing and scale tier drop-down list, select one of the standard tiers (S1, S2, or S3) or F1: Free tier. 也可根据队列大小以及预期在中心会出现的非流式处理工作负荷(例如遥测消息)完成该选择。This choice can also be guided by the size of your fleet and the non-streaming workloads that you expect in your hub (for example, telemetry messages). 例如,免费层适用于测试和评估。For example, 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 中心单元数”: 此项选择取决于中心内预期会出现的非流式处理工作负荷。For Number of IoT Hub units: This choice depends on non-streaming workload you expect in your hub. 暂时可以选择“1”。You can select 1 for now.

    有关层选项的详细信息,请参阅选择适当的 IoT 中心层For more information about tier options, see Choose the right IoT hub tier.

  5. 若要检查所做的选择,请选择“查看+创建”选项卡。 此时会打开如下所示的窗格:To review your choices, select the Review + create tab. The pane that opens is similar to the following:

    用于创建新 IoT 中心的信息

  6. 若要创建新的 IoT 中心,请选择“创建” 。To create your new IoT hub, select Create. 该过程需要花费几分钟时间。The process 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 Cloud Shell 来注册模拟设备。In this quickstart, you use the Azure Cloud Shell to register a simulated device.

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

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

    MyDevice:这是为注册的设备提供的名称。MyDevice: This is the name given for the registered device. 如示例中所示使用 MyDevice。Use MyDevice as shown. 如果为设备选择不同名称,则可能还需要在本文中从头至尾使用该名称,并在运行示例应用程序之前在其中更新设备名称。If you choose a different name for your device, you will 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 MyDevice
    
  2. 还需一个服务连接字符串,以便后端应用程序能够连接到 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
    

    记下返回的值,如下所示:Make a note of the returned value, which looks like this:

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

通过设备流在设备和服务之间通信Communicate between device and service via device streams

在本部分中,你将运行设备端应用程序和服务器端应用程序并在两者之间进行通信。In this section, you run both the device-side application and the service-side application and communicate between the two.

运行设备端应用程序Run the device-side application

如前所述,IoT 中心 Node.js SDK 仅支持服务端的设备流。As mentioned earlier, IoT Hub Node.js SDK only supports device streams on the service side. 对于设备端应用程序,请使用以下快速入门之一附带的设备程序:For device-side application, use the accompanying device program available in one of these quickstarts:

在继续下一步之前,请确保设备端应用程序正在运行。Ensure the device-side application is running before proceeding to the next step.

运行服务端应用程序Run the service-side application

假设设备端应用程序正在运行,请遵循以下步骤运行以 Node.js 编写的服务端应用程序:Assuming the device-side application is running, follow the steps below to run the service-side application in Node.js:

  • 以环境变量的形式提供服务凭据和设备 ID。Provide your service credentials and device ID as environment variables.

    # In Linux
    export IOTHUB_CONNECTION_STRING="<provide_your_service_connection_string>"
    export STREAMING_TARGET_DEVICE="MyDevice"
    
    # In Windows
    SET IOTHUB_CONNECTION_STRING=<provide_your_service_connection_string>
    SET STREAMING_TARGET_DEVICE=MyDevice
    

    MyDevice 更改为你给设备选择的设备 ID。Change MyDevice to the device ID you chose for your device.

  • 导航到解压缩的项目文件夹中的 Quickstarts/device-streams-service,并使用节点来运行示例。Navigate to Quickstarts/device-streams-service in your unzipped project folder and run the sample using node.

    cd azure-iot-samples-node-streams-preview/iot-hub/Quickstarts/device-streams-service
    
    # Install the preview service SDK, and other dependencies
    npm install azure-iothub@streams-preview
    npm install
    
    node echo.js
    

在最后一步结束时,服务端程序会启动一个发往设备的流,在该流建立后就会通过其将字符串缓冲区发送到服务。At the end of the last step, the service-side program will initiate a stream to your device and once established will send a string buffer to the service over the stream. 在此示例中,服务端程序直接读取终端的 stdin 并将其发送到设备,后者然后将其回显。In this sample, the service-side program simply reads the stdin on the terminal and sends it to the device, which will then echo it back. 这演示了两个应用程序之间成功进行的双向通信。This demonstrates successful bidirectional communication between the two applications.

服务端控制台输出

然后可以再次按 Enter,将程序终止。You can then terminate the program by pressing enter again.

清理资源Clean up resources

如果你打算继续学习下一篇建议的文章,可以保留并重复使用已创建的资源。If you plan to continue to the next recommended article, you can keep and reuse the resources you've already created.

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

重要

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

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

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

  2. 在“按名称筛选”框中,输入包含你的 IoT 中心的资源组的名称。 In the Filter by name box, enter the name of the resource group that contains your IoT hub.

  3. 在结果列表中你的资源组的右侧,选择 ( ... ),然后选择“删除资源组” 。In the result list, to the right of your resource group, select the ellipsis (...), and then select Delete resource group.

    “删除资源组”按钮

  4. 若要确认删除该资源组,请重新输入资源组名称,然后选择“删除”。 To confirm the deletion of the resource group, reenter the resource group name, and then select Delete. 片刻之后,将会删除该资源组及其包含的所有资源。After a few moments, the resource group and all its contained resources are deleted.

后续步骤Next steps

在本快速入门中,你设置了一个 IoT 中心、注册了一个设备、在设备和服务端的应用程序之间建立了一个设备流,并通过该流在应用程序之间来回发送数据。In this quickstart, you have set up an IoT hub, registered a device, established a device stream between applications on the device and service side, and used the stream to send data back and forth between the applications.

请使用以下链接详细了解设备流:Use the links below to learn more about device streams: