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

如何将在 Linux 或 Windows 上运行的 IoT 即插即用 bridge 示例连接到 IoT 中心How to connect an IoT Plug and Play bridge sample running on Linux or Windows to IoT Hub

本文说明如何构建 IoT 即插即用桥的示例环境适配器,如何将其连接到 IoT 中心,以及如何使用 Azure IoT 资源管理器工具查看它发送的遥测数据。This article shows you how to build the IoT Plug and Play bridge's sample environmental adapter, connect it to your IoT hub, and use the Azure IoT explorer tool to view the telemetry it sends. IoT 即插即用 bridge 用 C 语言编写,包括适用于 C 语言的 Azure IoT 设备 SDK。本教程结束时,你应该能够运行 IoT 即插即用 bridge,并在 Azure IoT 资源管理器中查看它报告遥测:The IoT Plug and Play bridge is written in C and includes the Azure IoT device SDK for C. By the end of this tutorial you should be able to run the IoT Plug and Play bridge and see it report telemetry in Azure IoT explorer:

显示 Azure IoT 资源管理器的屏幕截图,其中包含一个报告的遥测 (湿度,温度从 Iot 即插即用 bridge) 。

先决条件Prerequisites

您可以在 Windows 或 Linux 一文中运行该示例。You can run the sample in the article on Windows or Linux. 本操作方法指南中的 shell 命令遵循适用于路径分隔符 "" 的 Windows 约定 \ ,如果遵循 Linux,请确保为 "" 交换这些分隔符 /The shell commands in this how-to guide follow the Windows convention for path separators '\', if you're following along on Linux be sure to swap these separators for '/'.

Azure IoT 资源管理器Azure IoT explorer

若要与本文第二部分中的示例设备进行交互,请使用 Azure IoT 浏览器 工具。To interact with the sample device in the second part of this article, you use the Azure IoT explorer tool. 为操作系统下载并安装最新版本的 Azure IoT 资源管理器Download and install the latest release of Azure IoT explorer for your operating system.

准备 IoT 中心Prepare an IoT hub

Azure 订阅中需要有一个 Azure IoT 中心才能完成本文中的步骤。You need an Azure IoT hub in your Azure subscription to complete the steps in this article. 如果没有 Azure 订阅,请在开始之前创建一个免费帐户If you don't have an Azure subscription, create a free account before you begin.

如果要在本地使用 Azure CLI,请先使用 az login 登录到 Azure 订阅。If you're using the Azure CLI locally, first sign in to your Azure subscription using az login. 如果在 Azure Cloud Shell 中运行这些命令,则会自动登录。If you're running these commands in the Azure Cloud Shell, you're signed in automatically.

如果在本地使用 Azure CLI,则 az 的版本应为 2.8.0 或更高版本;Azure Cloud Shell 使用最新版本。If you're using the Azure CLI locally, the az version should be 2.8.0 or later; the Azure Cloud Shell uses the latest version. 使用 az --version 命令检查计算机上安装的版本。Use the az --version command to check the version installed on your machine.

运行以下命令将用于 Azure CLI 的 Microsoft Azure IoT 扩展添加到你的实例:Run the following command to add the Microsoft Azure IoT Extension for Azure CLI to your instance:

az extension add --name azure-iot

如果还没有可使用的 IoT 中心,请运行以下命令,以在订阅中创建资源组和免费层的 IoT 中心。If you don't already have an IoT hub to use, run the following commands to create a resource group and a free-tier IoT hub in your subscription. <YourIoTHubName> 替换为所选的中心名称:Replace <YourIoTHubName> with a hub name of your choice:

az group create --name my-pnp-resourcegroup \
    --location centralus
az iot hub create --name <YourIoTHubName> \
    --resource-group my-pnp-resourcegroup --sku F1

运行以下命令,在 IoT 中心创建设备标识。Run the following command to create the device identity in your IoT hub. <YourIoTHubName><YourDeviceID> 占位符替换为你自己的“IoT 中心名称”和所选“设备 ID” 。Replace the <YourIoTHubName> and <YourDeviceID> placeholders with your own IoT Hub name and a device ID of your choice.

az iot hub device-identity create --hub-name <YourIoTHubName> --device-id <YourDeviceID>

运行以下命令以获取中心的 IoT 中心连接字符串Run the following command to get the IoT Hub connection string for your hub. 记下此连接字符串,稍后在本文中使用它:Make a note of this connection string, you use it later in this article:

az iot hub show-connection-string --hub-name <YourIoTHubName> --output table

运行以下命令,获取已添加到中心的设备的设备连接字符串。Run the following command to get the device connection string for the device you added to the hub. 记下此连接字符串,稍后在本文中使用它:Make a note of this connection string, you use it later in this article:

az iot hub device-identity show-connection-string --hub-name <YourIoTHubName> --device-id <YourDeviceID> --output table

下载并运行桥接Download and run the bridge

本文介绍了两个运行桥的选项。In this article, you have two options to run the bridge. 方法:You can:

  • 下载预生成的可执行文件,并按本部分中所述运行该可执行文件。Download a prebuilt executable and run it as described in this section.
  • 下载源代码,然后 生成并运行桥 ,如以下部分所述。Download the source code and then build and run the bridge as described in the following section.

下载并运行桥:To download and run the bridge:

  1. 中转到 IoT 即插即用 版本 "页Go to the IoT Plug and Play releases page.

  2. 下载适用于你的操作系统的预生成的可执行文件:适用于 Windows 的 pnpbridge_bin.exe 或适用于 Linux 的 pnpbridge_binDownload the prebuilt executable for your operating system: pnpbridge_bin.exe for Windows, or pnpbridge_bin for Linux.

  3. 下载环境传感器示例的配置文件的示例 config.jsDownload the sample config.json configuration file for the environmental sensor sample. 请确保配置文件与可执行文件位于同一文件夹中。Make sure that the configuration file is in the same folder as the executable.

  4. 编辑文件 上的config.jsEdit the config.json file:

    • 添加 connection-string 一个值,该值是之前记下的 设备连接字符串Add the connection-string value that's the device connection string you made a note of previously.
    • 添加 symmetric_key 来自 设备连接字符串 的 "共享访问密钥" 值。Add the symmetric_key value that's shared access key value from the device connection string.
    • root_interface_model_id 值替换为 dtmi:com:example:PnpBridgeEnvironmentalSensor;1Replace the root_interface_model_id value with dtmi:com:example:PnpBridgeEnvironmentalSensor;1.

    文件 config.js 的第一部分现在类似于以下代码片段:The first section of the config.json file now looks like the following snippet:

    {
      "$schema": "../../../pnpbridge/src/pnpbridge_config_schema.json",
      "pnp_bridge_connection_parameters": {
        "connection_type" : "connection_string",
        "connection_string" : "HostName=youriothub.azure-devices.net;DeviceId=yourdevice;SharedAccessKey=TTrz8fR7ylHKt7DC/e/e2xocCa5VIcq5x9iQKxKFVa8=",
        "root_interface_model_id": "dtmi:com:example:PnpBridgeEnvironmentalSensor;1",
        "auth_parameters": {
            "auth_type": "symmetric_key",
            "symmetric_key": "TTrz8fR7ylHKt7DC/e/e2xocCa5VIcq5x9iQKxKFVa8="
        },
    
  5. 在命令行环境中运行可执行文件。 桥生成如下所示的输出:The bridge generates output that looks like:

    c:\temp\temp-bridge>dir
     Volume in drive C is OSDisk
     Volume Serial Number is 38F7-DA4A
    
     Directory of c:\temp\temp-bridge
    
    10/12/2020  12:24    <DIR>          .
    10/12/2020  12:24    <DIR>          ..
    08/12/2020  15:26             1,216 config.json
    10/12/2020  12:21         3,617,280 pnpbridge_bin.exe
                   2 File(s)      3,618,496 bytes
                   2 Dir(s)  12,999,147,520 bytes free
    
    c:\temp\temp-bridge>pnpbridge_bin.exe
    Info:
     -- Press Ctrl+C to stop PnpBridge
    
    Info: Using default configuration location
    Info: Starting Azure PnpBridge
    Info: Pnp Bridge is running as am IoT egde device.
    Info: Pnp Bridge creation succeeded.
    Info: Connection_type is [connection_string]
    Info: Tracing is disabled
    Info: WARNING: SharedAccessKey is included in connection string. Ignoring symmetric_key in config file.
    Info: IoT Edge Device configuration initialized successfully
    Info: Building Pnp Bridge Adapter Manager, Adapters & Components
    Info: Adapter with identity environment-sensor-sample-pnp-adapter does not have any associated global parameters. Proceeding with adapter creation.
    Info: Pnp Adapter with adapter ID environment-sensor-sample-pnp-adapter has been created.
    Info: Pnp Adapter Manager created successfully.
    Info: Pnp components created successfully.
    Info: Pnp components built in model successfully.
    Info: Connected to Azure IoT Hub
    Info: Environmental Sensor: Starting Pnp Component
    Info: IoTHub client call to _SendReportedState succeeded
    Info: Environmental Sensor Adapter:: Sending device information property to IoTHub. propertyName=state, propertyValue=true
    Info: Pnp components started successfully.
    

构建并运行桥Build and run the bridge

如果你希望自行生成可执行文件,则可以下载源代码和生成脚本。If you prefer to build the executable yourself, you can download the source code and build scripts.

在所选文件夹中打开命令提示符。Open a command prompt in a folder of your choice. 运行以下命令,将 IoT 即插即用 bridge GitHub 存储库克隆到此位置:Run the following command to clone the IoT Plug and Play bridge GitHub repository into this location:

git clone https://github.com/Azure/iot-plug-and-play-bridge.git

克隆存储库后,请更新子模块。After you clone the repository, update the submodules. 子模块包括适用于 C 语言的 Azure IoT SDK:The submodules include the Azure IoT SDK for C:

cd iot-plug-and-play-bridge
git submodule update --init --recursive

此操作需要几分钟才能完成。Expect this operation to take several minutes to complete.

提示

如果遇到 git 克隆子模块更新失败的问题,则这是 Windows 文件路径的已知问题。If you run into issues with the git clone sub module update failing, this is a known issue with Windows file paths. 可以尝试以下命令来解决问题: git config --system core.longpaths trueYou can try the following command to resolve the issue: git config --system core.longpaths true

构建桥的先决条件在操作系统上有所不同:The prerequisites for building the bridge differ by operating system:

WindowsWindows

若要在 Windows 上构建 IoT 即插即用 bridge,请安装以下软件:To build the IoT Plug and Play bridge on Windows, install the following software:

LinuxLinux

本文假设你使用 Ubuntu Linux。This article assumes you're using Ubuntu Linux. 本文中的步骤使用 Ubuntu 18.04 进行了测试。The steps in this article were tested using Ubuntu 18.04.

若要在 Linux 上构建 IoT 即插即用 bridge,请使用命令安装 GCCGitcmake 和所有必需的依赖项 apt-getTo build the IoT Plug and Play bridge on Linux, install GCC, Git, cmake, and all the required dependencies using the apt-get command:

sudo apt-get update
sudo apt-get install -y git cmake build-essential curl libcurl4-openssl-dev libssl-dev uuid-dev

验证 cmake 的版本是否高于 2.8.12,GCC 的版本是否高于 4.4.7 。Verify the version of cmake is above 2.8.12 and the version of GCC is above 4.4.7.

cmake --version
gcc --version

构建 IoT 即插即用 bridgeBuild the IoT Plug and Play bridge

导航到存储库目录中的 pnpbridge 文件夹。Navigate to the pnpbridge folder in the repository directory.

对于 Windows,请在 适用于 Visual Studio 的开发人员命令提示中运行以下内容:For Windows run the following in a Developer Command Prompt for Visual Studio:

cd scripts\windows
build.cmd

同样,对于 Linux,请运行以下内容:Similarly for Linux run the following:

cd scripts/linux
./setup.sh
./build.sh

提示

在 Windows 上,可以在 Visual Studio 2019 中打开 cmake 命令生成的解决方案。On Windows, you can open the solution generated by the cmake command in Visual Studio 2019. 在 cmake 目录中打开 azure_iot_pnp_bridge .sln 项目文件,并将 pnpbridge_bin 项目设置为解决方案的启动项目。Open the azure_iot_pnp_bridge.sln project file in the cmake directory and set the pnpbridge_bin project as the startup project in the solution. 现在可以在 Visual Studio 中生成示例,并在调试模式下运行它。You can now build the sample in Visual Studio and run it in debug mode.

编辑配置文件Edit the configuration file

可以在 IoT 即插即用 bridge 概念文档中了解有关配置文件的详细信息。You can learn more about config files in the IoT Plug and Play bridge concepts document.

在文本编辑器中打开文件 上的iot-plug-and-play-bridge\pnpbridge\src\adapters\samples\environmental_sensor\config.jsOpen the the iot-plug-and-play-bridge\pnpbridge\src\adapters\samples\environmental_sensor\config.json file in a text editor.

  • 添加 connection-string 一个值,该值是之前记下的 设备连接字符串Add the connection-string value that's the device connection string you made a note of previously.
  • 添加 symmetric_key 来自 设备连接字符串 的 "共享访问密钥" 值。Add the symmetric_key value that's shared access key value from the device connection string.
  • root_interface_model_id 值替换为 dtmi:com:example:PnpBridgeEnvironmentalSensor;1Replace the root_interface_model_id value with dtmi:com:example:PnpBridgeEnvironmentalSensor;1.

文件 config.js 的第一部分现在类似于以下代码片段:The first section of the config.json file now looks like the following snippet:

{
  "$schema": "../../../pnpbridge/src/pnpbridge_config_schema.json",
  "pnp_bridge_connection_parameters": {
    "connection_type" : "connection_string",
    "connection_string" : "HostName=youriothub.azure-devices.net;DeviceId=yourdevice;SharedAccessKey=TTrz8fR7ylHKt7DC/e/e2xocCa5VIcq5x9iQKxKFVa8=",
    "root_interface_model_id": "dtmi:com:example:PnpBridgeEnvironmentalSensor;1",
    "auth_parameters": {
        "auth_type": "symmetric_key",
        "symmetric_key": "TTrz8fR7ylHKt7DC/e/e2xocCa5VIcq5x9iQKxKFVa8="
    },

运行 IoT 即插即用 bridgeRun the IoT Plug and Play bridge

启动 IoT 即插即用 bridge 环境传感器示例。Start the IoT Plug and Play bridge environmental sensor sample. 参数是 config.json 在上一节中编辑的文件的路径:The parameter is the path to config.json file you edited in the previous section:

REM Windows
cd iot-plug-and-play-bridge\pnpbridge\cmake\pnpbridge_x86\src\pnpbridge\samples\console
Debug\pnpbridge_bin.exe ..\..\..\..\..\..\src\adapters\samples\environmental_sensor\config.json

桥生成如下所示的输出:The bridge generates output that looks like:

c:\temp>cd iot-plug-and-play-bridge\pnpbridge\cmake\pnpbridge_x86\src\pnpbridge\samples\console

c:\temp\iot-plug-and-play-bridge\pnpbridge\cmake\pnpbridge_x86\src\pnpbridge\samples\console>Debug\pnpbridge_bin.exe ..\..\..\..\..\..\src\adapters\samples\environmental_sensor\config.json
Info:
 -- Press Ctrl+C to stop PnpBridge

Info: Using configuration from specified file path: ..\..\..\..\..\..\src\adapters\samples\environmental_sensor\config.json
Info: Starting Azure PnpBridge
Info: Pnp Bridge is running as am IoT egde device.
Info: Pnp Bridge creation succeeded.
Info: Connection_type is [connection_string]
Info: Tracing is disabled
Info: WARNING: SharedAccessKey is included in connection string. Ignoring symmetric_key in config file.
Info: IoT Edge Device configuration initialized successfully
Info: Building Pnp Bridge Adapter Manager, Adapters & Components
Info: Adapter with identity environment-sensor-sample-pnp-adapter does not have any associated global parameters. Proceeding with adapter creation.
Info: Pnp Adapter with adapter ID environment-sensor-sample-pnp-adapter has been created.
Info: Pnp Adapter Manager created successfully.
Info: Pnp components created successfully.
Info: Pnp components built in model successfully.
Info: Connected to Azure IoT Hub
Info: Environmental Sensor: Starting Pnp Component
Info: IoTHub client call to _SendReportedState succeeded
Info: Environmental Sensor Adapter:: Sending device information property to IoTHub. propertyName=state, propertyValue=true
Info: Pnp components started successfully.
Info: IoTHub client call to _SendEventAsync succeeded
Info: PnpBridge_PnpBridgeStateTelemetryCallback called, result=0, telemetry=PnpBridge configuration complete
Info: Processing property update for the device or module twin
Info: Environmental Sensor Adapter:: Successfully delivered telemetry message for <environmentalSensor>

使用以下命令在 Linux 上运行桥:Use the following commands to run the bridge on Linux:

cd iot-plug-and-play-bridge/pnpbridge/cmake/pnpbridge_x86/src/pnpbridge/samples/console
./pnpbridge_bin ../../../../../../src/adapters/samples/environmental_sensor/config.json

下载模型文件Download the model files

稍后使用 Azure IoT 浏览器在连接到 IoT 中心时查看设备。You use Azure IoT Explorer later to view the device when it connects to your IoT hub. Azure IoT 浏览器需要模型文件的本地副本,该副本与设备发送的 模型 ID 匹配。Azure IoT Explorer needs a local copy of the model file that matches the Model ID your device sends. 通过模型文件,IoT 管理器可以显示设备实现的遥测、属性和命令。The model file lets the IoT Explorer display the telemetry, properties, and commands that your device implements.

下载 Azure IoT 资源管理器的模型:To download the models for Azure IoT explorer:

  1. 在本地计算机上创建名为 models 的文件夹。Create a folder called models on your local machine.
  2. EnvironmentalSensor.js 保存到你在上一步中创建的 " 模型 " 文件夹。Save EnvironmentalSensor.json to the models folder you created in the previous step.
  3. 如果在文本编辑器中打开此模型文件,则可以看到模型将组件定义 dtmi:com:example:PnpBridgeEnvironmentalSensor;1 为其 ID。If you open this model file in a text editor, you can see the the model defines a component with dtmi:com:example:PnpBridgeEnvironmentalSensor;1 as its ID. 这与你在 config.js 文件中使用的模型 ID 相同。This is the same model ID you used in the config.json file.

使用 Azure IoT 资源管理器验证代码Use Azure IoT explorer to validate the code

桥启动后,使用 Azure IoT 资源管理器工具验证它是否正常工作。After the bridge starts, use the Azure IoT explorer tool to verify it's working. 您可以查看模型中定义的遥测、属性和命令 dtmi:com:example:PnpBridgeEnvironmentalSensor;1You can see the telemetry, properties, and commands defined in the dtmi:com:example:PnpBridgeEnvironmentalSensor;1 model.

  1. 打开 Azure IoT 资源管理器。Open Azure IoT explorer.

  2. 在“IoT 中心”页上,如果尚未将连接添加到 IoT 中心,请选择“+ 添加连接”。On the IoT hubs page, if you haven't already added a connection to your IoT hub, select + Add connection. 输入先前创建的 IoT 中心的连接字符串,然后选择“保存”。Enter the connection string for the IoT hub you created previously and select Save.

  3. 在“IoT 即插即用设置”页上,选择“+ 添加”>“本地文件夹”,然后选择在其中保存了模型文件的本地“模型”文件夹。On the IoT Plug and Play Settings page, select + Add > Local folder and select the local models folder where you saved your model files.

  4. 在“IoT 中心”页上,单击要使用的中心的名称。On the IoT hubs page, click on the name of the hub you want to work with. 你将看到已注册到 IoT 中心的设备的列表。You see a list of devices registered to the IoT hub.

  5. 单击前面创建的设备的“设备 ID”。Click on the Device ID of the device you created previously.

  6. 左侧菜单显示了可用于设备的不同类型的信息。The menu on the left shows the different types of information available for the device.

  7. 选择“IoT 即插即用组件”以查看设备的模型信息。Select IoT Plug and Play components to view the model information for your device.

  8. 可以查看设备的不同组件。You can view the different components of the device. 默认组件和任何其他组件。The default component and any additional ones. 选择要使用的组件。Select a component to work with.

  9. 选择“遥测”页,然后选择“开始”,查看设备正在为此组件发送的遥测数据。Select the Telemetry page and then select Start to view the telemetry data the device is sending for this component.

  10. 选择“属性(只读)”页以查看为此组件报告的只读属性。Select the Properties (read-only) page to view the read-only properties reported for this component.

  11. 选择“属性(可写)”页以查看可以为此组件更新的可写属性。Select the Properties (writable) page to view the writable properties you can update for this component.

  12. 按名称选择属性,为其输入新值,然后选择“更新所需值”。Select a property by it's name, enter a new value for it, and select Update desired value.

  13. 若要查看显示的新值,请选择“刷新”按钮。To see the new value show up select the Refresh button.

  14. 选择“命令”页以查看此组件的所有命令。Select the Commands page to view all the commands for this component.

  15. 选择要测试参数的命令(如果有)。Select the command you want to test set the parameter if any. 选择“发送命令”以调用设备上的命令。Select Send command to call the command on the device. 可以在正在运行示例代码的命令提示符窗口中看到你的设备响应命令。You can see your device respond to the command in the command prompt window where the sample code is running.

清理资源Clean up resources

如果打算继续学习其他 IoT 即插即用文章,则可保留并重复使用在本文中使用的资源。If you plan to continue with additional IoT Plug and Play articles, you can keep and reuse the resources you used in this article. 否则,可删除在本文中创建的资源,以免产生额外的费用。Otherwise, you can delete the resources you created in this article to avoid additional charges.

可通过使用以下 Azure CLI 命令删除整个资源组来一次性删除中心和注册设备。You can delete both the hub and registered device at once by deleting the entire resource group with the following Azure CLI command. 如果这些资源与你想要保留的其他资源共享一个资源组,则不要使用此命令。Don't use this command if these resources are sharing a resource group with other resources you want to keep.

az group delete --name <YourResourceGroupName>

若要仅删除 IoT 中心,请使用 Azure CLI 运行以下命令:To delete just the IoT hub, run the following command using Azure CLI:

az iot hub delete --name <YourIoTHubName>

若要仅删除注册到 IoT 中心的设备标识,请使用 Azure CLI 运行以下命令:To delete just the device identity you registered with your IoT hub, run the following command using Azure CLI:

az iot hub device-identity delete --hub-name <YourIoTHubName> --device-id <YourDeviceID>

你可能还需要从开发计算机中删除克隆的示例文件。You may also want to remove the cloned sample files from your development machine.

后续步骤Next steps

本文介绍了如何将 IoT 即插即用设备连接到 IoT 中心。In this article, you've learned how to connect an IoT Plug and Play device to an IoT hub. 若要详细了解如何生成可与 IoT 即插即用设备交互的解决方案,请参阅:To learn more about how to build a solution that interacts with your IoT Plug and Play devices, see: