Skip to main content

Automatic Device Management with Device Twins in Azure

Hands-On Lab

 

Photo of Shawn Johnson

Shawn Johnson

Azure Training Architect II in Content

Length

01:00:00

Difficulty

Intermediate

Managing one or two IoT devices is really no big deal. But what if you had 100 devices? 1000? Then things get a little more interesting. And by interesting, we mean excruciatingly painful.

But help is on the way, in the form of Automatic Device Management in Azure IoT Hub. We can use this handy feature to manage properties and tags on hundreds of IoT devices at the same time!

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Automatic Device Management with Device Twins in Azure

Introduction

Managing one or two IoT devices is really no big deal. But what if you had 100 devices? 1000? Then things get a little more interesting. And by interesting, we mean excruciatingly painful.

But help is on the way, in the form of Automatic Device Management in Azure IoT Hub. We can use this handy feature to manage properties and tags on hundreds of IoT devices at the same time!

The Scenario

You have recently been hired by Parktronics, a monitoring company that works with local, state, and national park services. They have decided to use Azure IoT to develop Gatekeeper, a solution that will monitor entry and exit gates to ensure they are closed and locked at closing time.

You've been tasked with a proof-of-concept of the Gatekeeper solution. Prior to shipping out a device for use in your proof-of-concept, you are using Azure’s Automated Device Management feature to set properties on your simulated IoT device.

You will need to:

  • Register a device with Azure IoT Hub
  • Create an IoT Device Deployment
  • View the Device Twin
  • Download Sample Node App
  • Modify and Execute Node App
  • Verify Results

If you get stuck, feel free to check out the solution video or the detailed instructions under each objective. Good luck!

Tools

You will be using the Azure CLI to perform most of the tasks in this lab. You can access the CLI by using Azure Cloud Shell. When accessing the shell, select Show advanced settings, and use the existing storage account that is in the location where the storage group resides.

Node.js Application

We will be using the sample IoT Node.js application to simulate the IoT device application. This app can be downloaded from GitHub.

Lab Suffix

Predeployed lab resources will all end with a unique five-character suffix. Make note of this suffix, as you may need it when naming resources during the lab.

WARNING: Be Prepared for UI Changes

Given the fluid nature of Microsoft cloud tools, you may experience user interface (UI) changes that were made following the development of this hands-on lab that do not match up with lab instructions. When any such changes are brought to our attention, we will attempt to update the content accordingly. However, if changes occur, students will have to adapt to the changes and work through them in the hands-on labs as needed.

Logging In

Use the credentials provided on the hands-on lab page, and log into the Azure Portal.

Getting Our Bearings

Before we create anything, let's take a look at what's already been set up for us. Navigate to Resource groups, and click on the one that has been provided.

Once we're in there, we should see a storage account and an IoT Hub. Note the location where the storage account was provisioned. We'll need that in a little bit.

Go ahead and click on the Cloud Shell icon at the top of the screen and we can get started.

Register and Configure the Device with an Azure IoT Hub

  1. In the Welcome to Azure Cloud Shell window, choose Bash.
  2. At the You have no storage mounted prompt, click Show advanced settings.
  3. Make sure Use existing is selected as a Resource group, change the Cloud Shell region to the one where our storage account was created, then select Use existing, and our storage account should appear. In the File share section, select Use existing and enter cloudshell as a name. Click Attach storage to complete this part of the process.
  4. Next, install the Azure IoT extension for CLI by running this command:
     az extension add --name azure-iot

Register and configure the IoT device

In all of the following steps, XXXXX is the five-character suffix for the lab resources.

  1. Next, let's register a device in the IoT Hub identity registry:
     az iot hub device-identity create --device-id IoTDevice1 --hub-name iothub-XXXXX

    Note: There is a trick to finding this. Yes, you can go looking in the Azure web interface, but we can also just hit the Tab key after --hub-name (don't forget the space after name) and the CLI will finish the command for us.

  2. We've got to get the connection string for the device application, before we can connect the device to the Hub. Remember the Tab trick here:
     az iot hub device-identity show-connection-string --hub-name iothub-XXXXX --device-id IoTDevice1 --output table
  3. Copy the connection string to your clipboard and paste it into a text document. We'll need it in a bit.
  4. Now we can add a couple of tags to the IoT device twin:
     az iot hub device-twin update --device-id {device_id} --hub-name iothub-XXXXX --set tags='{"location":{"state":"TX","city":"Austin"}}'

Create an IoT Device Management Configuration

We're going to back out of the shell for a bit, and perform these next steps in the Azure Portal. Remember that XXXXX is the five-character suffix for the lab resources.

  1. Navigate to the IoT Hub provisioned for this lab.
  2. In the Resource menu, click on IoT device configuration.
  3. Click + Add Device Configuration to create the configuration with the following settings:
    • Name and Label:
      • Name: This is descriptive, so name it anything. It has to be lowercase and can only use these special characters: '-+%_*.
      • Labels: You can specify a key/tag pair for this configuration, but it is not required.
    • Twin Settings:
      • Device Twin Property: properties.desired.settings
      • Device Twin Property Content: { "gatelocked": false, "gateclosed": false }
    • Metrics:
      • Metric Name: nowReporting
      • Metric Criteria: SELECT deviceId FROM devices WHERE properties.reported.settings.status = 'Success'
    • Target Devices:
      • Priority: 10
      • Target Condition: tags.location.city = 'Austin'

Click Review + create and then Create to create the deployment.

Download and Configure the Node.js Application

Let's head back into Cloud Shell for this next part.

  1. Download the sample Node.js application by cloning the Git repository for this course:

    git clone https://github.com/linuxacademy/content-AZ-220.git
  2. Change to the directory for the Device Twin lab:

    cd content-AZ-220/samples/DeviceTwins/
  3. Now we can install the Node dependencies for the sample application:

    npm install
  4. Modify test_device_twins.js in vi or nano, replacing <device-id> on line 6 with the device connection string copied in Objective 1 (the bit that we put into a text file).

Connection String

Run the Node.js Application to Apply Desired Properties

The sample node application acts as a simulated device. It reads the desired properties from the device twin and "sets" the properties as reported. This is how we use device twins to synchronize desired properties (from the back-end application) with the reported properties (from the Iot Devices).

To run the application, type the following in Cloud Shell:

node test_device_twins.js

There will be output regarding the progress of the application. Once the application has reported successful changes, exit by pressing CTRL+C.

Verify That the Reported Properties Were Applied

Verify that the desired properties are now reported properties in the device twin:

  1. Click on IoT devices in the Resource menu, then click on the device created in the first objective.
  2. Click on Device Twin to view the twin. Verify that the reported properties now reside within the twin.

Device Reported Properties!

Look at the Metric

Let's have one more peek at the metric. Close this view, and then click IoT device management in the Resource menu. Over in the System Metrics column, we'll see 1 Targeted and 1 Applied. Click on that, then the Metrics section on the next page. There's a dropdown that will appear. Select nowReporting, then click View. We'll see our IoTDevice1 show up below.

Conclusion

We were able to successfully configure automatic device management, and use device twins in Azure. Congratulations! You have completed this hands-on lab!