Experiment #101 How to create an Azure Function App to record telemetry readings

In this post we’ll see how to create an Azure Function App to send the real-time telemetry readings of an IoT Device and record it as a block in Azure Blockchain Workbench using its REST API.

 

1. The Azure Function App Resource

We’ll use the messages that the IoT Device sends to an Azure Service Bus queue via Azure IoT Central.

When we create the Azure Function, we must choose the Azure Service Bus Queue Trigger template.

Each message acts as a trigger an runs the Azure Function that extracts the temperature value from the message.

This numeric value is finally sent to our Azure Blockchain Workbench application as a TemperatureCheck action.

 

 

2. The Code in C# .Net Core

Specify the NuGet package we need for the Authentication:

#r "Microsoft.IdentityModel.Clients.ActiveDirectory"

List the using references we’ll use later in the code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

Declare the main function using a Service Bus QueueItem as a trigger:

public static async void Run(string QueueItem, ILogger log)
{
    log.LogInformation($"C# ServiceBus queue trigger function processed message: {QueueItem}");
    if (QueueItem.Contains("temp"))
    {
        var telemetry = Serializer.DeserializeFromJson(QueueItem);
        log.LogInformation($"IoT Device Telemetry Reading: SUCCESSFULL");
        log.LogInformation($"IoT Device Telemetry Reading: TEMPERATURE = {telemetry.temp}");
        ApiTasks api = new ApiTasks();
        Action send = new Action(15, (int)telemetry.temp);
        string sendJson = Serializer.SerializeToJson(send);
        await api.PostContractActionAsync(12, sendJson);
    }
}

Define the tasks we need to call the API, GetToken and PostContractAction:

public class ApiTasks
{
    private static readonly string AUTHORITY_TENANT = "https://login.microsoftonline.com/xxx.xxx";
    private static readonly string WORKBENCH_API_URL = "https://xxx-xxx-api.azurewebsites.net";
    private static readonly string WORKBENCH_APP_ID = "xxx-xxx-xxx-xxx-xxx";
    private static readonly string CLIENT_APP_ID = "xxx-xxx-xxx-xxx-xxx";
    private static readonly string CLIENT_APP_KEY = "xxxxxxxxx";
    private static readonly HttpClient _httpClient;
    private static readonly AuthenticationContext _authenticationContext;
    private static readonly ClientCredential _clientCredential;
    static ApiTasks()
    {
        _httpClient = new HttpClient();
        _authenticationContext = new AuthenticationContext(AUTHORITY_TENANT);
        _clientCredential = new ClientCredential(CLIENT_APP_ID, CLIENT_APP_KEY);
    }
    private async Task GetTokenAsync()
    {
        var result = await _authenticationContext.AcquireTokenAsync(WORKBENCH_APP_ID, _clientCredential);
        var token = result.AccessToken;
        return token;
    }
    public async Task PostContractActionAsync(int contractId, string actionJson)
    {
        var token = await GetTokenAsync();
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        HttpContent content = new StringContent(actionJson, System.Text.Encoding.UTF8, "application/json");
        await _httpClient.PostAsync($"{WORKBENCH_API_URL}/api/v2/contracts/{contractId}/actions", content);
    }
}

Define the Blockchain Workbench API action and parameter formats:

public class Action
{
    public int workflowFunctionId { get; set; }
    public List workflowActionParameters { get; set; }
    public Action() { }
    public Action(int functionId)
    {
        workflowFunctionId = functionId;
        workflowActionParameters = new List();
    }
    public Action(int functionId, int temperature)
    {
        workflowFunctionId = functionId;
        workflowActionParameters = new List();
        workflowActionParameters.Add(new Workflowactionparameter(temperature));
    }
}
public class Workflowactionparameter
{
    public string name { get; set; }
    public int value { get; set; }
    public Workflowactionparameter() { }
    public Workflowactionparameter(int temperature)
    {
        name = "temperature";
        value = temperature;
    }
}

Create the IoT Device Telemetry class with all the sensor parameters:

public class Telemetry
{
    public float humidity { get; set; }
    public float temp { get; set; }
    public float pressure { get; set; }
    public float magnetometerX { get; set; }
    public float magnetometerY { get; set; }
    public float magnetometerZ { get; set; }
    public float accelerometerX { get; set; }
    public float accelerometerY { get; set; }
    public float accelerometerZ { get; set; }
    public float gyroscopeX { get; set; }
    public float gyroscopeY { get; set; }
    public float gyroscopeZ { get; set; }
    public string deviceState { get; set; }
}

Add a Serializer helper class to work with JSON format:

public class Serializer
{
    public static string SerializeToJson(T obj)
    {
        MemoryStream jsonMemoryStream = new MemoryStream();
        DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType());
        jsonSerializer.WriteObject(jsonMemoryStream, obj);
        jsonMemoryStream.Position = 0;
        StreamReader jsonStreamReader = new StreamReader(jsonMemoryStream);
        string json = jsonStreamReader.ReadToEnd();
        jsonMemoryStream.Close();
        return json;
    }
    public static T DeserializeFromJson(string json)
    {
        MemoryStream jsonMemoryStream = new MemoryStream(Encoding.UTF8.GetBytes(json));
        DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
        T obj = (T)jsonSerializer.ReadObject(jsonMemoryStream);
        jsonMemoryStream.Close();
        return obj;
    }
}

 

3. The Experiment #101 In Action 

Here we can see how a Blockchain Smart Contract is created from our Azure Blockchain Workbench application.

The donated organ transportation process starts and moves along manually until the chain flow goes to the IoT Device.

Then, the Azure Function App takes the control automatically and it begins adding TemperatureCheck blocks to the chain.

The IoT Device continues sending telemetry readings until the OrganArrived action is taken or when the organ reaches the Spoiled state.

 

 

Stay up to date!



1 comment

Leave a comment