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

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

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

服务和设备应用程序可以使用 IoT 中心设备流以安全且防火墙友好的方式进行通信。IoT Hub device streams allow service and device applications to communicate in a secure and firewall-friendly manner. 在公共预览期,C SDK 仅支持设备端的设备流。During public preview, the C SDK supports device streams on the device side only. 因此,本快速入门只介绍如何运行设备端应用程序。As a result, this quickstart covers instructions to run only the device-side application. 若要运行相应的服务端应用程序,请参阅以下文章:To run a corresponding service-side application, see these articles:

本快速入门中的设备端 C 应用程序具有以下功能:The device-side C application in this quickstart has the following functionality:

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

  • 接收从服务端应用程序发送的数据并将其回显。Receive data that's sent from the service-side application and echo it back.

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

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

先决条件Prerequisites

需要具备以下先决条件:You need the following prerequisites:

  • Azure Cloud Shell 中使用 Bash 环境。Use the Bash environment in Azure Cloud Shell.

    在新窗口中启动 Cloud ShellLaunch Cloud Shell in a new window

  • 如果需要,请安装 Azure CLI 来运行 CLI 参考命令。If you prefer, install the Azure CLI to run CLI reference commands.

    • 如果使用的是本地安装,请使用 az login 命令登录到 Azure CLI。If you're using a local installation, sign in to the Azure CLI by using the az login command. 若要完成身份验证过程,请遵循终端中显示的步骤。To finish the authentication process, follow the steps displayed in your terminal. 有关其他登录选项,请参阅登录 Azure CLIFor additional sign-in options, see Sign in with the Azure CLI.

    • 出现提示时,请在首次使用时安装 Azure CLI 扩展。When you're prompted, install Azure CLI extensions on first use. 有关扩展详细信息,请参阅使用 Azure CLI 的扩展For more information about extensions, see Use extensions with the Azure CLI.

    • 运行 az version 以查找安装的版本和依赖库。Run az version to find the version and dependent libraries that are installed. 若要升级到最新版本,请运行 az upgradeTo upgrade to the latest version, run az upgrade.

备注

本文使用最新版本的 Azure IoT 扩展(称为 azure-iot)。This article uses the newest version of the Azure IoT extension, called azure-iot. 旧版本称为 azure-cli-iot-ext。只应同时安装有一个版本。The legacy version is called azure-cli-iot-ext.You should only have one version installed at a time. 可以使用命令 az extension list 来验证当前安装的扩展。You can use the command az extension list to validate the currently installed extensions.

使用 az extension remove --name azure-cli-iot-ext 可删除扩展的旧版本。Use az extension remove --name azure-cli-iot-ext to remove the legacy version of the extension.

使用 az extension add --name azure-iot 可添加扩展的新版本。Use az extension add --name azure-iot to add the new version of the extension.

若要查看已安装了哪些扩展,请使用 az extension listTo see what extensions you have installed, use az extension list.

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

  • 美国中部Central US
  • 美国中部 EUAPCentral US EUAP
  • 北欧North Europe
  • 东南亚Southeast Asia

准备开发环境Prepare the development environment

在本快速入门中,我们将使用适用于 C 的 Azure IoT 设备 SDK。准备一个用于从 GitHub 克隆和生成 Azure IoT C SDK 的开发环境。For this quickstart, you use the Azure IoT device SDK for C. You prepare a development environment used to clone and build the Azure IoT C SDK from GitHub. GitHub 上的 SDK 包括在本快速入门中使用的示例代码。The SDK on GitHub includes the sample code that's used in this quickstart.

备注

在开始此过程之前,请确保已安装了带有“使用 C++ 进行桌面开发”工作负荷的 Visual Studio。Before you begin this procedure, be sure that Visual Studio is installed with the Desktop development with C++ workload.

  1. 按照下载页上的说明安装 CMake 生成系统Install the CMake build system as described on the download page.

  2. 打开命令提示符或 Git Bash shell。Open a command prompt or Git Bash shell. 运行以下命令克隆 Azure IoT C SDK GitHub 存储库:Run the following commands to clone the Azure IoT C SDK GitHub repository:

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

    此操作需要花费几分钟时间。This operation should take a few minutes.

  3. 在 git 存储库的根目录中创建 cmake 子目录,并导航到该文件夹。Create a cmake subdirectory in the root directory of the git repository, and navigate to that folder. 从 azure-iot-sdk-c 目录运行以下命令:Run the following commands from the azure-iot-sdk-c directory:

    mkdir cmake
    cd cmake
    
  4. cmake 目录运行以下命令,以生成特定于开发客户端平台的 SDK 版本。Run the following commands from the cmake directory to build a version of the SDK that's specific to your development client platform.

    • 在 Linux 中:In Linux:

      cmake ..
      make -j
      
    • 在 Windows 中,打开 Visual Studio 的开发人员命令提示In Windows, open a Developer Command Prompt for Visual Studio. 运行 Visual Studio 版本的命令。Run the command for your version of Visual Studio. 本快速入门使用 Visual Studio 2019。This quickstart uses Visual Studio 2019. 这些命令在 cmake 目录中为模拟设备创建 Visual Studio 解决方案。These commands create a Visual Studio solution for the simulated device in the cmake directory.

      rem For VS2015
      cmake .. -G "Visual Studio 14 2015"
      
      rem Or for VS2017
      cmake .. -G "Visual Studio 15 2017"
      
      rem Or for VS2019
      cmake .. -G "Visual Studio 16 2019"
      
      rem Then build the project
      cmake --build . -- /m /p:Configuration=Release
      

创建 IoT 中心Create an IoT hub

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

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

  2. 从 Azure 主页中选择“+ 创建资源”按钮,然后在“搜索市场”字段中输入“IoT 中心”。From the Azure homepage, select the + Create a resource button, and then enter IoT Hub in the Search the Marketplace field.

  3. 在搜索结果中选择“IoT 中心”,然后选择“创建” 。Select IoT Hub from the search results, and then select Create.

  4. 在“基本信息”选项卡上,按如下所示填写字段:On the Basics tab, complete the fields as follows:

    • 订阅:选择要用于中心的订阅。Subscription: Select the subscription to use for your hub.

    • 资源组:选择一个资源组或新建一个资源组。Resource Group: Select a resource group or create a new one. 若要新建资源组,请选择“新建”并填写要使用的名称。To create a new one, select Create new and fill in the name you want to use. 若要使用现有的资源组,请选择它。To use an existing resource group, select that resource group. 有关详细信息,请参阅管理 Azure 资源管理器资源组For more information, see Manage Azure Resource Manager resource groups.

    • 区域:选择中心所在的区域。Region: Select the region in which you want your hub to be located. 选择最靠近你的位置。Select the location closest to you. 某些功能(如 IoT 中心设备流)仅适用于特定区域。Some features, such as IoT Hub device streams, are only available in specific regions. 对于这些受限功能,你必须选择受支持的区域之一。For these limited features, you must select one of the supported regions.

    • IoT 中心名称:输入中心的名称。IoT Hub Name: Enter a name for your hub. 该名称必须全局唯一。This name must be globally unique.

    重要

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

    在 Azure 门户中创建中心。

  5. 在完成时选择“下一步:网络”,继续创建中心。Select Next: Networking to continue creating your hub.

    选择可以连接到 IoT 中心的终结点。Choose the endpoints that can connect to your IoT Hub. 你可以选择默认设置“公共终结点(所有网络)”,也可选择“公共终结点(选定的 IP 范围)”或“专用终结点” 。You can select the default setting Public endpoint (all networks), or choose Public endpoint (selected IP ranges), or Private endpoint. 接受此示例的默认设置。Accept the default setting for this example.

    选择可以连接的终结点。

  6. 在完成时选择“下一步:管理”,继续创建中心。Select Next: Management to continue creating your hub.

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

    可在此处接受默认设置。You can accept the default settings here. 如果需要,可以修改以下任何字段:If desired, you can modify any of the following fields:

    • 定价和缩放层:选择的层。Pricing and scale tier: Your selected tier. 可以根据你需要的功能数以及每天通过解决方案发送的消息数从多个层级中进行选择。You can choose from several tiers, depending on how many features you want and how many messages you send through your solution per day. 免费层适用于测试和评估。The free tier is intended for testing and evaluation. 允许 500 台设备连接到中心,每天最多可传输 8,000 条消息。It allows 500 devices to be connected to the hub and up to 8,000 messages per day. 每个 Azure 订阅可以在免费层中创建一个 IoT 中心。Each Azure subscription can create one IoT hub in the free tier.

      如果正在完成 IoT 中心设备流的快速入门,请选择免费层。If you are working through a Quickstart for IoT Hub device streams, select the free tier.

    • IoT 中心单元:每日每单位允许的消息数取决于中心的定价层。IoT Hub units: The number of messages allowed per unit per day depends on your hub's pricing tier. 例如,如果希望中心支持 700,000 条消息引入,请选择两个 S1 层单位。For example, if you want the hub to support ingress of 700,000 messages, you choose two S1 tier units. 有关其他层选项的详细信息,请参阅选择合适的 IoT 中心层For details about the other tier options, see Choosing the right IoT Hub tier.

    • Defender for IoT:启用此功能可为 IoT 和设备添加额外的一层威胁防护。Defender for IoT: Turn this on to add an extra layer of threat protection to IoT and your devices. 此选项不可用于免费层的中心。This option is not available for hubs in the free tier. 有关此功能的详细信息,请参阅适用于 IoT 的 Azure 安全中心For more information about this feature, see Azure Security Center for IoT.

    • 高级设置 > 设备到云的分区:此属性将设备到云消息与这些消息的同步读取器数目相关联。Advanced Settings > Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. 大多数中心只需要 4 个分区。Most hubs need only four partitions.

  7. 在完成时选择“下一步:标记”继续到下一屏幕。Select Next: Tags to continue to the next screen.

    标记是名称/值对。Tags are name/value pairs. 可以为多个资源和资源组分配相同的标记,以便对资源进行分类并合并计费。You can assign the same tag to multiple resources and resource groups to categorize resources and consolidate billing. 有关详细信息,请参阅使用标记来组织 Azure 资源For more information, see Use tags to organize your Azure resources.

    使用 Azure 门户为中心分配标记。

  8. 在完成时选择“下一步:查看+创建”可查看选择。Select Next: Review + create to review your choices. 你会看到类似于此屏幕的内容,但其中包含创建中心时选择的值。You see something similar to this screen, but with the values you selected when creating the hub.

    查看用于创建新中心的信息。

  9. 选择“创建”以创建新的中心。Select Create to create your new hub. 创建中心需要几分钟时间。Creating the hub takes a few minutes.

注册设备Register a device

必须先将设备注册到 IoT 中心,然后该设备才能进行连接。You must register a device with your IoT hub before it can connect. 在本部分中,我们将使用具有 IoT 扩展的 Azure Cloud Shell 注册模拟设备。In this section, you use Azure Cloud Shell with the IoT Extension to register a simulated device.

  1. 若要创建设备标识,请在 Cloud Shell 中运行以下命令:To create the device identity, run the following command in Cloud Shell:

    备注

    • 请将 YourIoTHubName 占位符替换为你为 IoT 中心选择的名称。Replace the YourIoTHubName placeholder with the name you chose for your IoT hub.
    • 对于正在注册的设备的名称,建议使用 MyDevice,如下所示。For the name of the device you're registering, it's recommended to use MyDevice as shown. 如果为设备选择其他名称,请在本文中从头至尾使用该名称,并在运行示例应用程序之前在其中更新设备名称。If you choose a different name for your device, use that name throughout this article, and update the device name in the sample applications before you run them.
    az iot hub device-identity create --hub-name {YourIoTHubName} --device-id MyDevice
    
  2. 若要获取刚刚注册的设备的 设备连接字符串,请在 Cloud Shell 中运行以下命令:To get the device connection string for the device that you just registered, run the following command in Cloud Shell:

    备注

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

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

    请记下返回的设备连接字符串,以便稍后在此快速入门中使用。Note the returned device connection string for later use in this quickstart. 如以下示例所示:It looks like the following example:

    HostName={YourIoTHubName}.azure-devices.net;DeviceId=MyDevice;SharedAccessKey={YourSharedAccessKey}

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

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

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

若要运行设备端应用程序,请执行以下步骤:To run the device-side application, follow these steps:

  1. 通过编辑 iothub_client/samples/iothub_client_c2d_streaming_sample 文件夹中的 iothub_client_c2d_streaming_sample.c 源文件并添加设备连接字符串来提供设备凭据。Provide your device credentials by editing the iothub_client_c2d_streaming_sample.c source file in the iothub_client/samples/iothub_client_c2d_streaming_sample folder and adding your device connection string.

    /* Paste in your iothub connection string  */
    static const char* connectionString = "{DeviceConnectionString}";
    
  2. 使用以下命令编译代码:Compile the code with the following commands:

    # In Linux
    # Go to the sample's folder cmake/iothub_client/samples/iothub_client_c2d_streaming_sample
    make -j
    
    rem In Windows
    rem Go to the cmake folder at the root of repo
    cmake --build . -- /m /p:Configuration=Release
    
  3. 运行编译的程序:Run the compiled program:

    # In Linux
    # Go to the sample's folder cmake/iothub_client/samples/iothub_client_c2d_streaming_sample
    ./iothub_client_c2d_streaming_sample
    
    rem In Windows
    rem Go to the sample's release folder cmake\iothub_client\samples\iothub_client_c2d_streaming_sample\Release
    iothub_client_c2d_streaming_sample.exe
    

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

如前所述,IoT 中心 C SDK 仅支持设备端的设备流。As mentioned previously, the IoT Hub C SDK supports device streams on the device side only. 若要生成和运行随附的服务端应用程序,请按照以下快速入门之一中的说明进行操作:To build and run the accompanying service-side application, follow the instructions in one of the following quickstarts:

清理资源Clean up resources

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

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

重要

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

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

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

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

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

    “删除资源组”按钮

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

后续步骤Next steps

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

若要详细了解设备流,请参阅:To learn more about device streams, see: