Tuesday, 15 November 2016

Part 1–Create an Azure IoT Hub and Device

This is not AX but this was a nice experience. I worked through some labs to interact with Azure IoT Hub.

There is a lot of information out there on the web. So, I will focus on the the IoT Hub only here. On later dates, I may get into the other features of the IoT services in Azure.

Below are the steps to create a device in IoT Hub to get you started. After you have created your device, you can interact with the device in multiple ways.

Go to Azure and Create a new IoT Hub App.


Enter the required information.


Now you can Add Devices manually through the Azure Portal. Otherwise, you can use the SDK to add the device via code.


Now, I will show how to add the device via C#. Create a new Console project.

Add the reference via NuGet.


Search for Microsoft.Azure.Devices and Install it.



Below is the code to copy and paste. Make sure to change the connection string to point it to your IoT Hub.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Devices; using Microsoft.Azure.Devices.Common.Exceptions;

namespace CreateDeviceIdentity { class Program { static RegistryManager registryManager; static string connectionString = "HostName=DAXIOTHUB.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=xxxxxxxx"; static void Main(string[] args) { registryManager = RegistryManager.CreateFromConnectionString(connectionString); AddDeviceAsync().Wait(); Console.ReadLine(); } private async static Task AddDeviceAsync() { string deviceId = "myFirstDevice"; Device device; try { device = await registryManager.AddDeviceAsync(new Device(deviceId)); } catch (DeviceAlreadyExistsException) { device = await registryManager.GetDeviceAsync(deviceId); } Console.WriteLine("Generated device key: {0}", device.Authentication.SymmetricKey.PrimaryKey); } } }

Credit to Microsoft for the Labs. Lab doc I found was a little old but most of the steps worked.



No comments: