Building Connected Things with Windows 10 IoT and Microsoft Azure
Lab 7: Sending Cloud-to-Device (C2D) Messages
Table of Contents
- Table of Contents
- Add Newtonsoft Json Library
- Create a Command Message Class
- Add A Method to Receive Messages from the Cloud
- Run the Application Again and Turn the LED On and Off
In this lab you will extend your website by adding the ability to control the ThingLabs Thingy™ remotely. The website will send messages to the Thingy via Azure.
Add Newtonsoft Json Library
In a previous lab, you built the ThingLabs Thingy™ for Windows 10 IoT Core and deployed a website to display data from the Thingy. In this lab, you will send messages from the Microsoft Azure IoT Hub to the Thingy. In the same way that you added a NuGet package for the Azure IoT SDK, you need to add a package for working with JSON data.
- Open the Thingy project.
- Click on the Project menu and select Manage NuGet Packages.
- Use the search field to search for Newtonsoft.Json.
- Click on the Install button to install the package.
Create a Command Message Class
It is easiest to transition the JSON message you receive from the cloud into a class so that you can avoid string parsing.
- Create a new class called CommandMessage.
- Add a single property named LedStatus with a type of int.
Add A Method to Receive Messages from the Cloud
Now you will add a method to the end of the StartupTask class that will look for messages from the deviceClient that you created in a previous lab.
- Locate the end of the StartupTask and add a method called ReceiveCloudToDeviceMessagesAsync.
- Locate the end of the Run(IBackgroundTaskInstance taskInstance) method and add a call to the ReceiveCloudToDeviceMessagesAsync method.
Run the Application Again and Turn the LED On and Off
Now you can browse to the website you deployed in lab 05 and use the buttons to turn the blue LED on and off.
- Browse to your website and enter the name of your device as the device id.
- Press the LED ON button and see your blue led turn on.
- Press the LED OFF button and see your blue led turn off.
Congratulations! In this lab, you updated the Thingy application to receive messages from a website through Azure IoT Hub. The core concepts you’ve learned are:
- Using the Azure IoT SDK to connect to Azure and send cloud-to-device (C2D) messages.
- Handling the times when the device didn’t receive an messages from the cloud