Frist steps with Azure IoT Hub

While ordering the new Raspberry Pi 3 Model B today, I just looked into the Azure IoT Hub, tried it out and wrote down what I accomplished till now.

Raspberry Pi 3 B 2016

If you are interested how I made my first steps with the Azure IoT, while implementing a device registration into ASP.net, just read on.

Basically I followed the getting started with the IoT Hub guide from Dominic Betts.

Create a new Azure IoT Hub

First you log on to the Azure Portal and click new. Next hit “Internet of Things” and then “Azure IoT Hub“. Provide a name for your hub, select the pricing tier, a resource group or create a new one, your subscription and at last the location your hub should be hosted in.

Create an Azure IoT hub

It takes about 5min to create your hub, time we can use to create our ASP.net MVC project.

ASP.net MVC Project

Open Visual Studio and create a new project, next select web and ASP.net Web Application.

Create an ASP site to comunicate with Azure IoT hub

For the simplicity hit “Empty” and get rid of the authentication.

Hint: If you don’t want to go over all steps by yourself, check out my GitHub repo and grab the complete solution.

Open the NuGet package manager and search for the “Microsoft.Azure.Devices” reference, select your project and hit install.

Add Azure IoT references in VS

Next add two folders to your solution. First add a folder called “Service“, then add a new class (I named it MyDevice here) to that folder and add the code below.

using Microsoft.Azure.Devices;
using Microsoft.Azure.Devices.Common.Exceptions;
namespace FirstStepsWithAzureIoTHub.Service
{
public class MyDevice
{
private static Device device;
private static RegistryManager regManager;
private const string IOTHUBSTRING = "yourConnectionString";
}
}
view raw MyDevice hosted with ❤ by GitHub

On the image below you can see how you can retrieve your connection string, copy it from your portal and replace the IOTHUBSTRING with your connection string.
Azure IoT hub connection string
At this point VS 2015 normally recognized that you’re trying to build a website and recommends to add a few packages to your project (e.g. Bootstrap). If not, you have to add at least a View folder, within this folder create another folder called like your controller (in my example a folder called Home), add an Index.cshtml file. Click right on the created index file and hit “Set As Start Page“.
namespace FirstStepsWithAzureIoTHub.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}

Register a device

Next we want to add the code to register a device with the Azure IoT Hub. In our MyDevice class we add the following static method:

public async static Task AddDeviceAsync(string deviceId) {
regManager = RegistryManager.CreateFromConnectionString(IOTHUBSTRING);
try
{
device = await regManager.AddDeviceAsync(new Device(deviceId));
}
catch (DeviceAlreadyExistsException)
{
device = await regManager.GetDeviceAsync(deviceId);
}
}
view raw AddDeviceAsync hosted with ❤ by GitHub

Next we have to make a few changes to our view (index.cshtml).
@{
ViewBag.Title = "Index";
}
<hr />
@using (Html.BeginForm("AddDevice", "Home",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-2">Add device</label>
<div class="col-md-10">
<input class="form-control" id="id" name="id" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Add Device" class="btn btn-success" />
</div>
</div>
</div>
}

Then our HomeController,  at first we want to add two new using statements.
using System.Threading.Tasks;
using FirstStepsWithAzureIoTHub.Service;

Then a new method to handle the form post and the call of our AddDevice method through the Azure IoT Hub.
public async Task AddDevice(string id) {
await MyDevice.AddDeviceAsync(id);
return RedirectToAction("Index", "Home");
}
view raw AddDevice hosted with ❤ by GitHub

List your devices and keys

To use our devices later on, we need to know the security keys first. So let’s add a method to retrieve the keys and show them on our view. Like before we add a new method to the MyDevice class.

public async static Task<IEnumerable> GetDevicesAsync(int deviceCount = 8) {
regManager = RegistryManager.CreateFromConnectionString(IOTHUBSTRING);
return await regManager.GetDevicesAsync(deviceCount);
}
view raw GetDevicesAsync hosted with ❤ by GitHub

We also want to pass the list of devices to our view, so let’s edit the Index method of our HomeController.
public async Task Index() {
ViewBag.data = await MyDevice.GetDevicesAsync();
return View();
}
view raw Index hosted with ❤ by GitHub

And also we’re adding a few new lines to our view.
<hr />
<h2>Device list</h2>
<ul>
@{
foreach (var device in ViewBag.data)
{
<li>
@device.Id -
@device.Authentication.SymmetricKey.PrimaryKey -
<a href="@Url.Action("DeleteDevice", new { id = device.Id })">
<span class="glyphicon glyphicon-trash"></span>
</a>
</li>
}
}
</ul>

Next the MyDevice class.
public async static Task DeleteDeviceAsync(string deviceId) {
regManager = RegistryManager.CreateFromConnectionString(IOTHUBSTRING);
device = await regManager.GetDeviceAsync(deviceId);
if (device != null)
await regManager.RemoveDeviceAsync(deviceId);
}

Now your site should look like in the screenshot below. You can add new devices by defining an id and hit “Add Device“. You also get a list of all your registered devices and you could delete them by hitting the little “trash” icon behind the keys.
Azure IoT hub control with ASP net
If you navigate back to the portal and open your IoT Hub pane you should also see your added devices on the overview page, like shown below.
IoT devices Azure hub

Demo Code

  • GitHub

 

You may also like...