Skip to content

Workshop demonstrating how to get started with the Azure IoT Raspberry Pi 2 kits

Notifications You must be signed in to change notification settings

cambridge-msp/Azure-IoT-Workshop

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 

Repository files navigation

Introduction to Azure IoT with Windows 10 IoT Core

This workshop is based off of a talk given by Microsoft at the Build 2016 conference. It has been updated to work with some newer tooling, and uses the Raspberry Pi 2 rather than 3.

Overview

Azure IoT Hub is a service that enables secure and reliable bi-directional communications between your application back end and billions of IoT devices. It allows the application back end to receive telemetry at scale from your devices, route that data to a stream event processor, and also to send cloud-to-device commands to specific devices.

Windows 10 IoT Core is a version of Windows 10 that is optimized for smaller devices with or without a display including the Raspberry Pi, Arrow DragonBoard, MinnowBoard MAX and more. Windows 10 IoT Core utilizes the rich, extensible Universal Windows Platform (UWP) API for building great solutions.

In this workshop you will use a Raspberry Pi device with Windows 10 IoT Core and a FEZ HAT sensor hat. Using a Windows 10 Universal Application, the sensors get the raw data and format it into a JSON string. That string is then shuttled off to the Azure IoT Hub, where it gathers the data and is then displayed in an Azure website. Finally, you'll see how to send cloud-to-device messages to your device to command it.

Objectives

In this workshop, you'll see how to:

  • Create a Universal app that reads sensor information from a Raspberry Pi running Windows 10 IoT Core
  • Upload those readings to an Azure IoT Hub
  • Display the the IoT Hub information in a website
  • Command your device based on IoT Hub Cloud-To-Device messages

Prerequisites

The following is required to complete this module:

Exercises

This module includes the following exercises:

  1. Connecting and configuring your device
  2. Sending telemetry data to Azure IoT Hub
  3. Consuming the IoT Hub data from a Website
  4. Sending commands to your devices

Estimated time to complete this module: 90 minutes

Note: When you first start Visual Studio, you must select one of the predefined settings collections. Each predefined collection is designed to match a particular development style and determines window layouts, editor behavior, IntelliSense code snippets, and dialog box options. The procedures in this module describe the actions necessary to accomplish a given task in Visual Studio when using the General Development Settings collection. If you choose a different settings collection for your development environment, there may be differences in the steps that you should take into account.

Exercise 1: Connecting and configuring your device

The IoT Starter Kits should contain a Raspberry Pi with Windows 10 IoT Core Image, Ethernet cable, Ethernet to USB adapter, and FEZ HAT.

In this exercise, you'll verify the setup of your Raspberry Pi and set up the GHI FEZ HAT devices.

Task 1 - Setting up your Device and Verifying the Connection

In this task, you'll setup your devices by following these steps:

  1. Plug the GHI FEZ HAT into the Raspberry Pi.

    The FEZ hat connected to the Raspberry Pi device

    The FEZ hat connected to the Raspberry Pi device

    Windows 10 IoT Core with FEZ hat hardware setup

    Windows 10 IoT Core with FEZ hat hardware setup

  2. The Raspberry Pi 2 does not have a WiFi adapter, so must use the Ethernet connection into your PC and share the PC's internet connection instead. (If you are using a Raspberry Pi 3 which has its own WiFi adapter, follow the instructions here for setting up your device instead and move on to Exercise 2). To allow sharing the internet connection:

    1. Right-click the Windows "Start" Menu and choose "Network Connections"
    2. Right-click on the network your PC is connected to, for exmample, WiFi. Select "Properties".
    3. In the dialog that pops up, select the "Sharing" tab and ensure the first tick box ("Allow other network users to connect through this computer's Internet connection") is checked.
    4. Click "OK". Now on the Network Connections window your PC's internet connection network should have the word "Shared" next to it.

Exercise 2: Sending telemetry data to Azure IoT Hub

In this exercise, you'll create an Azure IoT Hub to provide reliable and secure bi-directional communications between your IoT device and a Universal app.

Task 1 - Creating an IoT Hub

In this task, you'll create an IoT Hub for communicating with your device.

  1. Go to the Azure portal, by navigating to http://portal.azure.com

  2. Create a new IoT Hub. To do this, click New Resource in the jumpbar, then click Internet of Things, then click IoT Hub.

  3. Configure the IoT hub with the desired information:

    • Enter a Name for the hub e.g. iot-workshop (note that this should be a globally unique name of your own choosing),
    • Select a Pricing and scale tier (F1 Free tier is enough),
    • Create a new resource group, or select and existing one. For more information, see Using resource groups to manage your Azure resources.
    • Select the Region South UK for where the service will be located (if you are not in the UK choose wherever the nearest option is).

    New IoT Hub Settings

    New IoT Hub Settings

  4. It can take a few minutes for the IoT hub to be created. Wait for this to complete.

Task 2 - Registering your device

You must register your device in order to be able to send and receive information from the Azure IoT Hub. You can do this via the IoT Core Dashboard.

  1. Open the IoT Core Dashboard app and click the "Connect to Azure" tab. Log in to Azure if necessary.

  2. Fill out the fields.

    • Choose the Azure IoT Hub instance you created above.
    • Add a device and give it a memorable name - this will be the name associated with the Raspberry Pi you have plugged in.
    • For "Device to Provision" select the Raspberry Pi you have plugged in. You may need to install additional software to the Raspberry Pi; let it do so and choose the default options. It may take a couple of minutes and the Raspberry Pi may restart, but you should get a message saying that the device is ready to be provisioned.
    • Click "Provision" and wait for it to complete.

Task 3 - Sending telemetry data to the Azure IoT hub

Now that the device is configured, you'll see how to make an application read the values of the FEZ HAT sensors, and then send those values to an Azure IoT Hub.

This task uses an existing Universal application that will be deployed to your Raspberry Pi device and use FEZ HAT sensors.

  1. Open in Visual Studio the IoTWorkshop.sln solution located at Source\Ex2\Begin folder.

  2. In Solution Explorer, right-click the IoTWorkshop project, and then click Manage NuGet Packages.

  3. In the NuGet Package Manager window, click Browse and search for Microsoft.Azure.Devices.Client.PCL. Install it. This downloads, installs, and adds a reference to the Microsoft Azure IoT Service SDK NuGet package. (NuGet is a package management system, much like NPM for NodeJS).

  4. Add the following using (this is equivalent to import in Java) statements at the top of the MainPage.xaml.cs file:

    using Microsoft.Azure.Devices.Client;
  5. Add the following field to the MainPage class, replace the placeholder value with the device connection string you've created in the previous task (note that the curly braces { } are NOT part of the connection string and should be removed when you paste in your connection string):

    private DeviceClient deviceClient = DeviceClient.CreateFromConnectionString("{device connection string}");
  6. Add the following method to the MainPage class to create and send messages to the IoT hub. Resolve the missing using statements (if you are unsure what the async and await keywords mean, read the docs here):

    public async void SendMessage(string message)
    {
    	 // Send message to an IoT Hub using IoT Hub SDK
    	 try
    	 {
    		  var content = new Message(Encoding.UTF8.GetBytes(message));
    		  await deviceClient.SendEventAsync(content);
    
    		  Debug.WriteLine("Message Sent: {0}", message, null);
    	 }
    	 catch (Exception e)
    	 {
    		  Debug.WriteLine("Exception when sending message:" + e.Message);
    	 }
    }
  7. Add the following code to the Timer_Tick method to send a message with the temperature and another with the light level:

    // send data to IoT Hub
    var jsonMessage = string.Format("{{ displayname:null, location:\"USA\", organization:\"Fabrikam\", guid: \"41c2e437-6c3d-48d0-8e12-81eab2aa5013\", timecreated: \"{0}\", measurename: \"Temperature\", unitofmeasure: \"C\", value:{1}}}",
    	 DateTime.UtcNow.ToString("o"),
    	 temp);
    
    this.SendMessage(jsonMessage);
    
    jsonMessage = string.Format("{{ displayname:null, location:\"USA\", organization:\"Fabrikam\", guid: \"41c2e437-6c3d-48d0-8e12-81eab2aa5013\", timecreated: \"{0}\", measurename: \"Light\", unitofmeasure: \"L\", value:{1}}}",
    	 DateTime.UtcNow.ToString("o"),
    	 light);
    
    this.SendMessage(jsonMessage);
    1. In order to deploy your app to the IoT device, select the ARM architecture in the Solution Platforms dropdown.

      ARM Solution Platform

      ARM Solution Platform

    2. Next, click the Device dropdown and select Remote Machine.

      Run in remote machine

      Run in remote machine

    3. In the Remote Connections dialog, click your device name within the Auto Detected list and then click Select. Not all devices can be auto detected, if you don't see it, enter the IP address using the Manual Configuration. After entering the device name/IP, select Universal (Unencrypted Protocol) Authentication Mode, then click Select.

      Remote Connections dialog

      Remote Connections dialog

  8. Press F5 to run and deploy the app to the device.

    The information being sent can be monitored using the Device Explorer application. Run the application and go to the Data tab and select the name of the device you want to monitor, then click Monitor.

    Monitoring messages sent

    Monitoring messages sent

    Note: If you navigate back to your IoT Hub blade in the Azure Portal, it may take a couple minutes before the message count is updated to reflect the device activity under Usage.

Exercise 3: Consuming the IoT Hub data from a Website

In this exercise, you'll deploy a website to Azure, and then you'll enable WebSockets to allow communication with the IoT hub, and display live telemetry data using charts.

Task 1 - Create a Consumer Group for the Web site

In order to allow several consumer applications to read data from the IoT Hub independently, a Consumer Group must be configured for each one. If all of the consumer applications (the Device Explorer, Stream Analytics / Power BI, the Web site you'll configure in the next section) read the data from the default consumer group, only one application will retain the lease and the others will be disconnected.

In this task you'll create two Consumer Groups for the website to avoid conflicts with other consumers.

Important Note: In order to use the EventProcessorHost class, for Build 2016, you must create an Azure Storage account to enable the EventProcessorHost to record checkpoint information. Please follow the instructions in About Azure Storage to create a new one. Make a note of the storage account connection string because you'll need it later.

  1. Open the Azure Portal (https://portal.azure.com/), and select the IoT Hub you created.

  2. From the settings blade, click Messaging.

  3. At the bottom of the Messaging blade, type the name of each new Consumer Group and then Save:

  • website
  • local (used when debugging)
  1. Take note of the Event Hub-compatible name and Event Hub-compatible endpoint values in the Messaging blade

    Adding website consumer groups

    Adding website consumer groups

  2. Go to the Source\Ex3\Begin folder, and open the Web Site project (IoTWorkshopWebSite.sln) in Visual Studio.

  3. Edit the Web.config file and add the corresponding values for the following keys:

    • Microsoft.ServiceBus.EventHubDevices: Event hub-compatible name you copied in the previous step.
    • Microsoft.ServiceBus.ConnectionStringDevices: Event hub-compatible connection string which is composed by the Event hub-compatible endpoint and the iothubowner Shared access policy Primary Key.
    • Microsoft.Storage.ConnectionString: insert the storage account name and storage account primary key corresponding to your Storage Account to complete the endpoint.
  4. Did you create the storage account? :)

Task 2 - Deploying to Azure Web Site

In this task, you'll deploy the website to an Azure Web Site.

  1. In Visual Studio, right-click the project name and select Publish.

  2. Select Microsoft Azure App Service. (Note that the name has been changed to Web App. Please select that.)

    Selecting Publish Target

    Selecting Publish target

  3. Click New and use the following configuration.

    • Web App name: Pick something unique, e.g. iotmodule.
    • App Service plan: Select an App Service plan in the same region used for the IoT Hub or create a new one using that region.
    • Region: Pick same region as you used for the IoT Hub.
    • Database server: No database.
  4. Click Create. After some time the website will be created in Azure.

    Creating a New Web App

    Creating a new Web App on Microsoft Azure

  5. Click Publish.

    Note: You might need to install the WebDeploy extension if you are having an error stating that the Web deployment task failed. You can find WebDeploy here.

Task 3 - Enabling WebSockets in the Azure Web Site

After you deploy the site, it's required that you enable Web sockets. To do this, perform the following steps:

  1. Browse to https://portal.azure.com and select your iotmodule Web app.

  2. Click Settings.

  3. Click Applicattion settings

  4. Then set Web sockets to On and click Save.

    Enabling Web Sockets in your website

    Enabling Web Sockets in your website

  5. Navigate to your recently deployed Web Application. You will see something like in the following screenshot. There will be 2 real-time graphs representing the values read from the temperature and light sensors.

    Note: Take into account that the Universal app must be running and sending information to the IoT Hub in order to see the graphics.

    Web Site Consuming the IoT Hub Data

    Web Site Consuming the IoT Hub data

    Note: At the bottom of the page you should see "Connected". If you see "ERROR undefined" you likely didn't enabled WebSockets for the Azure Web Site.

Exercise 4: Sending commands to your devices

Azure IoT Hub is a service that enables reliable and secure bi-directional communications between millions of IoT devices and an application back end. In this section you will see how to send cloud-to-device messages to your device to command it to change the color of one of the FEZ HAT leds, using the Device Explorer app as the back end.

In this exercise, you'll add the logic to process the messages received from your Raspberry Pi.

Task 1 - Processing IoT Hub received messages

In this task, you'll add logic to process the messages received from the IoT Hub.

  1. Open the Universal app you created before and add the following method to the MainPage.xaml.cs file. The ReceiveAsync method returns the received message at the time that it is received by the device. The call to CompleteAsync() notifies IoT Hub that the message has been successfully processed and that it can be safely removed from the device queue. If something happened that prevented the device app from completing the processing of the message, IoT Hub will deliver it again.

    public async Task<string> ReceiveMessage()
    {
    	try
    	{
    		var receivedMessage = await this.deviceClient.ReceiveAsync();
    
    		if (receivedMessage != null)
    		{
    			var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
    			this.deviceClient.CompleteAsync(receivedMessage);
    			return messageData;
    		}
    		else
    		{
    			return string.Empty;
    		}
    	}
    	catch (Exception e)
    	{
    		Debug.WriteLine("Exception when receiving message:" + e.Message);
    		return string.Empty;
    	}
    }
  2. Now you will add the logic to process the messages received, add a new timer to the MainPage class:

    private DispatcherTimer commandsTimer;
  3. Add the following method, which will be in charge of processing the commands. It reads the message received, and according to the text of the command, it set the value of the hat.D2.Color attribute to change the color of the FEZ HAT's LED D2. When the "OFF" command is received the TurnOff() method is called, which turns the LED off.

    private async void CommandsTimer_Tick(object sender, object e)
    {
    	string message = await ReceiveMessage();
    
    	if (message != string.Empty)
    	{
    		System.Diagnostics.Debug.WriteLine("Command Received: {0}", message);
    		switch (message.ToUpperInvariant())
    		{
    			case "RED":
    				hat.D2.Color = new FEZHAT.Color(255, 0, 0);
    				break;
    			case "GREEN":
    				hat.D2.Color = new FEZHAT.Color(0, 255, 0);
    				break;
    			case "BLUE":
    				hat.D2.Color = new FEZHAT.Color(0, 0, 255);
    				break;
    			case "OFF":
    				hat.D2.TurnOff();
    				break;
    			default:
    				System.Diagnostics.Debug.WriteLine("Unrecognized command: {0}", message);
    				break;
    		}
    	}
    }
  4. Lastly, add the following piece of code to the SetupHat method in order to initialize the timer used to poll for messages.

    //setup receive timer
    this.commandsTimer = new DispatcherTimer();
    this.commandsTimer.Interval = TimeSpan.FromSeconds(60);
    this.commandsTimer.Tick += this.CommandsTimer_Tick;
    this.commandsTimer.Start();

    Note: The recommended interval for HTTP/1 message polling is 25 minutes. For debugging and demonstration purposes a 1 minute polling interval is fine (you can use an even smaller interval for testing), but bear it in mind for production development. Check this article for guidance. When AMQP becomes available for the IoT Hub SDK using UWP apps a different approach can be taken for message processing, since AMQP supports server push when receiving cloud-to-device messages, and it enables immediate pushes of messages from IoT Hub to the device. The following article explains how to handle cloud-to-device messages using AMQP.

Task 2 - Processing IoT Hub received messages

  1. Deploy the app to the device and open the Device Explorer app.

  2. Once it's loaded (and configured to point to your IoT hub), go to the Messages To Device tab, check the Monitor Feedback Endpoint option and write your command, e.g. BLUE, in the Message field. Click Send.

    Sending cloud-to-device message

    Sending cloud-to-device message

  3. After a few seconds the message will be processed by the device and the LED will turn on in the color you selected. The feedback will also be reflected in the Device Explorer screen after a few seconds.

    Cloud-to-device message received

    Cloud-to-device message received


Summary

By completing this module, you should have:

  • Learned how to connect and configure a Raspberry Pi device with Windows 10 IoT Core.
  • Learned how to create an Azure IoT hub and configure a device app to connect to the hub.
  • Created a Windows Universal Platform app and deployed to a remote Windows IoT device that sends telemetry messages to Azure IoT Hub.
  • Programmed the input (buttons) and output (LEDs) of a GHI's FEZ HAT topping connected to the Raspberry Pi.
  • Read the temperature and light sensors and set the RGB LEDs colors from the FEZ HAT.
  • Configured and deployed an Azure Web site that consumes and displays the live data from the Azure IoT Hub.
  • Sent commands to your IoT devices from Azure IoT Hub.

Build attendees, please submit a quick evaluation for this lab:

About

Workshop demonstrating how to get started with the Azure IoT Raspberry Pi 2 kits

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published