title | description | services | author | manager | ms.author | ms.date | ms.topic | ms.service | ms.custom |
---|---|---|---|---|---|---|---|---|---|
Tutorial develop Node.js module for Linux - Azure IoT Edge | Microsoft Docs |
This tutorial shows you how to create an IoT Edge module with Node.js code and deploy it to an edge device |
iot-edge |
shizn |
philmea |
xshi |
01/04/2019 |
tutorial |
iot-edge |
mvc, tracking-python |
Use Visual Studio Code to develop Node.js code and deploy it to a Linux device running Azure IoT Edge.
You can use IoT Edge modules to deploy code that implements your business logic directly to your IoT Edge devices. This tutorial walks you through creating and deploying an IoT Edge module that filters sensor data. You'll use the simulated IoT Edge device that you created in the quickstarts. In this tutorial, you learn how to:
[!div class="checklist"]
- Use Visual Studio Code to create an IoT Edge Node.js module
- Use Visual Studio Code and Docker to create a docker image and publish it to your registry
- Deploy the module to your IoT Edge device
- View generated data
The IoT Edge module that you create in this tutorial filters the temperature data generated by your device. It only sends messages upstream if the temperature is above a specified threshold. This type of analysis at the edge is useful for reducing the amount of data communicated to and stored in the cloud.
[!INCLUDE quickstarts-free-trial-note]
This tutorial demonstrates how to develop a module in Node.js using Visual Studio Code, and how to deploy it to a Linux device. IoT Edge does not support Node.js modules for Windows devices.
Use the following table to understand your options for developing and deploying Node.js modules:
Node.js | Visual Studio Code | Visual Studio 2017/2019 |
---|---|---|
Linux AMD64 | ![]() |
|
Linux ARM32 | ![]() |
Before beginning this tutorial, you should have gone through the previous tutorial to set up your development environment for Linux container development: Develop IoT Edge modules for Linux devices. By completing either of those tutorials, you should have the following prerequisites in place:
- A free or standard-tier IoT Hub in Azure.
- A Linux device running Azure IoT Edge
- A container registry, like Azure Container Registry.
- Visual Studio Code configured with the Azure IoT Tools.
- Docker CE configured to run Linux containers.
To develop an IoT Edge module in Node.js, install the following additional prerequisites on your development machine:
- Node.js and npm. The npm package is distributed with Node.js, which means that when you download Node.js, you automatically get npm installed on your computer.
The following steps show you how to create an IoT Edge Node.js module using Visual Studio Code and the Azure IoT Tools.
Use npm to create a Node.js solution template that you can build on top of.
-
In Visual Studio Code, select View > Integrated Terminal to open the VS Code integrated terminal.
-
In the integrated terminal, enter the following command to install yeoman and the generator for Node.js Azure IoT Edge module:
npm install -g yo generator-azure-iot-edge-module
-
Select View > Command Palette to open the VS Code command palette.
-
In the command palette, type and run the command Azure: Sign in and follow the instructions to sign in your Azure account. If you've already signed in, you can skip this step.
-
In the command palette, type and run the command Azure IoT Edge: New IoT Edge solution. Follow the prompts in the command palette to create your solution.
Field Value Select folder Choose the location on your development machine for VS Code to create the solution files. Provide a solution name Enter a descriptive name for your solution or accept the default EdgeSolution. Select module template Choose Node.js Module. Provide a module name Name your module NodeModule. Provide Docker image repository for the module An image repository includes the name of your container registry and the name of your container image. Your container image is prepopulated from the name you provided in the last step. Replace localhost:5000 with the login server value from your Azure container registry. You can retrieve the login server from the Overview page of your container registry in the Azure portal.
The final image repository looks like <registry name>.azurecr.io/nodemodule.
The environment file stores the credentials for your container repository and shares those with the IoT Edge runtime. The runtime needs these credentials to pull your private images onto the IoT Edge device.
- In the VS Code explorer, open the .env file.
- Update the fields with the username and password values that you copied from your Azure container registry.
- Save this file.
Currently, Visual Studio Code can develop Node.js modules for Linux AMD64 and Linux ARM32v7 devices. You need to select which architecture you're targeting with each solution, because the container is built and run differently for each architecture type. The default is Linux AMD64.
-
Open the command palette and search for Azure IoT Edge: Set Default Target Platform for Edge Solution, or select the shortcut icon in the side bar at the bottom of the window.
-
In the command palette, select the target architecture from the list of options. For this tutorial, we're using an Ubuntu virtual machine as the IoT Edge device, so will keep the default amd64.
Each template comes with sample code included, which takes simulated sensor data from the SimulatedTemperatureSensor module and routes it to IoT Hub. In this section, add code to have NodeModule analyze the messages before sending them.
-
In the VS Code explorer, open modules > NodeModule > app.js.
-
Add a temperature threshold variable below required node modules. The temperature threshold sets the value that the measured temperature must exceed in order for the data to be sent to IoT Hub.
var temperatureThreshold = 25;
-
Replace the entire
PipeMessage
function with theFilterMessage
function.// This function filters out messages that report temperatures below the temperature threshold. // It also adds the MessageType property to the message with the value set to Alert. function filterMessage(client, inputName, msg) { client.complete(msg, printResultFor('Receiving message')); if (inputName === 'input1') { var message = msg.getBytes().toString('utf8'); var messageBody = JSON.parse(message); if (messageBody && messageBody.machine && messageBody.machine.temperature && messageBody.machine.temperature > temperatureThreshold) { console.log(`Machine temperature ${messageBody.machine.temperature} exceeds threshold ${temperatureThreshold}`); var outputMsg = new Message(message); outputMsg.properties.add('MessageType', 'Alert'); client.sendOutputEvent('output1', outputMsg, printResultFor('Sending received message')); } } }
-
Replace the function name
pipeMessage
withfilterMessage
inclient.on()
function.client.on('inputMessage', function (inputName, msg) { filterMessage(client, inputName, msg); });
-
Copy the following code snippet into the
client.open()
function callback, afterclient.on()
inside theelse
statement. This function is invoked when the desired properties are updated.client.getTwin(function (err, twin) { if (err) { console.error('Error getting twin: ' + err.message); } else { twin.on('properties.desired', function(delta) { if (delta.TemperatureThreshold) { temperatureThreshold = delta.TemperatureThreshold; } }); } });
-
Save the app.js file.
-
In the VS Code explorer, open the deployment.template.json file in your IoT Edge solution workspace.
-
Add the NodeModule module twin to the deployment manifest. Insert the following JSON content at the bottom of the
moduleContent
section, after the$edgeHub
module twin:"NodeModule": { "properties.desired":{ "TemperatureThreshold":25 } }
-
Save the deployment.template.json file.
In the previous section, you created an IoT Edge solution and added code to the NodeModule that will filter out messages where the reported machine temperature is within the acceptable limits. Now you need to build the solution as a container image and push it to your container registry.
-
Open the VS Code integrated terminal by selecting View > Terminal.
-
Sign in to Docker by entering the following command in the terminal. Sign in with the username, password, and login server from your Azure container registry. You can retrieve these values from the Access keys section of your registry in the Azure portal.
docker login -u <ACR username> -p <ACR password> <ACR login server>
You may receive a security warning recommending the use of
--password-stdin
. While that best practice is recommended for production scenarios, it's outside the scope of this tutorial. For more information, see the docker login reference. -
In the VS Code explorer, right-click the deployment.template.json file and select Build and Push IoT Edge solution.
The build and push command starts three operations. First, it creates a new folder in the solution called config that holds the full deployment manifest, built out of information in the deployment template and other solution files. Second, it runs
docker build
to build the container image based on the appropriate dockerfile for your target architecture. Then, it runsdocker push
to push the image repository to your container registry.
Use the Visual Studio Code explorer and the Azure IoT Tools extension to deploy the module project to your IoT Edge device. You already have a deployment manifest prepared for your scenario, the deployment.json file in the config folder. All you need to do now is select a device to receive the deployment.
Make sure that your IoT Edge device is up and running.
-
In the Visual Studio Code explorer, expand the Azure IoT Hub Devices section to see your list of IoT devices.
-
Right-click the name of your IoT Edge device, then select Create Deployment for Single Device.
-
Select the deployment.json file in the config folder and then click Select Edge Deployment Manifest. Do not use the deployment.template.json file.
-
Click the refresh button. You should see the new NodeModule running along with the SimulatedTemperatureSensor module and the $edgeAgent and $edgeHub.
Once you apply the deployment manifest to your IoT Edge device, the IoT Edge runtime on the device collects the new deployment information and starts executing on it. Any modules running on the device that aren't included in the deployment manifest are stopped. Any modules missing from the device are started.
You can view the status of your IoT Edge device using the Azure IoT Hub Devices section of the Visual Studio Code explorer. Expand the details of your device to see a list of deployed and running modules.
-
In the Visual Studio Code explorer, right-click the name of your IoT Edge device and select Start Monitoring Built-in Event Endpoint.
-
View the messages arriving at your IoT Hub. It may take a while for the messages to arrive. The IoT Edge device has to receive its new deployment and start all the modules. Then, the changes we made to the NodeModule code wait until the machine temperature reaches 25 degrees before sending messages. It also adds the message type Alert to any messages that reach that temperature threshold.
We used the NodeModule module twin in the deployment manifest to set the temperature threshold at 25 degrees. You can use the module twin to change the functionality without having to update the module code.
-
In Visual Studio Code, expand the details under your IoT Edge device to see the running modules.
-
Right-click NodeModule and select Edit module twin.
-
Find TemperatureThreshold in the desired properties. Change its value to a new temperature 5 degrees to 10 degrees higher than the latest reported temperature.
-
Save the module twin file.
-
Right-click anywhere in the module twin editing pane and select Update module twin.
-
Monitor the incoming device-to-cloud messages. You should see the messages stop until the new temperature threshold is reached.
If you plan to continue to the next recommended article, you can keep the resources and configurations that you created and reuse them. You can also keep using the same IoT Edge device as a test device.
Otherwise, you can delete the local configurations and the Azure resources that you created in this article to avoid charges.
[!INCLUDE iot-edge-clean-up-cloud-resources]
In this tutorial, you created an IoT Edge module that contains code to filter raw data generated by your IoT Edge device. When you're ready to build your own modules, you can learn more about developing your own IoT Edge modules or how to develop modules with Visual Studio Code. For examples of IoT Edge modules, including the simulated temperature module, see IoT Edge module samples.
You can continue on to the next tutorials to learn how Azure IoT Edge can help you deploy Azure cloud services to process and analyze data at the edge.
[!div class="nextstepaction"] Functions Stream Analytics Machine Learning Custom Vision Service