在 Web 应用程序中可视化 Azure IoT 中心内的实时传感器数据Visualize real-time sensor data from your Azure IoT hub in a web application

端到端关系图

Note

开始本教程前,请设置设备Before you start this tutorial, set up your device. 在本文中,将设置 Azure IoT 设备和 IoT 中心,并部署一个在设备上运行的示例应用程序。In the article, you set up your Azure IoT device and IoT hub, and you deploy a sample application to run on your device. 该应用程序会将收集的传感器数据发送到 IoT 中心。The application sends collected sensor data to your IoT hub.

学习内容What you learn

本教程介绍如何使用本地计算机上运行的 node.js Web 应用将 IoT 中心收到的实时传感器数据可视化。In this tutorial, you learn how to visualize real-time sensor data that your IoT hub receives with a node.js web app running on your local computer. 在本地运行该 Web 应用后,可以选择性地遵循相应的步骤在 Azure 应用服务中托管该 Web 应用。After running the web app locally, you can optionally follow steps to host the web app in Azure App Service.

准备工作What you do

  • 将一个使用者组添加到 Web 应用程序用来读取传感器数据的 IoT 中心Add a consumer group to your IoT hub that the web application will use to read sensor data
  • 从 GitHub 下载 Web 应用代码Download the web app code from GitHub
  • 检查 Web 应用代码Examine the web app code
  • 配置环境变量用于保存 Web 应用所需的 IoT 中心项目Configure environment variables to hold the IoT Hub artifacts needed by your web app
  • 在开发计算机上运行该 Web 应用Run the web app on your development machine
  • 打开一个网页,以查看 IoT 中心内的实时温度和湿度数据Open a web page to see real-time temperature and humidity data from your IoT hub
  • (可选)使用 Azure CLI 在 Azure 应用服务中托管 Web 应用(Optional) Use Azure CLI to host your web app in Azure App Service

所需条件What you need

  • 完成 Raspberry Pi 联机模拟器教程或其中一个设备教程;例如将 Raspberry Pi 与 Node.js 配合使用Complete the Raspberry Pi online simulator tutorial or one of the device tutorials; for example, Raspberry Pi with node.js. 这包括以下要求:These cover the following requirements:

    • 一个有效的 Azure 订阅An active Azure subscription
    • 已在订阅中创建一个 IoT 中心An Iot hub under your subscription
    • 一个可向 IoT 中心发送消息的客户端应用程序A client application that sends messages to your Iot hub
  • 下载 GitDownload Git

  • 本文中的步骤假设使用 Windows 开发计算机;但是,也可以在 Linux 系统上使用偏好的 shell 轻松执行这些步骤。The steps in this article assume a Windows development machine; however, you can easily perform these steps on a Linux system in your preferred shell.

运行以下命令将用于 Azure CLI 的 Azure IoT 扩展添加。Run the following command to add the Azure IoT Extension for Azure CLI. 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 Azure CLI.

az extension add --name azure-iot

将使用者组添加到 IoT 中心Add a consumer group to your IoT hub

使用者组提供事件流的独立视图,可让应用和 Azure 服务单独使用同一事件中心终结点内的数据。Consumer groups provide independent views into the event stream that enable apps and Azure services to independently consume data from the same Event Hub endpoint. 在本部分,你要将一个使用者组添加到 IoT 中心的内置终结点,Web 应用将从该终结点读取数据。In this section, you add a consumer group to your IoT hub's built-in endpoint that the web app will use to read data from.

运行以下命令,将使用者组添加到 IoT 中心的内置终结点:Run the following command to add a consumer group to the built-in endpoint of your IoT hub:

az iot hub consumer-group create --hub-name YourIoTHubName --name YourConsumerGroupName

请记下所选的名称,因为本教程稍后需要用到。Note down the name you choose, you'll need it later in this tutorial.

获取 IoT 中心的服务连接字符串Get a service connection string for your IoT hub

创建的 IoT 中心具有多个默认访问策略。IoT hubs are created with several default access policies. 其中的一个策略是服务策略,该策略为某个服务提供足够的权限,使其能够读取和写入 IoT 中心的终结点。One such policy is the service policy, which provides sufficient permissions for a service to read and write the IoT hub's endpoints. 运行以下命令获取符合服务策略的 IoT 中心的连接字符串:Run the following command to get a connection string for your IoT hub that adheres to the service policy:

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

该连接字符串应如下所示:The connection string should look similar to the following:

"HostName={YourIotHubName}.azure-devices.cn;SharedAccessKeyName=service;SharedAccessKey={YourSharedAccessKey}"

请记下服务连接字符串,因为本教程稍后需要用到。Note down the service connection string, you'll need it later in this tutorial.

从 GitHub 下载 Web 应用Download the web app from GitHub

打开命令窗口,输入以下命令以从 GitHub 下载示例,然后切换到示例目录:Open a command window, and enter the following commands to download the sample from GitHub and change to the sample directory:

git clone https://github.com/Azure-Samples/web-apps-node-iot-hub-data-visualization.git
cd web-apps-node-iot-hub-data-visualization

检查 Web 应用代码Examine the web app code

在 web-apps-node-iot-hub-data-visualization 目录中,使用偏好的编辑器打开 Web 应用。From the web-apps-node-iot-hub-data-visualization directory, open the web app in your favorite editor. 下面显示了 VS Code 中显示的文件结构:The following shows the file structure viewed in VS Code:

Web 应用文件结构

请花费片刻时间检查以下文件:Take a moment to examine the following files:

  • Server.js 是用于初始化 Web 套接字和事件中心包装类的服务端脚本。Server.js is a service-side script that initializes the web socket and the Event Hub wrapper class. 它提供对事件中心包装类的回调,以便将传入的消息广播到 Web 套接字。It provides a callback to the Event Hub wrapper class that the class uses to broadcast incoming messages to the web socket.

  • Event-hub-reader.js 是使用指定的连接字符串和使用者组连接到 IoT 中心内置终结点的服务端脚本。Event-hub-reader.js is a service-side script that connects to the IoT hub's built-in endpoint using the specified connection string and consumer group. 它从传入消息中的元数据提取 DeviceId 和 EnqueuedTimeUtc,然后使用 server.js 注册的回调方法中继消息。It extracts the DeviceId and EnqueuedTimeUtc from metadata on incoming messages and then relays the message using the callback method registered by server.js.

  • Chart-device-data.js 是一个客户端脚本,可以侦听 Web 套接字,跟踪每个 DeviceId,并存储每个设备的最后 50 个传入数据点。Chart-device-data.js is a client-side script that listens on the web socket, keeps track of each DeviceId, and stores the last 50 points of incoming data for each device. 然后,它将选定的设备数据绑定到图表对象。It then binds the selected device data to the chart object.

  • Index.html 处理网页的 UI 布局,并引用客户端逻辑的所需脚本。Index.html handles the UI layout for the web page and references the necessary scripts for client-side logic.

配置 Web 应用的环境变量Configure environment variables for the web app

若要从 IoT 中心读取数据,Web 应用需要获取 IoT 中心的连接字符串,以及从中读取数据的使用者组的名称。To read data from your IoT hub, the web app needs your IoT hub's connection string and the name of the consumer group that it should read through. 它会从 server.js 的以下行中的进程环境获取这些字符串:It gets these strings from the process environment in the following lines in server.js:

const iotHubConnectionString = process.env.IotHubConnectionString;
const eventHubConsumerGroup = process.env.EventHubConsumerGroup;

在命令窗口中使用以下命令设置环境变量。Set the environment variables in your command window with the following commands. 请将占位符值替换为 IoT 中心的服务连接字符串,以及前面创建的使用者组的名称。Replace the placeholder values with the service connection string for your IoT hub and the name of the consumer group you created previously. 不要使用引号括住字符串。Don't quote the strings.

set IotHubConnectionString=YourIoTHubConnectionString
set EventHubConsumerGroup=YourConsumerGroupName

运行 Web 应用Run the web app

  1. 确保设备正在运行,且正在发送数据。Make sure that your device is running and sending data.

  2. 在命令窗口中,运行以下代码行以下载并安装引用的包,然后启动网站:In the command window, run the following lines to download and install referenced packages and start the website:

    npm install
    npm start
    
  3. 控制台中应会显示输出,指出 Web 应用已成功连接到 IoT 中心并在侦听端口 3000:You should see output in the console that indicates that the web app has successfully connected to your IoT hub and is listening on port 3000:

    Web 应用已在控制台上启动

打开一个网页以查看 IoT 中心的数据Open a web page to see data from your IoT hub

在浏览器中打开 http://localhost:3000Open a browser to http://localhost:3000.

在“选择设备”列表中选择你的设备,以查看设备发送到 IoT 中心的最后 50 个温度和湿度数据点的运行图。 In the Select a device list, select your device to see a running plot of the last 50 temperature and humidity data points sent by the device to your IoT hub.

显示实时温度和湿度的 Web 应用页

此外,控制台中还应有输出显示 Web 应用正在广播到浏览器客户端的消息:You should also see output in the console that shows the messages that your web app is broadcasting to the browser client:

控制台上的 Web 应用广播输出

在应用服务中托管 Web 应用Host the web app in App Service

Azure 应用服务的 Web 应用功能提供用于托管 Web 应用程序的平台即服务 (PAAS)。The Web Apps feature of Azure App Service provides a platform as a service (PAAS) for hosting web applications. 托管在 Azure 应用服务中的 Web 应用程序可受益于强大的 Azure 功能(例如更高的安全性、负载均衡和可伸缩性)以及 Azure 和合作伙伴 DevOps 解决方案(例如持续部署、包管理等)。Web applications hosted in Azure App Service can benefit from powerful Azure features like additional security, load balancing, and scalability as well as Azure and partner DevOps solutions like continuous deployment, package management, and so on. Azure 应用服务支持以多种流行语言开发的、部署在 Windows 或 Linux 基础结构上的 Web 应用程序。Azure App Service supports web applications developed in many popular languages and deployed on Windows or Linux infrastructure.

在本部分,你将在应用服务中预配一个 Web 应用,然后使用 Azure CLI 命令将代码部署到该应用。In this section, you provision a web app in App Service and deploy your code to it by using Azure CLI commands. 可以在 az webapp 文档中查找所用命令的详细信息。You can find details of the commands used in the az webapp documentation. 在开始之前,请确保已完成将资源组添加到 IoT 中心获取 IoT 中心的服务连接字符串以及从 GitHub下载 Web 应用的步骤。Before starting, make sure you've completed the steps to add a resource group to your IoT hub, get a service connection string for your IoT hub, and download the web app from GitHub.

  1. 应用服务计划为应用服务中托管的应用定义一组计算资源,使其能够运行。An App Service plan defines a set of compute resources for an app hosted in App Service to run. 本教程使用开发人员/免费层来托管 Web 应用。In this tutorial, we use the Developer/Free tier to host the web app. 使用免费层时,你的 Web 应用将在与其他应用服务应用(包括其他客户的应用)共享的 Windows 资源上运行。With the Free tier, your web app runs on shared Windows resources with other App Service apps, including apps of other customers. Azure 还提供应用服务计划用于在 Linux 计算资源上部署 Web 应用。Azure also offers App Service plans to deploy web apps on Linux compute resources. 如果你已有可用的应用服务计划,则可以跳过此步骤。You can skip this step if you already have an App Service plan that you want to use.

    若要使用 Windows 免费层创建应用服务计划,请运行以下命令。To create an App Service plan using the Windows free tier, run the following command. 使用 IoT 中心所在的同一资源组。Use the same resource group your IoT hub is in. 服务计划名称可以包含大小写字母、数字和连字符。Your service plan name can contain upper and lower case letters, numbers, and hyphens.

    az appservice plan create --name <app service plan name> --resource-group <your resource group name> --sku FREE
    
  2. 现在,在应用服务计划中预配一个 Web 应用。Now provision a web app in your App Service plan. 使用 --deployment-local-git 参数可从本地计算机上的 Git 存储库上传和部署 Web 应用代码。The --deployment-local-git parameter enables the web app code to be uploaded and deployed from a Git repository on your local machine. Web 应用名称必须全局唯一,可以包含大小写字母、数字和连字符。Your web app name must be globally unique and can contain upper and lower case letters, numbers, and hyphens. 请确保为 --runtime 参数指定 Node 版本 10.6 或更高版本,具体取决于所使用的 Node.js 运行时版本。Be sure to specify Node version 10.6 or later for the --runtime parameter, depending on the version of the Node.js runtime you are using. 可以使用 az webapp list-runtimes 命令获取支持的运行时列表。You can use the az webapp list-runtimes command to get a list of supported runtimes.

    az webapp create -n <your web app name> -g <your resource group name> -p <your app service plan name> --runtime "node|10.6" --deployment-local-git
    
  3. 现在,为指定 IoT 中心连接字符串和事件中心使用者组的环境变量添加应用程序设置。Now add Application Settings for the environment variables that specify the IoT hub connection string and the Event hub consumer group. -settings 参数中的每项设置以空格分隔。Individual settings are space delimited in the -settings parameter. 请使用 IoT 中心的服务连接字符串,以及前面在本教程中创建的使用者组。Use the service connection string for your IoT hub and the consumer group you created previously in this tutorial. 不要将值括在引号中。Don't quote the values.

    az webapp config appsettings set -n <your web app name> -g <your resource group name> --settings EventHubConsumerGroup=<your consumer group> IotHubConnectionString=<your IoT hub connection string>
    
  4. 为 Web 应用启用 Web 套接字协议,并将 Web 应用设置为仅接收 HTTPS 请求(HTTP 请求将重定向到 HTTPS)。Enable the Web Sockets protocol for the web app and set the web app to receive HTTPS requests only (HTTP requests are redirected to HTTPS).

    az webapp config set -n <your web app name> -g <your resource group name> --web-sockets-enabled true
    az webapp update -n <your web app name> -g <your resource group name> --https-only true
    
  5. 若要将代码部署到应用服务,需使用用户级部署凭据To deploy the code to App Service, you'll use your user-level deployment credentials. 用户级部署凭据不同于 Azure 凭据,用于在 Web 应用中实现 Git 本地部署和 FTP 部署。Your user-level deployment credentials are different from your Azure credentials and are used for Git local and FTP deployments to a web app. 设置后,可对 Azure 帐户中所有订阅内的所有应用服务应用使用这些凭据。Once set, they're valid across all of your App Service apps in all subscriptions in your Azure account. 如果以前已经设置了用户级部署凭据,则可以使用这些凭据。If you've previously set user-level deployment credentials, you can use them.

    如果以前尚未设置用户级部署凭据或不记得密码,请运行以下命令。If you haven't previously set user-level deployment credentials or you can't remember your password, run the following command. 部署用户名必须在 Azure 中唯一,不得包含用于本地 Git 推送的“@”符号。Your deployment user name must be unique within Azure, and it must not contain the ‘@’ symbol for local Git pushes. 出现提示时,请输入并确认新密码。When you're prompted, enter and confirm your new password. 密码必须至少为 8 个字符,且具有字母、数字和符号这三种元素中的两种。The password must be at least eight characters long, with two of the following three elements: letters, numbers, and symbols.

    az webapp deployment user set --user-name <your deployment user name>
    
  6. 获取用于将代码推送到应用服务的 Git URL。Get the Git URL to use to push your code up to App Service.

    az webapp deployment source config-local-git -n <your web app name> -g <your resource group name>
    
  7. 将远程库添加到引用应用服务中 Web 应用的 Git 存储库的克隆。Add a remote to your clone that references the Git repository for the web app in App Service. 对于“<Git 克隆 URL>”,请使用上一步骤返回的 URL。For <Git clone URL>, use the URL returned in the previous step. 在命令窗口中运行以下命令。Run the following command in your command window.

    git remote add webapp <Git clone URL>
    
  8. 若要将代码部署到应用服务,请在命令窗口中输入以下命令。To deploy the code to App Service, enter the following command in your command window. 系统提示输入凭据时,请输入在步骤 5 中创建的用户级部署凭据。If you are prompted for credentials, enter the user-level deployment credentials that you created in step 5. 确保推送到应用服务远程库的主分支。Make sure that you push to the master branch of the App Service remote.

    git push webapp master:master
    
  9. 命令窗口中的部署进度将会更新。The progress of the deployment will update in your command window. 如果部署成功,将返回类似于以下输出的行:A successful deployment will end with lines similar to the following output:

    remote:
    remote: Finished successfully.
    remote: Running post deployment command(s)...
    remote: Deployment successful.
    To https://contoso-web-app-3.scm.azurewebsites.cn/contoso-web-app-3.git
    6b132dd..7cbc994  master -> master
    
  10. 运行以下命令,以查询 Web 应用的状态并确保它正在运行:Run the following command to query the state of your web app and make sure it is running:

    az webapp show -n <your web app name> -g <your resource group name> --query state
    
  11. 在浏览器中导航到 https://<your web app name>.azurewebsites.cnNavigate to https://<your web app name>.azurewebsites.cn in a browser. 此时会显示一个网页,它类似于在本地运行 Web 应用时所看到的网页。A web page similar to the one you saw when you ran the web app locally displays. 假设你的设备正在运行且正在发送数据,则应会显示该设备最近发送的 50 个温度和湿度读数的运行图。Assuming that your device is running and sending data, you should see a running plot of the 50 most recent temperature and humidity readings sent by the device.

故障排除Troubleshooting

如果在学习本示例期间遇到任何问题,请尝试执行以下部分所述的步骤。If you come across any issues with this sample, try the steps in the following sections. 如果问题仍然出现,请通过本主题末尾的链接向我们发送反馈。If you still have problems, send us feedback at the bottom of this topic.

客户端问题Client issues

  • 如果设备未显示在列表中,或者未绘制任何图形,请确保设备代码在设备上运行。If a device does not appear in the list, or no graph is being drawn, make sure the device code is running on your device.

  • 在浏览器中打开开发人员工具(在许多浏览器中,按 F12 键可以打开它),并找到控制台。In the browser, open the developer tools (in many browsers the F12 key will open it), and find the console. 查看其中列显的任何警告或错误。Look for any warnings or errors printed there.

  • 可以调试 /js/chat-device-data.js 中的客户端脚本。You can debug client-side script in /js/chat-device-data.js.

本地网站问题Local website issues

  • 观察启动 node 时所在的窗口中的控制输出。Watch the output in the window where you launched node for console output.

  • 调试服务器代码,具体而言,是 server.js 和 /scripts/event-hub-reader.js。Debug the server code, specifically server.js and /scripts/event-hub-reader.js.

Azure 应用服务问题Azure App Service issues

  • 在 Azure 门户中转到你的 Web 应用。In Azure portal, go to your web app. 在左窗格中的“监视”下,选择“应用服务日志”。 Under Monitoring in the left pane, select App Service logs. 启用“应用程序日志记录(文件系统)”,将“级别”设置为“错误”,并选择“保存”。 Turn Application Logging (File System) to on, set Level to Error, and then select Save. 然后打开“日志流”(在“监视”下)。 Then open Log stream (under Monitoring).

  • 在 Azure 门户上的 Web 应用中,在“开发工具”下选择“控制台”,然后使用 node -vnpm -v 验证 node 和 npm 版本。 From your web app in Azure portal, under Development Tools select Console and validate node and npm versions with node -v and npm -v.

  • 如果看到了有关找不到包的错误,则可能表示步骤的运行顺序不当。If you see an error about not finding a package, you may have run the steps out of order. 部署站点(使用 git push)时,应用服务将会根据当前配置的 node 版本运行 npm installWhen the site is deployed (with git push) the app service runs npm install, which runs based on the current version of node it has configured. 如果以后在配置中更改此版本,则需要对代码进行无意义的更改,然后再次推送。If that is changed in configuration later, you'll need to make a meaningless change to the code and push again.

后续步骤Next steps

若要继续了解 Azure IoT 中心入门知识并浏览所有扩展的 IoT 方案,请参阅:To continue to get started with Azure IoT Hub and to explore all extended IoT scenarios, see the following: