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

教程:将 Linux 或 Windows 上运行的 IoT 即插即用多组件设备应用程序连接到 IoT 中心Tutorial: Connect an IoT Plug and Play multiple component device applications running on Linux or Windows to IoT Hub

本教程介绍如何使用组件生成示例 IoT 即插即用设备应用程序,将其连接到 IoT 中心,并使用 Azure IoT 资源管理器工具来查看它发送到中心的信息。This tutorial shows you how to build a sample IoT Plug and Play device application with components, connect it to your IoT hub, and use the Azure IoT explorer tool to view the information it sends to the hub. 该示例应用程序以 C 编写,包含在适用于 C 的 Azure IoT 设备 SDK 中。解决方案构建者可以使用 Azure IoT 资源管理器工具来了解 IoT 即插即用设备的功能,而无需查看任何设备代码。The sample application is written in C and is included in the Azure IoT device SDK for C. A solution builder can use the Azure IoT explorer tool to understand the capabilities of an IoT Plug and Play device without the need to view any device code.

本教程介绍以下操作:In this tutorial, you:

  • 下载示例代码。Download the sample code.
  • 生成示例代码。Build the sample code.
  • 运行该示例设备应用程序,并验证它是否会连接到 IoT 中心。Run the sample device application and validate that it connects to your IoT hub.
  • 检查源代码。Review the source code.

先决条件Prerequisites

请确保设置环境(包括 IoT 中心)后再继续。Before you continue, make sure you've set up your environment, including your IoT hub.

可以在 Linux 或 Windows 上完成本教程。You can complete this tutorial on Linux or Windows. 本教程中的 shell 命令遵循适用于路径分隔符“/”的 Linux 约定,如果你是在 Windows 上操作,请务必将这些分隔符替换为“\”。The shell commands in this tutorial follow the Linux convention for path separators '/', if you're following along on Windows be sure to swap these separators for '\'.

先决条件根据操作系统而异:The prerequisites differ by operating system:

LinuxLinux

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

若要在 Linux 上完成本教程,需在本地 Linux 环境上安装以下软件:To complete this tutorial on Linux, install the following software on your local Linux environment:

使用 apt-get 命令安装“GCC”、“Git”、“cmake”和所有必要的依赖项: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

WindowsWindows

若要在 Windows 上完成本教程,需在本地 Windows 环境上安装以下软件:To complete this tutorial on Windows, install the following software on your local Windows environment:

下载代码Download the code

如果已完成快速入门:将 Linux 或 Windows 上运行的示例 IoT 即插即用设备应用程序连接到 IoT 中心 (C),则已下载了代码。If you completed the Quickstart: Connect a sample IoT Plug and Play device application running on Linux or Windows to IoT Hub (C) you've already downloaded the code.

在本教程中,你将准备一个用于克隆和生成 Azure IoT 中心设备 C SDK 的开发环境。In this tutorial, you prepare a development environment you can use to clone and build the Azure IoT Hub Device C SDK.

在所选文件夹中打开命令提示符。Open a command prompt in a folder of your choice. 执行以下命令将 Azure IoT C SDK 和库 GitHub 存储库克隆到此位置:Execute the following command to clone the Azure IoT C SDKs and Libraries GitHub repository into this location:

git clone https://github.com/Azure/azure-iot-sdk-c.git
cd azure-iot-sdk-c
git submodule update --init

应该预料到此操作需要几分钟才能完成。You should expect this operation to take several minutes to complete.

生成并运行代码Build and run the code

可以使用 Visual Studio 或在命令行使用 cmake 生成并运行代码。You can build and run the code using Visual Studio or cmake at the command line.

使用 Visual StudioUse Visual Studio

  1. 打开克隆存储库的根文件夹。Open the root folder of the cloned repository. 几秒钟后,Visual Studio 中的 CMake 支持会创建运行和调试项目所需的所有内容。After a couple of seconds, the CMake support in Visual Studio creates all you need to run and debug the project.

  2. Visual Studio 准备就绪后,在“解决方案资源管理器”中,导航到示例 iothub_client/samples/pnp/pnp_temperature_controller/。When Visual Studio is ready, in Solution Explorer, navigate to the sample iothub_client/samples/pnp/pnp_temperature_controller/.

  3. 右键单击“pnp_temperature_controller.c”文件并选择“添加调试配置”。Right-click on the pnp_temperature_controller.c file and select Add Debug Configuration. 选择“默认值”。Select Default.

  4. Visual Studio 将打开“launch.vs.json”文件。Visual Studio opens the launch.vs.json file. 按照以下代码片段编辑此文件,设置所需的环境变量。Edit this file as shown in the following snippet to set the required environment variables. 完成为 IoT 即插即用设置环境的快速入门和教程后,请记下范围 ID 和注册主密钥:You made a note of the scope ID and enrollment primary key when you completed Set up your environment for the IoT Plug and Play quickstarts and tutorials:

    {
      "version": "0.2.1",
      "defaults": {},
      "configurations": [
        {
          "type": "default",
          "project": "iothub_client\\samples\\pnp\\pnp_temperature_controller\\pnp_temperature_controller.c",
          "projectTarget": "",
          "name": "pnp_temperature_controller.c",
          "env": {
            "IOTHUB_DEVICE_SECURITY_TYPE": "DPS",
            "IOTHUB_DEVICE_DPS_ID_SCOPE": "<Your ID scope>",
            "IOTHUB_DEVICE_DPS_DEVICE_ID": "my-pnp-device",
            "IOTHUB_DEVICE_DPS_DEVICE_KEY": "<Your enrollment primary key>"
          }
        }
      ]
    }
    
  5. 右键单击“pnp_temperature_controller.c”文件并选择“设置为启动项”。Right-click on the pnp_temperature_controller.c file and select Set as Startup Item.

  6. 若要在 Visual Studio 中跟踪代码执行,请在 pnp_temperature_controller.c 文件中向 main 函数添加一个断点。To trace the code execution in Visual Studio, add a breakpoint to the main function in the pnp_temperature_controller.c file.

  7. 现在可以从“调试”菜单中运行并调试示例。You can now run and debug the sample from the Debug menu.

设备现在可以接收命令和属性更新,并已开始向中心发送遥测数据。The device is now ready to receive commands and property updates, and has started sending telemetry data to the hub. 在执行后续步骤时,保持示例处于运行状态。Keep the sample running as you complete the next steps.

在命令行上使用 cmakeUse cmake at the command line

生成示例:To build the sample:

  1. 在克隆设备 SDK 根文件夹中创建一个 cmake 子文件夹,并导航到该文件夹:Create a cmake subfolder in the root folder of the cloned device SDK, and navigate to that folder:

    cd azure-iot-sdk-c
    mkdir cmake
    cd cmake
    
  2. 运行以下命令,为 SDK 和示例生成项目文件:Run the following commands to generate and build the project files for SDK and samples:

    cmake ..
    cmake --build .
    

设置环境部分创建了四个环境变量来配置示例,以使用设备预配服务 (DPS) 连接到 IoT 中心:In Set up your environment, you created four environment variables to configure the sample to use the Device Provisioning Service (DPS) to connect to your IoT hub:

  • 具有值 DPS 的 IOTHUB_DEVICE_SECURITY_TYPEIOTHUB_DEVICE_SECURITY_TYPE with the value DPS
  • 包含 DPS ID 范围的 IOTHUB_DEVICE_DPS_ID_SCOPE。IOTHUB_DEVICE_DPS_ID_SCOPE with the DPS ID scope.
  • 包含值 my-pnp-device 的 IOTHUB_DEVICE_DPS_DEVICE_ID。IOTHUB_DEVICE_DPS_DEVICE_ID with the value my-pnp-device.
  • 包含注册主密钥的 IOTHUB_DEVICE_DPS_DEVICE_KEY。IOTHUB_DEVICE_DPS_DEVICE_KEY with the enrollment primary key.
  • 包含值 global.azure-devices-provisioning.net 的 IOTHUB_DEVICE_DPS_ENDPOINT。IOTHUB_DEVICE_DPS_ENDPOINT with the value global.azure-devices-provisioning.net.

若要详细了解示例配置,请参阅示例自述文件To learn more about the sample configuration, see the sample readme.

若要运行该示例:To run the sample:

  1. 在 cmake 文件夹中,导航到包含可执行文件的文件夹,并运行该文件:From the cmake folder, navigate to the folder that contains the executable file and run it:

    # Bash
    cd iothub_client/samples/pnp/pnp_temperature_controller/
    ./pnp_temperature_controller
    
    REM Windows
    cd iothub_client\samples\pnp\pnp_temperature_controller\Debug
    pnp_temperature_controller.exe
    

设备现在可以接收命令和属性更新,并已开始向中心发送遥测数据。The device is now ready to receive commands and property updates, and has started sending telemetry data to the hub. 在执行后续步骤时,保持示例处于运行状态。Keep the sample running as you complete the next steps.

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

设备客户端示例启动后,使用 Azure IoT 资源管理器工具验证它是否正常工作。After the device client sample starts, use the Azure IoT explorer tool to verify it's working.

  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.

查看代码Review the code

此示例实现 IoT 即插即用温度控制器设备。This sample implements an IoT Plug and Play temperature controller device. 此示例实现具有多个组件的模型。This sample implements a model with multiple components. 温度设备的数字孪生定义语言 (DTDL) 模型文件定义了设备实现的遥测、属性和命令。The Digital Twins definition language (DTDL) model file for the temperature device defines the telemetry, properties, and commands the device implements.

IoT 即插即用帮助程序函数IoT Plug and Play helper functions

对于本示例,代码使用 /common 文件夹中的一些帮助程序函数:For this sample, the code uses some helper functions from the /common folder:

pnp_device_client_ll 包含 IoT 即插即用连接方法,其中包含 model-id 作为参数 PnP_CreateDeviceClientLLHandlepnp_device_client_ll contains the connect method for IoT Plug and Play with the model-id included as a parameter: PnP_CreateDeviceClientLLHandle.

pnp_protocol 包含 IoT 即插即用帮助程序函数:pnp_protocol: contains the IoT Plug and Play helper functions:

  • PnP_CreateReportedProperty
  • PnP_CreateReportedPropertyWithStatus
  • PnP_ParseCommandName
  • PnP_CreateTelemetryMessageHandle
  • PnP_ProcessTwinData
  • PnP_CopyPayloadToString
  • PnP_CreateDeviceClientLLHandle_ViaDps

这些帮助程序函数是通用的,足以供你在自己的项目中使用。These helper functions are generic enough to use in your own project. 此示例在与模型中每个组件对应的三个文件中使用:This sample uses them in the three files that correspond to each component in the model:

  • pnp_deviceinfo_componentpnp_deviceinfo_component
  • pnp_temperature_controllerpnp_temperature_controller
  • pnp_thermostat_componentpnp_thermostat_component

例如,在 pnp_deviceinfo_component 文件中,SendReportedPropertyForDeviceInformation 函数使用两种帮助程序函数:For example, in the pnp_deviceinfo_component file, the SendReportedPropertyForDeviceInformation function uses two of the helper functions:

if ((jsonToSend = PnP_CreateReportedProperty(componentName, propertyName, propertyValue)) == NULL)
{
    LogError("Unable to build reported property response for propertyName=%s, propertyValue=%s", propertyName, propertyValue);
}
else
{
    const char* jsonToSendStr = STRING_c_str(jsonToSend);
    size_t jsonToSendStrLen = strlen(jsonToSendStr);

    if ((iothubClientResult = IoTHubDeviceClient_LL_SendReportedState(deviceClientLL, (const unsigned char*)jsonToSendStr, jsonToSendStrLen, NULL, NULL)) != IOTHUB_CLIENT_OK)
    {
        LogError("Unable to send reported state for property=%s, error=%d", propertyName, iothubClientResult);
    }
    else
    {
        LogInfo("Sending device information property to IoTHub.  propertyName=%s, propertyValue=%s", propertyName, propertyValue);
    }
}

示例中的每个组件都遵循此模式。Each component in the sample follows this pattern.

代码流Code flow

main 函数将初始化连接并发送模型 ID:The main function initializes the connection and sends the model ID:

deviceClient = CreateDeviceClientAndAllocateComponents();

此代码使用 PnP_CreateDeviceClientLLHandle 连接到 IoT 中心,将 modelId 设置为一个选项,并设置设备方法和设备孪生回叫处理程序,以提供直接方法和设备孪生更新:The code uses PnP_CreateDeviceClientLLHandle to connect to the IoT hub, set modelId as an option, and set up the device method and device twin callback handlers for direct methods and device twin updates:

g_pnpDeviceConfiguration.deviceMethodCallback = PnP_TempControlComponent_DeviceMethodCallback;
g_pnpDeviceConfiguration.deviceTwinCallback = PnP_TempControlComponent_DeviceTwinCallback;
g_pnpDeviceConfiguration.modelId = g_temperatureControllerModelId;
...

deviceClient = PnP_CreateDeviceClientLLHandle(&g_pnpDeviceConfiguration);

&g_pnpDeviceConfiguration 也包含连接信息。&g_pnpDeviceConfiguration also contains the connection information. 环境变量 IOTHUB_DEVICE_SECURITY_TYPE 确定示例是使用连接字符串还是使用设备预配服务来连接到 IoT 中心。The environment variable IOTHUB_DEVICE_SECURITY_TYPE determines whether the sample uses a connection string or the device provisioning service to connect to the IoT hub.

设备发送模型 ID 时,它会成为 IoT 即插即用设备。When the device sends a model ID, it becomes an IoT Plug and Play device.

回叫处理程序就绪后,设备会响应孪生更新和直接方法调用:With the callback handlers in place, the device reacts to twin updates and direct method calls:

  • 对于设备孪生回叫,PnP_TempControlComponent_DeviceTwinCallback 调用 PnP_ProcessTwinData 函数来处理数据。For the device twin callback, the PnP_TempControlComponent_DeviceTwinCallback calls the PnP_ProcessTwinData function to process the data. PnP_ProcessTwinData 使用访问者模式分析 JSON,然后访问每个属性,并对每个元素调用 PnP_TempControlComponent_ApplicationPropertyCallbackPnP_ProcessTwinData uses the visitor pattern to parse the JSON and then visit each property, calling PnP_TempControlComponent_ApplicationPropertyCallback on each element.

  • 对于命令回叫,PnP_TempControlComponent_DeviceMethodCallback 函数使用帮助程序函数来分析命令和组件名称:For the commands callback, the PnP_TempControlComponent_DeviceMethodCallback function uses the helper function to parse the command and component names:

    PnP_ParseCommandName(methodName, &componentName, &componentNameSize, &pnpCommandName);
    

    然后 PnP_TempControlComponent_DeviceMethodCallback 函数对该组件调用命令:The PnP_TempControlComponent_DeviceMethodCallback function then calls the command on the component:

    LogInfo("Received PnP command for component=%.*s, command=%s", (int)componentNameSize, componentName, pnpCommandName);
    if (strncmp((const char*)componentName, g_thermostatComponent1Name, g_thermostatComponent1Size) == 0)
    {
        result = PnP_ThermostatComponent_ProcessCommand(g_thermostatHandle1, pnpCommandName, rootValue, response, responseSize);
    }
    else if (strncmp((const char*)componentName, g_thermostatComponent2Name, g_thermostatComponent2Size) == 0)
    {
        result = PnP_ThermostatComponent_ProcessCommand(g_thermostatHandle2, pnpCommandName, rootValue, response, responseSize);
    }
    else
    {
        LogError("PnP component=%.*s is not supported by TemperatureController", (int)componentNameSize, componentName);
        result = PNP_STATUS_NOT_FOUND;
    }
    

main 函数将初始化发送到 IoT 中心的只读属性:The main function initializes the read-only properties sent to the IoT hub:

PnP_TempControlComponent_ReportSerialNumber_Property(deviceClient);
PnP_DeviceInfoComponent_Report_All_Properties(g_deviceInfoComponentName, deviceClient);
PnP_TempControlComponent_Report_MaxTempSinceLastReboot_Property(g_thermostatHandle1, deviceClient);
PnP_TempControlComponent_Report_MaxTempSinceLastReboot_Property(g_thermostatHandle2, deviceClient);

main 函数进入一个循环,以更新每个组件的事件和遥测数据:The main function enters a loop to update event and telemetry data for each component:

while (true)
{
    PnP_TempControlComponent_SendWorkingSet(deviceClient);
    PnP_ThermostatComponent_SendTelemetry(g_thermostatHandle1, deviceClient);
    PnP_ThermostatComponent_SendTelemetry(g_thermostatHandle2, deviceClient);
}

PnP_ThermostatComponent_SendTelemetry 函数演示如何使用 PNP_THERMOSTAT_COMPONENT 结构。The PnP_ThermostatComponent_SendTelemetry function shows you how to use the PNP_THERMOSTAT_COMPONENT struct. 该示例使用此结构来存储关于温度控制器中两个调温器的信息。The sample uses this struct to store information about the two thermostats in the temperature controller. 代码使用 PnP_CreateTelemetryMessageHandle 函数来准备并发送消息:The code uses the PnP_CreateTelemetryMessageHandle function to prepare the message and send it:

messageHandle = PnP_CreateTelemetryMessageHandle(pnpThermostatComponent->componentName, temperatureStringBuffer);
...
iothubResult = IoTHubDeviceClient_LL_SendEventAsync(deviceClientLL, messageHandle, NULL, NULL);

main 函数最终会销毁不同的组件,并关闭与中心的连接。The main function finally destroys the different components and closes the connection to the hub.

本教程介绍如何使用组件生成示例 IoT 即插即用设备应用程序,将其连接到 IoT 中心,并使用 Azure IoT 资源管理器工具来查看它发送到中心的信息。This tutorial shows you how to build a sample IoT Plug and Play device application with components, connect it to your IoT hub, and use the Azure IoT explorer tool to view the information it sends to the hub. 该示例应用程序以 C# 编写,包含在用于 C# 的 Azure IoT 设备 SDK 中。The sample application is written in C# and is included in the Azure IoT device SDK for C#. 解决方案构建者可以使用 Azure IoT 资源管理器工具来了解 IoT 即插即用设备的功能,而无需查看任何设备代码。A solution builder can use the Azure IoT explorer tool to understand the capabilities of an IoT Plug and Play device without the need to view any device code.

本教程介绍以下操作:In this tutorial, you:

  • 下载示例代码。Download the sample code.
  • 生成示例代码。Build the sample code.
  • 运行该示例设备应用程序,并验证它是否会连接到 IoT 中心。Run the sample device application and validate that it connects to your IoT hub.
  • 检查源代码。Review the source code.

先决条件Prerequisites

请确保设置环境(包括 IoT 中心)后再继续。Before you continue, make sure you've set up your environment, including your IoT hub.

若要在 Windows 上完成本教程,需在本地 Windows 环境上安装以下软件:To complete this tutorial on Windows, install the following software on your local Windows environment:

使用示例代码克隆 SDK 存储库Clone the SDK repository with the sample code

如果已完成快速入门:将 Windows 上运行的示例 IoT 即插即用设备应用程序连接到 IoT 中心 (C#),则已克隆了存储库。If you completed Quickstart: Connect a sample IoT Plug and Play device application running on Windows to IoT Hub (C#), you've already cloned the repository.

为 C# GitHub 存储库克隆 Azure IoT 示例中的示例。Clone the samples from the Azure IoT Samples for C# GitHub repository. 在所选文件夹中打开命令提示符。Open a command prompt in a folder of your choice. 运行以下命令,以克隆用于 .NET 的 Microsoft Azure IoT 示例 GitHub 存储库:Run the following command to clone the Microsoft Azure IoT samples for .NET GitHub repository:

git clone https://github.com/Azure-Samples/azure-iot-samples-csharp.git

运行示例设备Run the sample device

在本快速入门中,我们使用一个以 C# 编写的示例温度控制器设备作为 IoT 即插即用设备。In this quickstart, you use a sample temperature controller device that's written in C# as the IoT Plug and Play device. 运行示例设备:To run the sample device:

  1. 在 Visual Studio 2019 中打开“azure-iot-samples-csharp\iot-hub\Samples\device\PnpDeviceSamples\TemperatureController\TemperatureController.csproj”项目文件。Open the azure-iot-samples-csharp\iot-hub\Samples\device\PnpDeviceSamples\TemperatureController\TemperatureController.csproj project file in Visual Studio 2019.

  2. 在 Visual Studio 中,导航到“项目”>“温度控制器属性”>“调试”。In Visual Studio, navigate to Project > TemperatureController Properties > Debug. 然后,将以下环境变量添加到项目:Then add the following environment variables to the project:

    名称Name Value
    IOTHUB_DEVICE_SECURITY_TYPEIOTHUB_DEVICE_SECURITY_TYPE DPSDPS
    IOTHUB_DEVICE_DPS_ENDPOINTIOTHUB_DEVICE_DPS_ENDPOINT global.azure-devices-provisioning.netglobal.azure-devices-provisioning.net
    IOTHUB_DEVICE_DPS_ID_SCOPEIOTHUB_DEVICE_DPS_ID_SCOPE 在完成设置环境时记下的值The value you made a note of when you completed Set up your environment
    IOTHUB_DEVICE_DPS_DEVICE_IDIOTHUB_DEVICE_DPS_DEVICE_ID my-pnp-devicemy-pnp-device
    IOTHUB_DEVICE_DPS_DEVICE_KEYIOTHUB_DEVICE_DPS_DEVICE_KEY 在完成设置环境时记下的值The value you made a note of when you completed Set up your environment
  3. 现在可以在 Visual Studio 中生成示例,并在调试模式下运行它。You can now build the sample in Visual Studio and run it in debug mode.

  4. 你会看到一些消息,指出设备已发送部分信息并报告其自身处于联机状态。You see messages saying that the device has sent some information and reported itself online. 这些消息表明设备已开始向中心发送遥测数据,现在可以接收命令和属性更新。These messages indicate that the device has begun sending telemetry data to the hub, and is now ready to receive commands and property updates. 请勿关闭此 Visual Studio 实例,你需要使用它确认服务示例正常工作。Don't close this instance of Visual Studio, you need it to confirm the service sample is working.

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

设备客户端示例启动后,使用 Azure IoT 资源管理器工具验证它是否正常工作。After the device client sample starts, use the Azure IoT explorer tool to verify it's working.

  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.

查看代码Review the code

此示例实现 IoT 即插即用温度控制器设备。This sample implements an IoT Plug and Play temperature controller device. 此示例实现的模型使用多个组件The model this sample implements uses multiple components. 温度设备的数字孪生定义语言 (DTDL) 模型文件定义了设备实现的遥测、属性和命令。The Digital Twins definition language (DTDL) model file for the temperature device defines the telemetry, properties, and commands the device implements.

设备代码使用标准 CreateFromConnectionString 方法连接到 IoT 中心。The device code connects to your IoT hub using the standard CreateFromConnectionString method. 设备发送在连接请求中实现的 DTDL 模型的模型 ID。The device sends the model ID of the DTDL model it implements in the connection request. 发送模型 ID 的设备是 IoT 即插即用设备:A device that sends a model ID is an IoT Plug and Play device:

private static DeviceClient InitializeDeviceClient(string hostname, IAuthenticationMethod authenticationMethod)
{
    var options = new ClientOptions
    {
        ModelId = ModelId,
    };

    var deviceClient = DeviceClient.Create(hostname, authenticationMethod, TransportType.Mqtt, options);
    deviceClient.SetConnectionStatusChangesHandler((status, reason) =>
    {
        s_logger.LogDebug($"Connection status change registered - status={status}, reason={reason}.");
    });

    return deviceClient;
}

模型 ID 存储在代码中,如以下代码片段所示:The model ID is stored in the code as shown in the following snippet:

private const string ModelId = "dtmi:com:example:TemperatureController;1";

设备连接到 IoT 中心后,代码将注册命令处理程序。After the device connects to your IoT hub, the code registers the command handlers. reboot 命令是在默认组件中定义的。The reboot command is defined in the default component. getMaxMinReport 命令分别定义在两个恒温器组件中:The getMaxMinReport command is defined in each of the two thermostat components:

await _deviceClient.SetMethodHandlerAsync("reboot", HandleRebootCommandAsync, _deviceClient, cancellationToken);
await _deviceClient.SetMethodHandlerAsync("thermostat1*getMaxMinReport", HandleMaxMinReportCommandAsync, Thermostat1, cancellationToken);
await _deviceClient.SetMethodHandlerAsync("thermostat2*getMaxMinReport", HandleMaxMinReportCommandAsync, Thermostat2, cancellationToken);

对于两个恒温器组件上的所需属性更新,有单独的处理程序:There are separate handlers for the desired property updates on the two thermostat components:

_desiredPropertyUpdateCallbacks.Add(Thermostat1, TargetTemperatureUpdateCallbackAsync);
_desiredPropertyUpdateCallbacks.Add(Thermostat2, TargetTemperatureUpdateCallbackAsync);

示例代码从每个恒温器组件发送遥测数据:The sample code sends telemetry from each thermostat component:

await SendTemperatureAsync(Thermostat1, cancellationToken);
await SendTemperatureAsync(Thermostat2, cancellationToken);

SendTemperatureTelemetryAsync 方法使用 PnpHhelper 类为每个组件创建消息:The SendTemperatureTelemetryAsync method uses the PnpHhelper class to create messages for each component:

using Message msg = PnpHelper.CreateIothubMessageUtf8(telemetryName, JsonConvert.SerializeObject(currentTemperature), componentName);

PnpHelper 类包含可以在多组件模型中使用的其他示例方法。The PnpHelper class contains other sample methods that you can use with a multiple component model.

使用 Azure IoT 资源管理器工具查看两个恒温器组件中的遥测数据和属性:Use the Azure IoT explorer tool to view the telemetry and properties from the two thermostat components:

Azure IoT 资源管理器中的多组件设备

还可以使用 Azure IoT 资源管理器工具在两个恒温器组件或默认组件中调用命令。You can also use the Azure IoT explorer tool to call commands in either of the two thermostat components, or in the default component.

本教程介绍如何生成多组件示例 IoT 即插即用设备应用程序,将其连接到 IoT 中心,并使用 Azure CLI 来查看它发送的遥测数据。This tutorial shows you how to build a multiple component sample IoT Plug and Play device application, connect it to your IoT hub, and use the Azure CLI to view the telemetry it sends. 该示例应用程序以 Java 编写,包含在用于 Java 的 Azure IoT 设备 SDK 中。The sample application is written in Java and is included in the Azure IoT device SDK for Java. 解决方案构建者可以使用 Azure CLI 来了解 IoT 即插即用设备的功能,而无需查看任何设备代码。A solution builder can use the Azure CLI to understand the capabilities of an IoT Plug and Play device without the need to view any device code.

本教程介绍如何使用组件生成示例 IoT 即插即用设备应用程序,将其连接到 IoT 中心,并使用 Azure IoT 资源管理器工具来查看它发送到中心的信息。This tutorial shows you how to build a sample IoT Plug and Play device application with components, connect it to your IoT hub, and use the Azure IoT explorer tool to view the information it sends to the hub. 该示例应用程序以 Java 编写,包含在用于 Java 的 Azure IoT 设备 SDK 中。The sample application is written in Java and is included in the Azure IoT device SDK for Java. 解决方案构建者可以使用 Azure IoT 资源管理器工具来了解 IoT 即插即用设备的功能,而无需查看任何设备代码。A solution builder can use the Azure IoT explorer tool to understand the capabilities of an IoT Plug and Play device without the need to view any device code.

本教程介绍以下操作:In this tutorial, you:

  • 下载示例代码。Download the sample code.
  • 生成示例代码。Build the sample code.
  • 运行该示例设备应用程序,并验证它是否会连接到 IoT 中心。Run the sample device application and validate that it connects to your IoT hub.
  • 检查源代码。Review the source code.

先决条件Prerequisites

请确保设置环境(包括 IoT 中心)后再继续。Before you continue, make sure you've set up your environment, including your IoT hub.

若要在 Windows 上完成本教程,需在本地 Windows 环境上安装以下软件:To complete this tutorial on Windows, install the following software on your local Windows environment:

下载代码Download the code

如果已完成快速入门:将 Windows 上运行的示例 IoT 即插即用设备应用程序连接到 IoT 中心 (Java),则已克隆了存储库。If you completed Quickstart: Connect a sample IoT Plug and Play device application running on Windows to IoT Hub (Java), you've already cloned the repository.

在所选目录中打开命令提示符。Open a command prompt in the directory of your choice. 执行以下命令将 Azure IoT Java SDK 和库 GitHub 存储库克隆到此位置:Execute the following command to clone the Azure IoT Java SDKs and Libraries GitHub repository into this location:

git clone https://github.com/Azure/azure-iot-sdk-java.git

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

生成代码Build the code

在 Windows 上,导航到克隆的 Java SDK 存储库的根文件夹。On Windows, navigate to the root folder of the cloned Java SDK repository. 运行以下命令以生成依赖项:Run the following command to build the dependencies:

mvn install -T 2C -DskipTests

运行设备示例Run the device sample

设置环境部分创建了四个环境变量来配置示例,以使用设备预配服务 (DPS) 连接到 IoT 中心:In Set up your environment, you created four environment variables to configure the sample to use the Device Provisioning Service (DPS) to connect to your IoT hub:

  • 具有值 DPS 的 IOTHUB_DEVICE_SECURITY_TYPEIOTHUB_DEVICE_SECURITY_TYPE with the value DPS
  • 包含 DPS ID 范围的 IOTHUB_DEVICE_DPS_ID_SCOPE。IOTHUB_DEVICE_DPS_ID_SCOPE with the DPS ID scope.
  • 包含值 my-pnp-device 的 IOTHUB_DEVICE_DPS_DEVICE_ID。IOTHUB_DEVICE_DPS_DEVICE_ID with the value my-pnp-device.
  • 包含注册主密钥的 IOTHUB_DEVICE_DPS_DEVICE_KEY。IOTHUB_DEVICE_DPS_DEVICE_KEY with the enrollment primary key.
  • 包含值 global.azure-devices-provisioning.net 的 IOTHUB_DEVICE_DPS_ENDPOINT。IOTHUB_DEVICE_DPS_ENDPOINT with the value global.azure-devices-provisioning.net.

若要运行示例应用程序,请导航到“\device\iot-device-samples\pnp-device-sample\temperature-controller-device-sample”文件夹,并运行以下命令:To run the sample application, navigate to the \device\iot-device-samples\pnp-device-sample\temperature-controller-device-sample folder and run the following command:

mvn exec:java -Dexec.mainClass="samples.com.microsoft.azure.sdk.iot.device.TemperatureController"

设备现在可以接收命令和属性更新,并已开始向中心发送遥测数据。The device is now ready to receive commands and property updates, and has started sending telemetry data to the hub. 在执行后续步骤时,保持示例处于运行状态。Keep the sample running as you complete the next steps.

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

设备客户端示例启动后,使用 Azure IoT 资源管理器工具验证它是否正常工作。After the device client sample starts, use the Azure IoT explorer tool to verify it's working.

  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.

查看代码Review the code

此示例实现 IoT 即插即用温度控制器设备。This sample implements an IoT Plug and Play temperature controller device. 此示例实现的模型使用多个组件The model this sample implements uses multiple components. 温度设备的数字孪生定义语言 (DTDL) 模型文件定义了设备实现的遥测、属性和命令。The Digital Twins definition language (DTDL) model file for the temperature device defines the telemetry, properties, and commands the device implements.

设备代码使用标准 DeviceClient 类连接到 IoT 中心。The device code uses the standard DeviceClient class to connect to your IoT hub. 设备发送在连接请求中实现的 DTDL 模型的模型 ID。The device sends the model ID of the DTDL model it implements in the connection request. 发送模型 ID 的设备是 IoT 即插即用设备:A device that sends a model ID is an IoT Plug and Play device:

private static void initializeDeviceClient() throws URISyntaxException, IOException {
    ClientOptions options = new ClientOptions();
    options.setModelId(MODEL_ID);
    deviceClient = new DeviceClient(deviceConnectionString, protocol, options);

    deviceClient.registerConnectionStatusChangeCallback((status, statusChangeReason, throwable, callbackContext) -> {
        log.debug("Connection status change registered: status={}, reason={}", status, statusChangeReason);

        if (throwable != null) {
            log.debug("The connection status change was caused by the following Throwable: {}", throwable.getMessage());
            throwable.printStackTrace();
        }
    }, deviceClient);

    deviceClient.open();
}

模型 ID 存储在代码中,如以下代码片段所示:The model ID is stored in the code as shown in the following snippet:

private static final String MODEL_ID = "dtmi:com:example:Thermostat;1";

设备连接到 IoT 中心后,代码将注册命令处理程序。After the device connects to your IoT hub, the code registers the command handlers.

deviceClient.subscribeToDeviceMethod(new MethodCallback(), null, new MethodIotHubEventCallback(), null);

对于两个恒温器组件上的所需属性更新,有单独的处理程序:There are separate handlers for the desired property updates on the two thermostat components:

deviceClient.startDeviceTwin(new TwinIotHubEventCallback(), null, new GenericPropertyUpdateCallback(), null);
Map<Property, Pair<TwinPropertyCallBack, Object>> desiredPropertyUpdateCallback = Stream.of(
        new AbstractMap.SimpleEntry<Property, Pair<TwinPropertyCallBack, Object>>(
                new Property(THERMOSTAT_1, null),
                new Pair<>(new TargetTemperatureUpdateCallback(), THERMOSTAT_1)),
        new AbstractMap.SimpleEntry<Property, Pair<TwinPropertyCallBack, Object>>(
                new Property(THERMOSTAT_2, null),
                new Pair<>(new TargetTemperatureUpdateCallback(), THERMOSTAT_2))
).collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue));

deviceClient.subscribeToTwinDesiredProperties(desiredPropertyUpdateCallback);

示例代码从每个恒温器组件发送遥测数据:The sample code sends telemetry from each thermostat component:

sendTemperatureReading(THERMOSTAT_1);
sendTemperatureReading(THERMOSTAT_2);

sendTemperatureReading 方法使用 PnpHhelper 类为每个组件创建消息:The sendTemperatureReading method uses the PnpHhelper class to create messages for each component:

Message message = PnpHelper.createIotHubMessageUtf8(telemetryName, currentTemperature, componentName);

PnpHelper 类包含可以在多组件模型中使用的其他示例方法。The PnpHelper class contains other sample methods that you can use with a multiple component model.

使用 Azure IoT 资源管理器工具查看两个恒温器组件中的遥测数据和属性:Use the Azure IoT explorer tool to view the telemetry and properties from the two thermostat components:

Azure IoT 资源管理器中的多组件设备

还可以使用 Azure IoT 资源管理器工具在两个恒温器组件或默认组件中调用命令。You can also use the Azure IoT explorer tool to call commands in either of the two thermostat components, or in the default component.

本教程介绍如何使用组件生成示例 IoT 即插即用设备应用程序,将其连接到 IoT 中心,并使用 Azure IoT 资源管理器工具来查看它发送到中心的信息。This tutorial shows you how to build a sample IoT Plug and Play device application with components, connect it to your IoT hub, and use the Azure IoT explorer tool to view the information it sends to the hub. 该示例应用程序针对 Node.js 编写,包含在用于 Node.js 的 Azure IoT 中心设备 SDK 中。The sample application is written for Node.js and is included in the Azure IoT Hub Device SDK for Node.js. 解决方案构建者可以使用 Azure IoT 资源管理器工具来了解 IoT 即插即用设备的功能,而无需查看任何设备代码。A solution builder can use the Azure IoT explorer tool to understand the capabilities of an IoT Plug and Play device without the need to view any device code.

本教程介绍以下操作:In this tutorial, you:

  • 下载示例代码。Download the sample code.
  • 运行该示例设备应用程序,并验证它是否会连接到 IoT 中心。Run the sample device application and validate that it connects to your IoT hub.
  • 检查源代码。Review the source code.

先决条件Prerequisites

请确保设置环境(包括 IoT 中心)后再继续。Before you continue, make sure you've set up your environment, including your IoT hub.

若要完成本教程,需要在开发计算机上使用 Node.js。To complete this tutorial, you need Node.js on your development machine. 可以从 nodejs.org 下载适用于多个平台的最新推荐版本。You can download the latest recommended version 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

下载代码Download the code

如果已完成快速入门:将 Windows 上运行的示例 IoT 即插即用设备应用程序连接到 IoT 中心 (Node),则已克隆了存储库。If you completed Quickstart: Connect a sample IoT Plug and Play device application running on Windows to IoT Hub (Node), you've already cloned the repository.

在所选目录中打开命令提示符。Open a command prompt in the directory of your choice. 执行以下命令,将用于 Node.js 的 Microsoft Azure IoT SDK GitHub 存储库克隆到此位置:Execute the following command to clone the Microsoft Azure IoT SDK for Node.js GitHub repository into this location:

git clone https://github.com/Azure/azure-iot-sdk-node

安装所需的库Install required libraries

使用设备 SDK 生成包含的示例代码。You use the device SDK to build the included sample code. 你构建的应用程序会模拟一个即插即用设备,其中包含多个连接到 IoT 中心的组件。The application you build simulates a Plug and Play device with multiple components that connects to an IoT hub. 应用程序将发送遥测数据和属性,并接收命令。The application sends telemetry and properties and receives commands.

  1. 在本地终端窗口中,前往克隆存储库的文件夹,导航到 /azure-iot-sdk-node/device/samples/pnp 文件夹。In a local terminal window, go to the folder of your cloned repository and navigate to the /azure-iot-sdk-node/device/samples/pnp folder. 然后运行以下命令以安装所需的库:Then run the following command to install the required libraries:
npm install

这会在文件夹中安装运行示例所需的相关 npm 文件。This will install the relevant npm files required to run the samples in the folder.

查看代码Review the code

导航到 azure-iot-sdk-node\device\samples\pnp 文件夹。Navigate to the azure-iot-sdk-node\device\samples\pnp folder.

azure-iot-sdk-node\device\samples\pnp 文件夹包含 IoT 即插即用温度控制器设备的示例代码。The azure-iot-sdk-node\device\samples\pnp folder contains the sample code for the IoT Plug and Play temperature controller device.

pnpTemperatureController.js 文件中的代码实现 IoT 即插即用温度控制器设备。The code in the pnpTemperatureController.js file implements an IoT Plug and Play temperature controller device. 此示例实现的模型使用多个组件The model this sample implements uses multiple components. 温度设备的数字孪生定义语言 (DTDL) 模型文件定义了设备实现的遥测、属性和命令。The Digital Twins definition language (DTDL) model file for the temperature device defines the telemetry, properties, and commands the device implements.

在所选的代码编辑器中打开 pnpTemperatureController.js 文件。Open the pnpTemperatureController.js file in a code editor of your choice. 示例代码演示如何执行以下操作:The sample code shows how to:

  • 为要实现的设备定义 DTMI modelIdDefine the modelId which is the DTMI for the device that's being implemented. 此 DTMI 是用户定义的,必须与温度控制器 DTDL 模型的 DTMI 相匹配。This DTMI is user-defined and must match the DTMI of the temperature controller DTDL model.

  • 实现温度控制器 DTDL 模型中定义的组件。Implement the components defined in the temperature controller DTDL model. 实际温度控制器中的组件应实现这两个接口。The components in a real temperature controller should implement these two interfaces. 这两个接口已在中央存储库中发布。These two interfaces are already published in a central repository. 在此示例中,这两个接口为:In this sample, the two interfaces are:

    • 恒温调节器Thermostat
    • Azure 开发的设备信息Device information developed by Azure
  • 定义组件名称。Define component names. 此示例包含两个恒温器和一个设备信息组件。This sample has two thermostats and one device information component.

  • 定义命令名称。Define command name. 这些是设备响应的命令。These are the commands the device responds to.

  • 定义 serialNumber 常量。Define the serialNumber constant. serialNumber 是任何指定的固定设备。The serialNumber is fixed any given device.

  • 定义命令处理程序。Define the command handlers.

  • 定义用于发送命令响应的函数。Define the functions to send command responses.

  • 定义用于记录命令请求的 helper 函数。Define helper functions to log command requests.

  • 定义用于创建属性的 helper 函数。Define a helper function to create the properties.

  • 为属性更新定义侦听器。Define a listener for property updates.

  • 定义一个函数,用于从此设备发送遥测数据。Define a function to send telemetry from this device. 恒温器和默认组件都发送遥测数据。Both thermostats and the default component send telemetry. 此函数接收组件名称作为参数。This function receives the component name as parameter.

  • 定义 main 函数:Define a main function that:

    • 使用设备 SDK 创建设备客户端并连接到 IoT 中心。Uses the device SDK to create a device client and connect to your IoT hub. 设备提供 modelId 以便 IoT 中心可以将设备标识为 IoT 即插即用设备。The device supplies the modelId so that IoT Hub can identify the device as an IoT Plug and Play device.

    • 使用 onDeviceMethod 函数开始侦听命令请求。Starts listening for command requests using the onDeviceMethod function. 函数为来自服务的命令请求设置侦听器:The function sets up a listener for command requests from the service:

      • 设备 DTDL 定义 rebootgetMaxMinReport 命令。The device DTDL defines the reboot and getMaxMinReport commands.
      • commandHandler 函数定义设备对命令的响应方式。The commandHandler function defines how the device responds to a command.
    • 使用 setIntervalsendTelemetry 开始发送遥测数据。Starts sending telemetry by using setInterval and sendTelemetry.

    • 使用 helperCreateReportedPropertiesPatch 函数创建属性,并使用 updateComponentReportedProperties 来更新属性。Uses the helperCreateReportedPropertiesPatch function to create the properties and the updateComponentReportedProperties to update the properties.

    • 使用 desiredPropertyPatchListener 侦听属性更新。Uses desiredPropertyPatchListener to listen for property updates.

    • 禁用所有侦听器和任务,并在按 Q 或 q 时退出循环。Disables all the listeners and tasks, and exits the loop when you press Q or q.

设置环境部分创建了四个环境变量来配置示例,以使用设备预配服务 (DPS) 连接到 IoT 中心:In Set up your environment, you created four environment variables to configure the sample to use the Device Provisioning Service (DPS) to connect to your IoT hub:

  • 具有值 DPS 的 IOTHUB_DEVICE_SECURITY_TYPEIOTHUB_DEVICE_SECURITY_TYPE with the value DPS
  • 包含 DPS ID 范围的 IOTHUB_DEVICE_DPS_ID_SCOPE。IOTHUB_DEVICE_DPS_ID_SCOPE with the DPS ID scope.
  • 包含值 my-pnp-device 的 IOTHUB_DEVICE_DPS_DEVICE_ID。IOTHUB_DEVICE_DPS_DEVICE_ID with the value my-pnp-device.
  • 包含注册主密钥的 IOTHUB_DEVICE_DPS_DEVICE_KEY。IOTHUB_DEVICE_DPS_DEVICE_KEY with the enrollment primary key.
  • 包含值 global.azure-devices-provisioning.net 的 IOTHUB_DEVICE_DPS_ENDPOINT。IOTHUB_DEVICE_DPS_ENDPOINT with the value global.azure-devices-provisioning.net.

若要详细了解示例配置,请参阅示例自述文件To learn more about the sample configuration, see the sample readme.

看到代码后,请使用以下命令运行该示例:Now that you've seen the code, use the following command to run the sample:

node pnpTemperatureController.js

将显示以下输出,这表明设备已开始向中心发送遥测数据,现在可以接收命令和属性更新。You see the following output, indicating the device has begun sending telemetry data to the hub, and is now ready to receive commands and property updates.

设备确认消息

在执行后续步骤时,保持示例处于运行状态。Keep the sample running as you complete the next steps.

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

设备客户端示例启动后,使用 Azure IoT 资源管理器工具验证它是否正常工作。After the device client sample starts, use the Azure IoT explorer tool to verify it's working.

  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.

本教程介绍如何使用组件生成示例 IoT 即插即用设备应用程序,将其连接到 IoT 中心,并使用 Azure IoT 资源管理器工具来查看它发送到中心的信息。This tutorial shows you how to build a sample IoT Plug and Play device application with components, connect it to your IoT hub, and use the Azure IoT explorer tool to view the information it sends to the hub. 该示例应用程序以 Python 编写,包含在用于 Python 的 Azure IoT 设备 SDK 中。The sample application is written in Python and is included in the Azure IoT device SDK for Python. 解决方案构建者可以使用 Azure IoT 资源管理器工具来了解 IoT 即插即用设备的功能,而无需查看任何设备代码。A solution builder can use the Azure IoT explorer tool to understand the capabilities of an IoT Plug and Play device without the need to view any device code.

本教程介绍以下操作:In this tutorial, you:

  • 下载示例代码。Download the sample code.
  • 运行该示例设备应用程序,并验证它是否会连接到 IoT 中心。Run the sample device application and validate that it connects to your IoT hub.
  • 检查源代码。Review the source code.

先决条件Prerequisites

请确保设置环境(包括 IoT 中心)后再继续。Before you continue, make sure you've set up your environment, including your IoT hub.

若要完成本教程,需要在开发计算机上使用 Python 3.7。To complete this tutorial, you need Python 3.7 on your development machine. 可以从 python.org 下载适用于多个平台的最新推荐版本。可以使用以下命令检查 Python 版本:You can download the latest recommended version for multiple platforms from python.org. You can check your Python version with the following command:

python --version

可以从 python.org 下载适用于多个平台的最新推荐版本。You can download the latest recommended version for multiple platforms from python.org.

下载代码Download the code

azure-iot-device 包以 PIP 的形式发布。The azure-iot-device package is published as a PIP.

在本地 Python 环境中安装该包,如下所示:In your local python environment install the package as follows:

pip install azure-iot-device

如果已完成快速入门:将 Windows 上运行的示例 IoT 即插即用设备应用程序连接到 IoT 中心 (Python),则已克隆了存储库。If you completed Quickstart: Connect a sample IoT Plug and Play device application running on Windows to IoT Hub (Python), you've already cloned the repository.

克隆 Python SDK IoT 存储库:Clone the Python SDK IoT repository:

git clone https://github.com/Azure/azure-iot-sdk-python

查看代码Review the code

此示例实现 IoT 即插即用温度控制器设备。This sample implements an IoT Plug and Play temperature controller device. 此示例实现的模型使用多个组件The model this sample implements uses multiple components. 温度设备的数字孪生定义语言 (DTDL) 模型文件定义了设备实现的遥测、属性和命令。The Digital Twins definition language (DTDL) model file for the temperature device defines the telemetry, properties, and commands the device implements.

azure-iot-sdk-python\azure-iot-device\samples\pnp 文件夹包含 IoT 即插即用设备的示例代码。The azure-iot-sdk-python\azure-iot-device\samples\pnp folder contains the sample code for the IoT Plug and Play device. 温度控制器示例的文件包括:The files for the temperature controller sample are:

  • temp_controller_with_thermostats.pytemp_controller_with_thermostats.py
  • pnp_helper.pypnp_helper.py

温度控制器基于温度控制器 DTDL 模型,具有多个组件和一个默认组件。Temperature controller has multiple components and a default component, based on the temperature controller DTDL model.

在所选的编辑器中打开 temp_controller_with_thermostats.py 文件。Open the temp_controller_with_thermostats.py file in an editor of your choice. 此文件中的代码:The code in this file:

  1. 导入 pnp_helper.py 以获取对帮助器方法的访问权限。Imports pnp_helper.py to get access to helper methods.

  2. 定义两个数字孪生模型标识符 (DTMI),它们唯一表示 DTDL 模型中定义的两个不同接口。Defines two digital twin model identifiers (DTMIs) that uniquely represent two different interfaces, defined in the DTDL model. 实际温度控制器中的组件应实现这两个接口。The components in a real temperature controller should implement these two interfaces. 这两个接口已在中央存储库中发布。These two interfaces are already published in a central repository. 这些 DTMI 必须为用户所知,并且根据设备实现方案而有所不同。These DTMIs must be known to the user and vary dependent on the scenario of device implementation. 对于当前示例,这两个接口表示:For the current sample, these two interfaces represent:

    • 调温器A thermostat
    • Azure 开发的设备信息。Device information developed by Azure.
  3. 为要实现的设备定义 DTMI model_idDefines the DTMI model_id for the device that's being implemented. DTMI 是用户定义的,必须与 DTDL 模型文件中的 DTMI 匹配。The DTMI is user-defined and must match the DTMI in the DTDL model file.

  4. 定义为 DTDL 文件中的组件提供的名称。Defines the names given to the components in the DTDL file. DTDL 中有两个调温器和一个设备信息组件。There are two thermostats in the DTDL and one device information component. 名为 serial_number 的常量也是在默认组件中定义。A constant called serial_number is also defined in the default component. 设备的 serial_number 无法更改。A serial_number can't change for a device.

  5. 定义命令处理程序实现。Defines command handler implementations. 它们定义设备接收命令请求时执行哪些操作。These define what the device does when it receives command requests.

  6. 定义创建命令响应的函数。Defines functions to create a command response. 它们定义设备如何响应命令请求。These define how the device responds with to command requests. 如果命令需要将自定义响应发送回 IoT 中心,你可以创建命令响应函数。You create command response functions if a command needs to send a custom response back to the IoT hub. 如果未提供命令的响应函数,则发送通用响应。If a response function for a command isn't provided, a generic response is sent. 在此示例中,只有 getMaxMinReport 命令具有自定义响应。In this sample, only the getMaxMinReport command has a custom response.

  7. 定义一个函数,用于从此设备发送遥测数据。Defines a function to send telemetry from this device. 恒温器和默认组件都发送遥测数据。Both the thermostats and the default component send telemetry. 此函数采用可选的组件名称参数,这让它能够识别哪个组件发送了遥测数据。This function takes in a optional component name parameter to enable it to identify which component sent the telemetry.

  8. 定义命令请求的侦听器。Defines a listener for command requests.

  9. 定义所需属性更新的侦听器。Defines a listener for desired property updates.

  10. 有一个 main 函数:Has a main function that:

    • 使用设备 SDK 创建设备客户端并连接到 IoT 中心。Uses the device SDK to create a device client and connect to your IoT hub. 设备发送 model_id,以便 IoT 中心可以将设备标识为 IoT 即插即用设备。The device sends the model_id so that the IoT hub can identify the device as an IoT Plug and Play device.

    • 使用帮助器文件中的 create_reported_properties 函数创建属性。Uses the create_reported_properties function in the helper file to create the properties. 将组件名称和属性作为键值对传递给此函数。Pass the component name, and the properties as key value pairs to this function.

    • 通过调用 patch_twin_reported_properties 为其组件更新可读属性。Updates the readable properties for its components by calling patch_twin_reported_properties.

    • 使用 execute_command_listener 函数开始侦听命令请求。Starts listening for command requests using the execute_command_listener function. 函数为来自服务的命令请求设置侦听器。The function sets up a listener for command requests from the service. 设置侦听器时,提供 method_nameuser_command_handler 和可选的 create_user_response_handler 作为参数。When you set up the listener you provide a method_name, user_command_handler, and an optional create_user_response_handler as parameters.

      • method_name 定义命令请求。The method_name defines the command request. 在此示例中,模型定义命令“reboot”和“getMaxMinReport” 。In this sample the model defines the commands reboot, and getMaxMinReport.
      • user_command_handler 函数定义设备在收到命令时应执行的操作。The user_command_handler function defines what the device should do when it receives a command.
      • 命令成功执行时,create_user_response_handler 函数将创建要发送到 IoT 中心的响应。The create_user_response_handler function creates a response to be sent to your IoT hub when a command executes successfully. 可以在门户中查看此响应。You can view this response in the portal. 如果未提供此函数,则向服务发送通用响应。If this function isn't provided, a generic response is sent to the service.
    • 使用 execute_property_listener 侦听属性更新。Uses execute_property_listener to listen for property updates.

    • 使用 send_telemetry 开始发送遥测数据。Starts sending telemetry using send_telemetry. 示例代码使用循环来调用三个发送遥测数据的函数。The sample code uses a loop to call three telemetry sending functions. 每八秒调用一次每个函数Each one is called every eight seconds

    • 禁用所有侦听器和任务,并在按 Q 或 q 时退出循环 。Disables all the listeners and tasks, and exits the loop when you press Q or q.

设置环境部分创建了四个环境变量来配置示例,以使用设备预配服务 (DPS) 连接到 IoT 中心:In Set up your environment, you created four environment variables to configure the sample to use the Device Provisioning Service (DPS) to connect to your IoT hub:

  • 具有值 DPS 的 IOTHUB_DEVICE_SECURITY_TYPEIOTHUB_DEVICE_SECURITY_TYPE with the value DPS
  • 包含 DPS ID 范围的 IOTHUB_DEVICE_DPS_ID_SCOPE。IOTHUB_DEVICE_DPS_ID_SCOPE with the DPS ID scope.
  • 包含值 my-pnp-device 的 IOTHUB_DEVICE_DPS_DEVICE_ID。IOTHUB_DEVICE_DPS_DEVICE_ID with the value my-pnp-device.
  • 包含注册主密钥的 IOTHUB_DEVICE_DPS_DEVICE_KEY。IOTHUB_DEVICE_DPS_DEVICE_KEY with the enrollment primary key.
  • 包含值 global.azure-devices-provisioning.net 的 IOTHUB_DEVICE_DPS_ENDPOINT。IOTHUB_DEVICE_DPS_ENDPOINT with the value global.azure-devices-provisioning.net.

若要详细了解示例配置,请参阅示例自述文件To learn more about the sample configuration, see the sample readme.

使用以下命令运行示例:Use the following command to run the sample:

python temp_controller_with_thermostats.py

示例设备每隔几秒钟向 IoT 中心发送遥测消息。The sample device sends telemetry messages every few seconds to your IoT hub.

你会看到以下输出,这表明设备正在向中心发送遥测数据,现在可以接收命令和属性更新。You see the following output, which indicates the device is sending telemetry data to the hub, and is now ready to receive commands and property updates.

设备确认消息

在执行后续步骤时,保持示例处于运行状态。Keep the sample running as you complete the next steps.

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

设备客户端示例启动后,使用 Azure IoT 资源管理器工具验证它是否正常工作。After the device client sample starts, use the Azure IoT explorer tool to verify it's working.

  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 tutorial, you've learned how to connect an IoT Plug and Play device with components to an IoT hub. 若要详细了解 IoT 即插即用设备模型,请参阅:To learn more about IoT Plug and Play device models, see: