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

教程:使用模拟设备测试与 IoT 中心的连接Tutorial: Use a simulated device to test connectivity with your IoT hub

本教程使用 Azure IoT 中心门户工具和 Azure CLI 命令来测试设备连接性。In this tutorial, you use Azure IoT Hub portal tools and Azure CLI commands to test device connectivity. 本教程还使用简单的可以在台式机上运行的设备模拟器。This tutorial also uses a simple device simulator that you run on your desktop machine.

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

本教程介绍如何执行下列操作:In this tutorial, you learn how to:

  • 检查设备身份验证Check your device authentication
  • 检查设备到云的连接性Check device-to-cloud connectivity
  • 检查云到设备的连接性Check cloud-to-device connectivity
  • 检查设备孪生同步Check device twin synchronization

使用 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.

先决条件Prerequisites

本教程中运行的 CLI 脚本使用适用于 Azure CLI 的 Microsoft Azure IoT 扩展The CLI scripts you run in this tutorial use the Microsoft Azure IoT Extension for Azure CLI. 若要安装此扩展,请运行以下 CLI 命令:To install this extension, run the following CLI command:

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

本教程中运行的设备模拟器应用程序是使用 Node.js 编写的。The device simulator application you run in this tutorial is written using Node.js. 开发计算机上需要有 Node.js v10.x.x 或更高版本。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

https://github.com/Azure-Samples/azure-iot-samples-node/archive/master.zip 下载示例设备模拟器 Node.js 项目并提取 ZIP 存档。Download the sample device simulator Node.js project from https://github.com/Azure-Samples/azure-iot-samples-node/archive/master.zip and extract the ZIP archive.

创建 IoT 中心Create an IoT hub

如果已在以前的快速入门或教程中创建免费层或标准层 IoT 中心,则可跳过此步骤。If you created a free or standard tier IoT hub in a previous quickstart or tutorial, you can skip this step.

若要使用 Azure 门户创建 IoT 中心,请执行以下操作:To create an IoT Hub using the Azure portal:

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

  2. 选择“创建资源” > “物联网” > “IoT 中心” 。Select Create a resource > Internet of Things > IoT Hub.

    选择安装 IoT 中心

  3. 若要创建免费层 IoT 中心,请使用以下表中的值:To create your free-tier IoT hub, use the values in the following tables:

    设置Setting Value
    SubscriptionSubscription 在下拉列表中选择自己的 Azure 订阅。Select your Azure subscription in the drop-down.
    Resource groupResource group 新建。Create new. 本教程使用名称 tutorials-iot-hub-rgThis tutorial uses the name tutorials-iot-hub-rg.
    区域Region 本教程使用“美国西部” 。This tutorial uses West US. 可以选择离你最近的区域。You can choose the region closest to you.
    NameName 以下屏幕截图使用名称 tutorials-iot-hubThe following screenshot uses the name tutorials-iot-hub. 创建中心时,必须选择自己的唯一名称。You must choose your own unique name when you create your hub.

    中心设置 1

    设置Setting Value
    定价和缩放层Pricing and scale tier F1 免费。F1 Free. 你只能在订阅中拥有一个免费层中心。You can only have one free tier hub in a subscription.
    IoT 中心单位IoT Hub units 11

    中心设置 2

  4. 单击“创建”。 Click Create. 创建中心可能需要几分钟。It can take several minutes for the hub to be created.

    中心设置 3

  5. 记下所选的 IoT 中心名称。Make a note of the IoT hub name you chose. 本教程稍后会用到此值。You use this value later in the tutorial.

检查设备身份验证Check device authentication

设备在与中心交换数据之前,必须通过中心进行身份验证。A device must authenticate with your hub before it can exchange any data with the hub. 可以使用门户的“设备管理”部分的 IoT 设备工具来管理设备并检查其使用的身份验证密钥。 You can use the IoT Devices tool in the Device Management section of the portal to manage your devices and check the authentication keys they're using. 在教程的此部分,请添加一个新的测试设备,检索其密钥,并检查此测试设备能否连接到中心。In this section of the tutorial, you add a new test device, retrieve its key, and check that the test device can connect to the hub. 稍后请重置身份验证密钥,观察在设备尝试使用过期密钥时会发生什么情况。Later you reset the authentication key to observe what happens when a device tries to use an outdated key. 教程的此部分使用 Azure 门户来创建、管理和监视设备以及示例 Node.js 设备模拟器。This section of the tutorial uses the Azure portal to create, manage, and monitor a device, and the sample Node.js device simulator.

登录门户,导航到 IoT 中心。Sign in to the portal and navigate to your IoT hub. 然后导航到“IoT 设备”工具: Then navigate to the IoT Devices tool:

“IoT 设备”工具

若要注册新设备,请单击“+ 添加”,将“设备 ID”设置为 MyTestDevice,然后单击“保存”: To register a new device, click + Add, set Device ID to MyTestDevice, and click Save:

添加新设备

若要检索 MyTestDevice 的连接字符串,请在设备列表中单击它,然后复制“连接字符串-主键”的值。 To retrieve the connection string for MyTestDevice, click on it in the list of devices and then copy the Connection string-primary key value. 连接字符串包含设备的共享访问密钥。 The connection string includes the shared access key for the device.

检索设备连接字符串

若要模拟 MyTestDevice 将遥测数据发送到 IoT 中心,请运行以前下载的 Node.js 模拟设备应用程序。To simulate MyTestDevice sending telemetry to your IoT hub, run the Node.js simulated device application you downloaded previously.

在开发计算机的终端窗口中,导航到下载的示例 Node.js 项目的根文件夹。In a terminal window on your development machine, navigate to the root folder of the sample Node.js project you downloaded. 然后导航到 iot-hub\Tutorials\ConnectivityTests 文件夹。Then navigate to the iot-hub\Tutorials\ConnectivityTests folder.

在终端窗口中,运行以下命令以安装所需的库,并运行模拟设备应用程序。In the terminal window, run the following commands to install the required libraries and run the simulated device application. 使用在门户中添加设备时记下的设备连接字符串。Use the device connection string you made a note of when you added the device in the portal.

npm install
node SimulatedDevice-1.js "{your device connection string}"

终端窗口在尝试连接到中心时会显示相关信息:The terminal window displays information as it tries to connect to your hub:

模拟的正在连接的设备

你现在已使用 IoT 中心生成的设备密钥成功地从设备进行了身份验证。You've now successfully authenticated from a device using a device key generated by your IoT hub.

重置密钥Reset keys

在此部分,请重置设备密钥,然后观察模拟的设备尝试进行连接时发生的错误。In this section, you reset the device key and observe the error when the simulated device tries to connect.

若要重置 MyTestDevice 的主设备密钥,请运行以下命令:To reset the primary device key for MyTestDevice, run the following commands:

# Generate a new Base64 encoded key using the current date
read key < <(date +%s | sha256sum | base64 | head -c 32)

# Requires the IoT Extension for Azure CLI
# az extension add --name azure-cli-iot-ext

# Reset the primary device key for MyTestDevice
az iot hub device-identity update --device-id MyTestDevice --set authentication.symmetricKey.primaryKey=$key --hub-name {YourIoTHubName}

在开发计算机的终端窗口中,再次运行模拟的设备应用程序:In the terminal window on your development machine, run the simulated device application again:

npm install
node SimulatedDevice-1.js "{your device connection string}"

这一次会看到应用程序尝试进行连接时发生的身份验证错误:This time you see an authentication error when the application tries to connect:

连接错误

生成共享访问签名 (SAS) 令牌Generate shared access signature (SAS) token

如果设备使用某个 IoT 中心设备 SDK,SDK 库代码会生成用于通过中心进行身份验证的 SAS 令牌。If your device uses one of the IoT Hub device SDKs, the SDK library code generates the SAS token used to authenticate with the hub. 可以通过中心名称、设备名称和设备密钥生成 SAS 令牌。A SAS token is generated from the name of your hub, the name of your device, and the device key.

在某些情况下,例如在云协议网关中或使用自定义身份验证方案的情况下,可能需要自行生成 SAS 令牌。In some scenarios, such as in a cloud protocol gateway or as part of a custom authentication scheme, you may need to generate the SAS token yourself. 若要排查 SAS 生成代码的问题,必须生成可以在测试过程中使用的已知良好的 SAS 令牌。To troubleshoot issues with your SAS generation code, it's useful to generate a known-good SAS token to use during testing.

备注

SimulatedDevice-2.js 示例包括使用 SDK 和不使用 SDK 生成 SAS 令牌的示例。The SimulatedDevice-2.js sample includes examples of generating a SAS token both with and without the SDK.

若要使用 CLI 生成已知良好的 SAS 令牌,请运行以下命令:To generate a known-good SAS token using the CLI, run the following command:

az iot hub generate-sas-token --device-id MyTestDevice --hub-name {YourIoTHubName}

记下已生成的 SAS 令牌的完整文本。Make a note of the full text of the generated SAS token. SAS 令牌如下所示:SharedAccessSignature sr=tutorials-iot-hub.azure-devices.net%2Fdevices%2FMyTestDevice&sig=....&se=1524155307A SAS token looks like the following: SharedAccessSignature sr=tutorials-iot-hub.azure-devices.net%2Fdevices%2FMyTestDevice&sig=....&se=1524155307

在开发计算机的终端窗口中,导航到下载的示例 Node.js 项目的根文件夹。In a terminal window on your development machine, navigate to the root folder of the sample Node.js project you downloaded. 然后导航到 iot-hub\Tutorials\ConnectivityTests 文件夹。Then navigate to the iot-hub\Tutorials\ConnectivityTests folder.

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

npm install
node SimulatedDevice-2.js "{Your SAS token}"

终端窗口在尝试使用 SAS 令牌连接到中心时会显示相关信息:The terminal window displays information as it tries to connect to your hub using the SAS token:

模拟的正在使用令牌进行连接的设备

你现在已使用 CLI 命令生成的测试性 SAS 令牌成功地从设备进行了身份验证。You've now successfully authenticated from a device using a test SAS token generated by a CLI command. SimulatedDevice-2.js 文件包含的示例代码演示了如何在代码中生成 SAS 令牌。The SimulatedDevice-2.js file includes sample code that shows you how to generate a SAS token in code.

协议Protocols

设备可以使用以下任何协议连接到 IoT 中心:A device can use any of the following protocols to connect to your IoT hub:

协议Protocol 出站端口Outbound port
MQTTMQTT 88838883
基于 WebSocket 的 MQTTMQTT over WebSockets 443443
AMQPAMQP 56715671
基于 WebSockets 的 AMQPAMQP over WebSockets 443443
HTTPSHTTPS 443443

如果防火墙阻止了出站端口,则设备无法进行连接:If the outbound port is blocked by a firewall, the device can't connect:

端口被阻止

检查设备到云的连接性Check device-to-cloud connectivity

通常情况下,设备在进行连接以后会尝试向 IoT 中心发送遥测数据。After a device connects, it typically tries to send telemetry to your IoT hub. 此部分介绍如何验证设备发送的遥测数据是否已到达中心。This section shows you how you can verify that the telemetry sent by the device reaches your hub.

首先,请使用以下命令检索模拟设备的当前连接字符串:First, retrieve the current connection string for your simulated device using the following command:

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

若要运行可发送消息的模拟设备,请导航到已下载代码中的 iot-hub\Tutorials\ConnectivityTests 文件夹。To run a simulated device that sends messages, navigate to the iot-hub\Tutorials\ConnectivityTests folder in the code you downloaded.

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

npm install
node SimulatedDevice-3.js "{your device connection string}"

终端窗口在将遥测数据发送到中心时会显示相关信息:The terminal window displays information as it sends telemetry to your hub:

发送消息的模拟设备

可以使用门户中的“指标”来验证遥测消息是否已到达 IoT 中心。 You can use Metrics in the portal to verify that the telemetry messages are reaching your IoT hub. 在“资源”下拉列表中选择 IoT 中心,选择“发送的遥测消息数”作为指标,然后将时间范围设置为“过去一小时”。 Select your IoT hub in the Resource drop-down, select Telemetry messages sent as the metric, and set the time range to Past hour. 图表显示模拟设备发送的消息的聚合计数:The chart shows the aggregate count of messages sent by the simulated device:

显示 IoT 中心指标

启动模拟设备后,指标在数分钟后才会变得可用。It takes a few minutes for the metrics to become available after you start the simulated device.

检查云到设备的连接性Check cloud-to-device connectivity

此部分介绍如何对设备进行测试性的直接方法调用,以便检查云到设备的连接性。This section shows how you can make a test direct method call to a device to check cloud-to-device connectivity. 请在开发计算机上运行模拟设备,以便侦听来自中心的直接方法调用。You run a simulated device on your development machine to listen for direct method calls from your hub.

在终端窗口中,请使用以下命令运行模拟设备应用程序:In a terminal window, use the following command to run the simulated device application:

node SimulatedDevice-3.js "{your device connection string}"

使用 CLI 命令在设备上调用直接方法:Use a CLI command to call a direct method on the device:

az iot hub invoke-device-method --device-id MyTestDevice --method-name TestMethod --timeout 10 --method-payload '{"key":"value"}' --hub-name {YourIoTHubName}

模拟设备在收到直接方法调用后会将一条消息列显到控制台:The simulated device prints a message to the console when it receives a direct method call:

模拟设备接收直接方法调用

模拟设备在成功收到直接方法调用之后,会向中心发送确认:When the simulated device successfully receives the direct method call, it sends an acknowledgement back to the hub:

接收直接方法确认

检查孪生同步Check twin synchronization

设备使用孪生在设备和中心之间同步状态。Devices use twins to synchronize state between the device and the hub. 在此部分,请使用 CLI 命令向设备发送所需属性 ,以及读取设备发送的报告属性。 In this section, you use CLI commands to send desired properties to a device and read the reported properties sent by the device.

在此部分使用的模拟设备只要一启动就会向中心发送报告属性,并且只要一收到所需属性就会将其列显到控制台。The simulated device you use in this section sends reported properties to the hub whenever it starts up, and prints desired properties to the console whenever it receives them.

在终端窗口中,请使用以下命令运行模拟设备应用程序:In a terminal window, use the following command to run the simulated device application:

node SimulatedDevice-3.js "{your device connection string}"

若要验证中心是否已收到设备的报告属性,请使用以下 CLI 命令:To verify that the hub received the reported properties from the device, use the following CLI command:

az iot hub device-twin show --device-id MyTestDevice --hub-name {YourIoTHubName}

在命令的输出中,可以在报告属性部分看到 devicelaststarted 属性。In the output from the command, you can see the devicelaststarted property in the reported properties section. 该属性显示上次启动模拟设备的日期和时间。This property shows the date and time you last started the simulated device.

查看报告属性

若要验证中心是否可以向设备发送所需属性值,请使用以下 CLI 命令:To verify that the hub can send desired property values to the device, use the following CLI command:

az iot hub device-twin update --set properties.desired='{"mydesiredproperty":"propertyvalue"}' --device-id MyTestDevice --hub-name {YourIoTHubName}

模拟设备在收到中心的所需属性更新后会列显一条消息:The simulated device prints a message when it receives a desired property update from the hub:

接收所需属性

除了即时接收所需属性更改,模拟设备还会在启动时自动检查是否存在所需属性。In addition to receiving desired property changes as they're made, the simulated device automatically checks for desired properties when it starts up.

清理资源Clean up resources

如果不再需要 IoT 中心,请在门户中删除该中心与资源组。If you don't need the IoT hub any longer, delete it and the resource group in the portal. 为此,请选择包含 IoT 中心的 tutorials-iot-hub-rg 资源组,然后单击“删除” 。To do so, select the tutorials-iot-hub-rg resource group that contains your IoT hub and click Delete.

后续步骤Next steps

本教程介绍了如何检查设备密钥、如何检查设备到云的连接性、如何检查云到设备的连接性,以及如何检查设备孪生同步。In this tutorial, you've seen how to check your device keys, check device-to-cloud connectivity, check cloud-to-device connectivity, and check device twin synchronization. 若要详细了解如何监视 IoT 中心,请访问有关 IoT 中心监视的操作方法文章。To learn more about how to monitor your IoT hub, visit the how-to article for IoT Hub monitoring.