Connect your Azure Sphere device to Azure IoT Hub – using Visual Studio 2019

I recently ordered an Azure Sphere MT3620 Starter Kit from Avnet to try out Azure Sphere first-hand. In this article I will go over how to connect such a device to Azure IoT Hub. The steps assume that this is your first time setting up your device. So some steps are to be done once (the first time).

Azure Sphere MT3620 Starter Kit

Steps Overview

  1. Test connecting your Azure Sphere development kit to the PC
  2. Install the Azure Sphere SDK
  3. Claim your device: add your device to your Azure Sphere tenant.  This can only be done ONCE in the lifetime of the device!
  4. Configure networking
  5. Check and download any updates
  6. Download the sample code from Github
  7. Connect your device by USB and verify that network connectivity is available
  8. Enable development on your device
  9. Configure the cloud services: create an IoT Hub and a Device Provisioning Service (DPS) and link them together
  10. Download the tenant authentication CA certificate
  11. Upload the tenant CA certificate to DPS and generate a verification code
  12. Verify the tenant CA certificate
  13. Use the validation certificate to add your device to an enrollment group
  14. Add the IoT Hub configuration settings to your Visual Studio project in the app_manifest.json file
  15. Build and run the code and watch for device-to-cloud messages coming to your IoT Hub

Detailed Steps

Prerequisites on Windows: a PC running Windows 10 Anniversary Update or later

Install the Azure Sphere SDK

  1. Attach your Azure Sphere dev kit (e.g. the Avnet Starter Kit) to your PC.  The drivers should be installed automatically.  Then, to verify the Dev Kit installed correctly, open Device Manager and look for 3 COM ports (e.g. USB Serial Port (COM10), USB Serial Port (COM11) and USB Serial Port (COM8)).  See this Troubleshooting page if there any connection errors.
  2. Install the Azure Sphere SDK in order to use Visual Studio 2019 (Enterprise, Professional or Community edition) version 16.04 or later for Azure Sphere development.

Claim your device

An Azure Sphere Tenant provides a way to isolate your devices and allows you to manage them.  Hence, if your organization already has a tenant, you may want to ask to join the existing tenant rather than creating a new one.  And note that once a tenant is created it cannot be moved or deleted.
Important note: once a device is claimed into a tenant then it is PERMANENTLY associated with that Azure Sphere tenant.

  1. Connect your device to your PC
  2. Open the Azure Sphere Command Prompt from the Start Menu
  3. Sign in using a Microsoft Account.  To use Azure Sphere you need a Microsoft account.  Depending on how your Azure Sphere tenant is set up, you can use your Microsoft account as the user or you can ask your administrator to add you.
    azsphere login 
  4. For those who have never logged in to Azure Sphere before or have just installed the 19.10 SDK, they must add the –newuser parameter to the login command:
    azsphere login –newuser <email-address>
  5. Subsequently, once logged in:
    1. If you have one Azure Sphere Tenant (already created) it will be selected as default and you can proceed
    2. Otherwise, if no tenants have been created yet, you will need to create a new tenant
      azsphere tenant create --name <my-tenant>
      Now that the command is successful, you will something like the following message :
      Created a new Azure Sphere Tenant
      --> Tenant Name: new-tenant
      --> Tenant ID: 4c556667-8 …
      Selected Azure Sphere tenant 'new-tenant' as the default.
      You may now wish to claim the attached device into this tenant using 'azsphere device claim'.
      Command completed successfully in 00:00:39.2176539.
    3. If Azure Sphere was previously used with 19.09 SDK or earlier, then the tenant needs to be migrated
    4. If you have multiple tenants, you will need to select one.
    5. Claim your device:
      azsphere device claim
      Upon success, you will see:
      Claiming device.
      Successfully claimed device ID 'AF0A42 ... 7AF0' into tenant 'new-tenant' with ID '4c556667-8 ...'
      Command completed successfully in 00:00:03.4460543

Configure Networking

Now on to configure networking: after you claim your device you need to set up networking so that the device can receive updates from the Azure Sphere Security Service and so that the device can communicate with Azure services such as IoT Hub.

  1. Connect your device to your PC via the USB cable
  2. Open the Azure Sphere device prompt
  3. Register the device’s MAC address if needed.  The following command will display the device’s MAC address:
    azsphere device wifi show-status


Get MAC ID of device

  1. Join your device to the WiFi network by using the following command:
    Note: Azure Sphere supports WPA and WPA2 protocols only.
    azsphere device wifi add –ssid <WIFI SSID> --psk <network security key>
  2. Verify that the device connected to the wireless network by typing:
    azsphere device wifi show-status


Get the WIFI status of your device

Update the Sofware on the Avent device and Enable Application Development on it

  1. Update the software (OS or application) on the device.  The Azure Sphere device checks for updates at boot up time and at every 24-hour interval going forward.  If the device gets updated, the download and update process can take up to 20 minutes.  And the device wifi show-status command will show configuration unknown while the update is progressing.
    To check on the status of an update, you can use:
    azsphere device show-deployment-status
    Upon successful completion you will see:
    Your device is running Azure Sphere OS version 19.11.
    The Azure Sphere Security Service is targeting this device with Azure Sphere OS version 19.11.
    Your device has the expected version of the Azure Sphere OS: 19.11.
  2. The Azure Sphere Samples can be found on this Github repository.  Download or clone the repository and go to the AzureIoT folder. 
  3. Connect your device via USB cable.  And verify that wireless connectivity is available by using:
    azsphere device WIFI show-status
  4. Enable application development on your device:
    azsphere device enable-development


Azure Sphere Enable Development

Configure the cloud services:

  1. Configure the cloud services: create an IoT Hub and a Device Provisioning Service (DPS) and link them together
  2. Download the tenant authentication CA certificate
  3. Upload the tenant CA certificate to DPS and generate a verification code
  4. Verify the tenant CA certificate
  5. Use the validation certificate to add your device to an enrollment group
  6. Add the IoT Hub configuration settings to your Visual Studio project in the app_manifest.json file
    1. The Tenant ID for your Azure Sphere Device can be obtained from the following command.  Enter it into the DeviceAuthentication field in the app_manifest.json file.
      azsphere tenant show-selected
    2. The Scope ID for your DPS instance can be obtained from the Summary screen (top right section).  Paste it into the CmdArgs section of app_manifest.json
    3. The IoT Hub URL for your IoT Hub goes into the AllowedConnections field in the app_manfest.json file
  7. Build and run the code and watch for device-to-cloud messages coming to your IoT Hub

Lessons Learned

  • Development in the C language is not for the faint of heart. However, Visual Studio makes it easy to code using Intellisense and it provides full debug capability.
  • Update to the latest OS version ASAP. There were some issues where the board could not connect to the service before I upgraded to OS version 19.10
  • Once big issue, that occurred during development, was that the LPS22HH sensor was not found. However, after contacting Avnet through the element14 community, they promptly released a fix on Github.
  • Some of the Azure Sphere videos talk about configuring the IoT Hub settings by selecting the project in Visual Studio, selecting Overview and then choosing Connected Services, then clicking on IoT Hub. That never worked. After researching the issue, I found out that this method has been deprecated. In the new OS versions, the IoT Hub settings are all done in the app_manifest.json file. 
  • As of OS version 19.10 Azure Sphere will now be built using a cross-platform build system called CMake.  CMake may be used to build high-level applications or to build real-time applications.  It may also be used for development from the command line.
  • Using CMake paves the way for using the Azure Sphere SDK on Linux and for using the Azure Sphere extension for Visual Studio Code.
  • There are many Azure Sphere sample apps.

An IoT solution using IoT Hub, Azure Stream Analytics and Power BI Desktop

Goal of the IoT Solution

Get the current temperature for Jeddah City and monitor it for anomalies (ups and downs) over a period of time (a few days).

Overview of the IoT Solution

The IOT solution gets the current weather data in Jeddah (from a weather web site) and sends it to Azure IOT Hub in Azure.  From the IOT Hub the data goes through Azure Stream Analytics (ASA).  ASA does some filtering on the data and then stores it in table storage in Azure.  Subsequently, I then read the data from the Power BI Desktop application and I plotted it on a chart.  Subsequently, using the plot,  I monitored the temperature data for anomalies or variances.

Details of the IoT Solution

Since the sensors for my TI micro-controller are yet to arrive, I developed a solution that simulates those temperature sensors by reading current temperature data from http://www.openweathermap.org.  The weather data is in the JSON format and it is consumed using a REST API.  In the future, instead of using a weather site to get temperature data, I can easily get real weather data from temperature sensors on a micro controller or a computer on a board.  For example, sensors attached to a Rasperry PI or sensors attached to an Arduino board can easily provide this data.

Reading the Weather Data from OpenWeatherMap web site
// Get temperature from OPenWeatherMap
JObject jsonData = JObject.Parse(new System.Net.WebClient().DownloadString(string.Format("http://api.openweathermap.org/data/2.5/forecast/daily?q=Jeddah&type=accurate&mode=json&units=metric&cnt=3&appid=key")));

if (jsonData.SelectToken("cod").ToString() == "200")
{
todayTemperature = (double)jsonData.SelectToken("list[0].temp.day");
Console.WriteLine($"Temp: {todayTemperature.ToString()}"
);

A Windows’ console application gets this temperature data (from openweathermap.org) and sends this telemetry to an Azure IOT Hub.

The data is sent to Azure IoT Hub and picked up by Azure Stream Analytics

From the IOT Hub the data is picked up by an Azure Stream Analytics job.  This is basically a query (similar to SQL) that takes the data from IOT hub, validates it and places it in an Azure Storage table.

SELECT
DeviceId,
telemetryTime,
temperature as TemperatureReading
INTO
TemperatureTableStorage
from TempSensor
WHERE
DeviceId is not null
and EventProcessedUtcTime is not null
and telemetryTime is not null
Finally analysis – for anomalies – is done in Power Bi Desktop

Once the data is in an Azure Storage table, I performed cold-path analytics on it using PowerBI Desktop.  I used PowerBI Desktop to read the data directly from Azure storage.  I then used it to analyze the data and plot it in different ways.

The image below is a screenshot of a Stacked Column chart of (temperature readings against time).  It shows the variance in Jeddah weather (temperature) over the course of a day on 15 May 2016.

PowerBI Desktop showing temperature data plot
PowerBI Desktop showing temperature data plot