An Azure IoT Hub can store just about any type of data from a Device.

There is support for:

  • Sending Device to Cloud messages.
  • Invoking direct methods on a device
  • Uploading files from a device
  • Managing Device Identities
  • Scheduling Jobs on single for multiple devices

The following is the List of of built-in endpoints

Custom Endpoints can also be created.

IoT Hub currently supports the following Azure services as additional endpoints:

  • Azure Storage containers
  • Event Hubs
  • Service Bus Queues
  • Service Bus Topics

Architecture

If we look through the documentation on the Azure Architecture Center, we can see a list of Architectural Styles.

If we were to design an IoT Solution, we would want to follow Best Practices. We can do this by using the Azure Architectural Style of Event Driven Architecture. Event-driven architectures are central to IoT solutions.

Merging Event Driven Architecture with Microservices can be used to separate the IoT Business Services.
These services include:

  • Provisioning
  • Management
  • Software Updating
  • Security
  • Logging and Notifications
  • Analytics

Creating our services

To create these services, we start by selecting our Compute Options.

App Services

The use of Azure Functions is becoming commonplace. They are an excellent replacement for API Applications. And they can be published to Azure Api Management.

We are able to create a Serverless API, or use Durable Functions that allow us to create workflows and maintain state in a serverless environment.

Logic Apps provide us with the capability of building automated scalable workflows.

Data Store

Having a single data store is usually not the best approach. Instead, it’s often better to store different types of data in different data stores, each focused towards a specific workload or usage pattern. These stores include Key/value stores, Document databases, Graph databases, Column-family databases, Data Analytics, Search Engine databases, Time Series databases, Object storage, and Shared files.

This may hold true for other Architectural Styles. In our Event-driven Architecture, it is ideal to store all data related to IoT Devices in the IoT Hub. This data includes results from all events within the Logic Apps, Function Apps, and Durable Functions.


Which brings us back to our topic… Considering Software as an IoT Device

Since Azure IoT supports the TransportType.Http1 protocol, we can use the Microsoft.Azure.Devices.ClientLibrary to send Event data to our IoT Hub from any type of software. We also have the capability of receiving configuration data from the IoT Hub.

The following is the source code for our SendEvent Function App.

SendEvent Function App

#region Information

//  
//  MIT License
//  
//  Copyright (c) 2018  Howard Edidin
//  
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//  
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//  
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//  SOFTWARE.

#endregion

#region

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Services.Client;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
using TransportType = Microsoft.Azure.Devices.Client.TransportType;

#endregion

namespace IoTHubClient
{
    public static class SendEvent
    {
        private static readonly string IotHubUri = ConfigurationManager.AppSettings["hubEndpoint"];

        [FunctionName("SendEventToHub")]
        public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "device/{id}/{key:guid}")]
            HttpRequestMessage req, string id, Guid key, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");


            // Get request body
            dynamic data = await req.Content.ReadAsAsync<object>();

            var deviceId = id;
            var deviceKey = key.ToString();

            if (string.IsNullOrEmpty(deviceKey) || string.IsNullOrEmpty(deviceId))
                return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a deviceid and deviceKey in the Url");

            var telemetry = new Dictionary<Guid, object>();


            foreach (var item in data.telemetryData)
            {
                var telemetryData = new TelemetryData
                {
                    MetricId = item.metricId,
                    MetricValue = item.metricValue,
                    MericDateTime = item.metricDateTime,
                    MetricValueType = item.metricValueType
                };

                telemetry.Add(Guid.NewGuid(), telemetryData);
            }


            var deviceData = new DeviceData
            {
                DeviceId = deviceId,
                DeviceName = data.deviceName,
                DeviceVersion = data.deviceVersion,
                DeviceOperation = data.deviceOperation,
                DeviceType = data.deviceType,
                DeviceStatus = data.deviceStatus,
                DeviceLocation = data.deviceLocation,
                SubscriptionId = data.subcriptionId,
                ResourceGroup = data.resourceGroup,
                EffectiveDateTime = new DateTimeOffset(DateTime.Now),
                TelemetryData = telemetry
            };


            var json = JsonConvert.SerializeObject(deviceData);

            var message = new Message(Encoding.ASCII.GetBytes(json));


            try
            {
                var client = DeviceClient.Create(IotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey),
                    TransportType.Http1);

                await client.SendEventAsync(message);

                return req.CreateResponse(HttpStatusCode.OK);
            }
            catch (DataServiceClientException e)
            {
                var resp = new HttpResponseMessage
                {
                    StatusCode = (HttpStatusCode) e.StatusCode,
                    Content = new StringContent(e.Message)
                };
                return resp;
            }
        }
    }


    public class DeviceData
    {
        public string DeviceId { get; set; }

        public string DeviceName { get; set; }

        public string DeviceVersion { get; set; }

        public string DeviceType { get; set; }

        public string DeviceOperation { get; set; }

        public string DeviceStatus { get; set; }

        public DeviceLocation DeviceLocation { get; set; }

        public string AzureRegion { get; set; }

        public string ResourceGroup { get; set; }

        public string SubscriptionId { get; set; }

        public DateTimeOffset EffectiveDateTime { get; set; }

        public Dictionary<Guid, object> TelemetryData { get; set; }
    }

    public class TelemetryData
    {
        public string MetricId { get; set; }

        public string MetricValueType { get; set; }

        public string MetricValue { get; set; }

        public DateTime MericDateTime { get; set; }
    }

    public enum DeviceLocation
    {
        Cloud,
        Container,
        OnPremise
    }
}

Software Device Properties

The following values are required in the Url Path

Route = "device/{id}/{key:guid}")

Name Description
id Device Id (String)
key Device Key (Guid)

The following are the properties to be sent in the Post Body
Name Description
deviceName Device Name
deviceVersion Device version number
deviceType Type of Device
deviceOperation Operation name or type
deviceStatus Default: Active
deviceLocation Cloud
Container
OnPremise
subscriptionId Azure Subscription Id
resourceGroup Azure Resource group
azureRegion Azure Region
telemetryData Array
telemetryData.metricId Array item id
telemetryData.metricValueType Array item valueType
telemetryData.metricValue Array item value
telemetryData.metricTimeStamp Array item TimeStamp

Summary

  • We can easily add the capability of sending messages and events to our Function and Logic Apps.
  • Optionally, we can send the data to an Event Grid.
  • We have a single data store for all our IoT events.
  • We can identify performance issues within our services.
  • Having a single data store makes it easier to perform Analytics.
  • We can use a Azure Function App to Send Device to Cloud Messages. In this case our Function App will be also be taking the role of a Device.