您现在访问的是微软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 Cloud ShellUse Azure Cloud Shell

Azure 托管 Azure Cloud Shell(一个可通过浏览器使用的交互式 shell 环境)。Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. 通过 Cloud Shell 可以将 bashPowerShell 与 Azure 服务配合使用。Cloud Shell lets you use either bash or PowerShell to work with Azure services. 可以使用 Azure Cloud Shell 预安装的命令来运行本文中的代码,而不必在本地环境中安装任何内容。You can use the Cloud Shell pre-installed commands to run the code in this article without having to install anything on your local environment.

若要启动 Azure Cloud Shell,请执行以下操作:To launch Azure Cloud Shell:

选项Option 示例/链接Example/Link
选择代码块右上角的“试用”。 Select Try It in the upper-right corner of a code block. 选择“试用” 不会自动将代码复制到 Cloud Shell。Selecting Try It doesn't automatically copy the code to Cloud Shell. Azure Cloud Shell 的“试用”示例
转到 https://shell.azure.com 或选择“启动 Cloud Shell” 按钮可在浏览器中打开 Cloud Shell。Go to https://shell.azure.com or select the Launch Cloud Shell button to open Cloud Shell in your browser. 在新窗口中启动 Cloud ShellLaunch Cloud Shell in a new window
选择 Azure 门户右上方菜单栏中的“Cloud Shell” 按钮。Select the Cloud Shell button on the top-right menu bar in the Azure portal. Azure 门户中的“Cloud Shell”按钮

若要在 Azure Cloud Shell 中运行本文中的代码,请执行以下操作:To run the code in this article in Azure Cloud Shell:

  1. 打开 Cloud Shell。Open Cloud Shell.
  2. 选择代码块上的“复制”按钮 以复制代码。Select the Copy button on a code block to copy the code.
  3. 在 Windows 和 Linux 上使用 Ctrl+Shift+V 将代码粘贴到 Cloud Shell 会话中,或在 macOS 上使用 Cmd+Shift+V 将代码粘贴到 Cloud Shell 会话中。Paste the code into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS.
  4. Enter 运行此代码。Press Enter to run the code.

如果还没有 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
  • 本快速入门中运行的两个示例应用程序是使用 C# 编写的。The two sample applications that you run in this quickstart are written by using C#. 开发计算机上需要有 .NET Core SDK 2.1.0 或更高版本。You need the .NET Core SDK 2.1.0 or later on your development machine.

    dotnet --version
    
  • 运行以下命令,将用于 Azure CLI 的 Azure IoT 扩展添加到 Cloud Shell 实例。Add the Azure IoT Extension for Azure CLI to your Cloud Shell instance by running the following command. IOT 扩展会将 IoT 中心、IoT Edge 和 IoT 设备预配服务 (DPS) 特定的命令添加到 Azure CLI。The IOT Extension adds IoT Hub, IoT Edge, and IoT Device Provisioning Service (DPS)-specific commands to the Azure CLI.

    az extension add --name azure-cli-iot-ext
    
  • 下载示例 C# 项目并解压缩 ZIP 存档。Download the sample C# project and extract the ZIP archive. 需要在设备端和服务端执行此操作。You need it on both the device side and the service side.

创建 IoT 中心Create an IoT hub

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

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

  2. 选择“创建资源”,然后选择“物联网”。 Select Create a resource, and then select Internet of Things.

  3. 在右侧的列表中选择“IoT 中心”。 In the list at the right, select Iot Hub. 此时会打开用于创建 IoT 中心的第一个页面。The first page for creating an IoT hub opens.

    在 Azure 门户中创建 IoT 中心

    填写字段:Fill in the fields:

    a.a. 在“订阅”下拉列表中,选择要用于 IoT 中心的订阅。 In the Subscription drop-down list, select the subscription to use for your IoT hub.

    b.b. 对于“资源组”,请执行以下操作之一: For Resource Group, do either of the following:

    • 若要创建新的资源组,请选择“新建”,然后输入所需的名称 。To create a new resource group, select Create new and enter the name you want to use.

    • 若要使用现有资源组,请选择“使用现有项”,然后在下拉列表中选择该资源组。 To use an existing resource group, select Use existing and then, in the drop-down list, select the resource group.

      有关详细信息,请参阅管理 Azure 资源管理器资源组For more information, see Manage Azure Resource Manager resource groups.

    c.c. 在“区域”下拉列表中,选择要在其中创建中心的区域。 In the Region drop-down list, select the region in which you want your hub to be located. 选择支持 IoT 中心设备流预览版的区域:“美国中部”或“美国中部 EUAP”。 Select a region that supports the IoT Hub device streams preview, either Central US or Central US EUAP.

    d.d. 在“IoT 中心名称”框中,输入 IoT 中心的名称。 In the IoT Hub Name box, enter the name for your IoT hub. 该名称必须全局唯一。The name must be globally unique. 如果输入的名称可用,会显示一个绿色复选标记。If the name you enter is available, a green check mark appears.

    重要

    由于 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.

  4. 若要继续创建 IoT 中心,请选择“下一步: 大小和规模”。To continue creating your IoT hub, select Next: Size and scale.

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

    在此窗格中,可以接受默认设置并选择底部的“查看 + 创建”。 In this pane, you can accept the default settings and select Review + create at the bottom. 请考虑以下选项:Consider the following options:

    • 在“定价和规模层”下拉列表中,选择一个标准层(“S1”、“S2”或“S3”),或选择“F1: 免费层”。In the Pricing and scale tier drop-down list, select one of the standard tiers (S1, S2, or S3) or F1: Free tier. 也可根据队列大小以及预期在中心会出现的非流式处理工作负荷(例如遥测消息)完成该选择。This choice can also be guided by the size of your fleet and the non-streaming workloads that you expect in your hub (for example, telemetry messages). 例如,免费层适用于测试和评估。For example, the free tier is intended for testing and evaluation. 它允许 500 台设备连接到 IoT 中心,并且每天最多传输 8,000 条信息。It allows 500 devices to be connected to the IoT hub and up to 8,000 messages per day. 每个 Azure 订阅可以在免费层中创建一个 IoT 中心。Each Azure subscription can create one IoT hub in the free tier.

    • 对于“IoT 中心单元数”: 此项选择取决于中心内预期会出现的非流式处理工作负荷。For Number of IoT Hub units: This choice depends on non-streaming workload you expect in your hub. 暂时可以选择“1”。You can select 1 for now.

    有关层选项的详细信息,请参阅选择适当的 IoT 中心层For more information about tier options, see Choose the right IoT hub tier.

  5. 若要检查所做的选择,请选择“查看+创建”选项卡。 此时会打开如下所示的窗格:To review your choices, select the Review + create tab. The pane that opens is similar to the following:

    用于创建新 IoT 中心的信息

  6. 若要创建新的 IoT 中心,请选择“创建” 。To create your new IoT hub, select Create. 该过程需要花费几分钟时间。The process 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 choose for your IoT hub.
    • 如示例中所示使用 MyDeviceUse MyDevice, as shown. 它是为注册的设备提供的名称。It's the name given for the registered device. 如果为设备选择其他名称,请在本文中从头至尾使用该名称,并在运行示例应用程序之前在其中更新设备名称。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 choose for your IoT hub.

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

    请记下设备连接字符串,稍后需要在本快速入门中用到它。Note the 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 choose for your IoT hub.

    az iot hub show-connection-string --policy-name service --name YourIoTHubName
    

    请记下返回的值,因为稍后要在本快速入门中用到它。Note the returned value 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 目录。Go 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 中心的服务连接字符串。Provide the service connection string of your IoT hub.
DeviceId 提供之前创建的设备的 ID(例如 MyDevice)。Provide the ID of the device you created earlier (for example, MyDevice).

按如下所示编译并运行代码:Compile and run the code as follows:

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>

备注

如果设备端应用程序未及时响应,则会发生超时。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 目录。Go 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 中心的设备连接字符串。Provide the device connection string of your IoT Hub.

按如下所示编译并运行代码:Compile and run the code as follows:

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've 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: