您现在访问的是微软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# 应用程序,它们利用设备流来回发送数据(回显)。This quickstart involves two C# applications that take advantage of device streams to send data back and forth (echo).

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

先决条件Prerequisites

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

    • 美国中部Central US
    • 美国中部 EUAPCentral US EUAP
    • 北欧North Europe
    • 东南亚Southeast Asia
  • 本快速入门中运行的两个示例应用程序是使用 C# 编写的。The two sample applications that you run in this quickstart are written in C#. 开发计算机上需要有 .NET Core SDK 2.1.0 或更高版本。You need the .NET Core SDK 2.1.0 or later on your development machine.

    从 .NET 下载适用于多个平台的 .NET Core SDKDownload the .NET Core SDK for multiple platforms from .NET.

    使用以下命令验证开发计算机上 C# 的当前版本:Verify the current version of C# on your development machine by using the following command:

    dotnet --version
    
  • 下载 Azure IoT C# 示例,并提取 ZIP 存档。Download the Azure IoT C# samples and extract the ZIP archive. 需要在设备端和服务端执行此操作。You need it on both the device side and the service side.

  • 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 中心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 中心,然后该设备才能进行连接。A device must be registered with your IoT hub before it can connect. 在本部分,我们将使用 Azure Cloud Shell 来注册模拟设备。In this section, you use Azure Cloud Shell 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}

  3. 此外,需要使用 IoT 中心的服务连接字符串才能让服务端应用程序连接到 IoT 中心并建立设备流。You also need the service connection string from your IoT hub to enable the service-side application to connect to your IoT hub and establish a device stream. 以下命令检索 IoT 中心的此值:The following command retrieves this value for your IoT hub:

    备注

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

    az iot hub show-connection-string --policy-name service --name {YourIoTHubName} --output table
    

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

    "HostName={YourIoTHubName}.azure-devices.net;SharedAccessKeyName=service;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 service-side application

在本地终端窗口中,导航到解压缩项目文件夹中的 iot-hub/Quickstarts/device-streams-echo/service 目录。In a local terminal window, navigate to the iot-hub/Quickstarts/device-streams-echo/service directory in your unzipped project folder. 请保留以下信息:Keep the following information handy:

参数名称Parameter name 参数值Parameter value
ServiceConnectionString IoT 中心的服务连接字符串。The service connection string of your IoT hub.
MyDevice 前面创建的设备标识符。The identifier of the device you created earlier.

使用以下命令编译并运行代码:Compile and run the code with the following commands:

cd ./iot-hub/Quickstarts/device-streams-echo/service/

# Build the application
dotnet build

# Run the application
# In Linux or macOS
dotnet run "{ServiceConnectionString}" "MyDevice"

# In Windows
dotnet run {ServiceConnectionString} MyDevice

应用程序将等待设备应用程序变为可用。The application will wait for the device application to become available.

备注

如果设备端应用程序未及时响应,则会发生超时。A timeout occurs if the device-side application doesn't respond in time.

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

在另一个本地终端窗口中,导航到解压缩项目文件夹中的 iot-hub/Quickstarts/device-streams-echo/device 目录。In another local terminal window, navigate to the iot-hub/Quickstarts/device-streams-echo/device directory in your unzipped project folder. 请保留以下信息:Keep the following information handy:

参数名称Parameter name 参数值Parameter value
DeviceConnectionString IoT 中心的设备连接字符串。The device connection string of your IoT Hub.

使用以下命令编译并运行代码:Compile and run the code with the following commands:

cd ./iot-hub/Quickstarts/device-streams-echo/device/

# Build the application
dotnet build

# Run the application
# In Linux or macOS
dotnet run "{DeviceConnectionString}"

# In Windows
dotnet run {DeviceConnectionString}

最后一个步骤结束时,服务端应用程序会向设备发起流。At the end of the last step, the service-side application initiates a stream to your device. 建立流后,应用程序会通过该流将一个字符串缓冲区发送到服务。After the stream is established, the application sends a string buffer to the service over the stream. 在此示例中,服务端应用程序直接将相同的数据回显到设备,表明已成功地在两个应用程序之间建立双向通信。In this sample, the service-side application simply echoes back the same data to the device, which demonstrates a successful bidirectional communication between the two applications.

设备端的控制台输出:Console output on the device side:

设备端的控制台输出

服务端的控制台输出:Console output on the service side:

服务端的控制台输出

通过该流发送的流量将通过 IoT 中心以隧道方式进行传输,而不是直接发送。The traffic being sent over the stream is tunneled through the IoT hub rather than sent directly. 设备流优势中详细介绍了所提供的优势。The benefits provided are detailed in Device streams benefits.

清理资源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 C# applications on the device and service sides, and used the stream to send data back and forth between the applications.

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