Visualize real-time sensor data from your Azure IoT hub in a web application
Before you start this tutorial, complete the Raspberry Pi online simulator tutorial or one of the device tutorials; for example, Raspberry Pi with node.js. In these articles, you set up your Azure IoT device and IoT hub, and you deploy a sample application to run on your device. The application sends collected sensor data to your IoT hub.
What you learn
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. After running the web app locally, you can optionally follow steps to host the web app in Azure App Service. If you want to try to visualize the data in your IoT hub by using Power BI, see Use Power BI to visualize real-time sensor data from Azure IoT Hub.
What you do
- Add a consumer group to your IoT hub that the web application will use to read sensor data
- Download the web app code from GitHub
- Examine the web app code
- Configure environment variables to hold the IoT Hub artifacts needed by your web app
- Run the web app on your development machine
- Open a web page to see real-time temperature and humidity data from your IoT hub
- (Optional) Use Azure CLI to host your web app in Azure App Service
What you need
- An active Azure subscription
- An Iot hub under your subscription
- A client application that sends messages to your Iot hub
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.
Use Azure Cloud Shell
Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. Cloud Shell lets you use either
PowerShell to work with Azure services. 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.
To launch Azure Cloud Shell:
|Select Try It in the upper-right corner of a code block. Selecting Try It doesn't automatically copy the code to Cloud Shell.|
|Go to https://shell.azure.com or select the Launch Cloud Shell button to open Cloud Shell in your browser.|
|Select the Cloud Shell button on the top-right menu bar in the Azure portal.|
To run the code in this article in Azure Cloud Shell:
- Launch Cloud Shell.
- Select the Copy button on a code block to copy the code.
- Paste the code into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS.
- Press Enter to run the code.
Run the following command to add the Microsoft Azure IoT Extension for Azure CLI to your Cloud Shell instance. The IOT Extension adds IoT Hub, IoT Edge, and IoT Device Provisioning Service (DPS) specific commands to Azure CLI.
az extension add --name azure-cli-iot-ext
Add a consumer group to your IoT hub
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. 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.
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.
Get a service connection string for your IoT hub
IoT hubs are created with several default access policies. One such policy is the service policy, which provides sufficient permissions for a service to read and write the IoT hub's endpoints. 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:
Note down the service connection string, you'll need it later in this tutorial.
Download the web app from 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
Examine the web app code
From the web-apps-node-iot-hub-data-visualization directory, open the web app in your favorite editor. The following shows the file structure viewed in VS Code:
Take a moment to examine the following files:
Server.js is a service-side script that initializes the web socket and the Event Hub wrapper class. 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 is a service-side script that connects to the IoT hub's built-in endpoint using the specified connection string and consumer group. 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 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 handles the UI layout for the web page and references the necessary scripts for client-side logic.
Configure environment variables for the web app
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. 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. 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
Run the web app
Make sure that your device is running and sending data.
In the command window, run the following lines to download and install referenced packages and start the website:
npm install npm start
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:
Open a web page to see data from your IoT hub
Open a browser to
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.
You should also see output in the console that shows the messages that your web app is broadcasting to the browser client:
Host the web app in App Service
The Web Apps feature of Azure App Service provides a platform as a service (PAAS) for hosting web applications. 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 App Service supports web applications developed in many popular languages and deployed on Windows or Linux infrastructure.
In this section, you provision a web app in App Service and deploy your code to it by using Azure CLI commands. You can find details of the commands used in the az webapp documentation. 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.
An App Service plan defines a set of compute resources for an app hosted in App Service to run. In this tutorial, we use the Developer/Free tier to host the web app. With the Free tier, your web app runs on shared Windows resources with other App Service apps, including apps of other customers. 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.
To create an App Service plan using the Windows free tier, run the following command. 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
Now provision a web app in your App Service plan. The
--deployment-local-gitparameter enables the web app code to be uploaded and deployed from a Git repository on your local machine. Your web app name must be globally unique and can contain upper and lower case letters, numbers, and hyphens.
az webapp create -n <your web app name> -g <your resource group name> -p <your app service plan name> --deployment-local-git
Now add Application Settings for the environment variables that specify the IoT hub connection string and the Event hub consumer group. Individual settings are space delimited in the
-settingsparameter. 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>
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
To deploy the code to App Service, you'll use your user-level deployment credentials. Your user-level deployment credentials are different from your Azure credentials and are used for Git local and FTP deployments to a web app. 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. 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. 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>
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>
Add a remote to your clone that references the Git repository for the web app in App Service. 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>
To deploy the code to App Service, enter the following command in your command window. 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
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.net/contoso-web-app-3.git 6b132dd..7cbc994 master -> master
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
https://<your web app name>.azurewebsites.netin a browser. A web page similar to the one you saw when you ran the web app locally displays. 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.
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.
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.
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.
You can debug client-side script in /js/chat-device-data.js.
Local website issues
Watch the output in the window where you launched node for console output.
Debug the server code, specifically server.js and /scripts/event-hub-reader.js.
Azure App Service issues
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).
From your web app in Azure portal, under Development Tools select Console and validate node and npm versions with
If you see an error about not finding a package, you may have run the steps out of order. When 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.
You've successfully used your web app to visualize real-time sensor data from your IoT hub.
For another way to visualize data from Azure IoT Hub, see Use Power BI to visualize real-time sensor data from your IoT hub.
To continue to get started with Azure IoT Hub and to explore all extended IoT scenarios, see the following: