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.

 

 

Step by step

Idiwork has arrived and we invite you to join us!
Raspberry Pi4 – All of a sudden!
Experiment #101 How to set up an IoT device in Azure IoT Hub
Start your own video game with Unity3D and CreatorKits
Experiment #101 How To Create a Blockchain Workbench App
XR World: Minecraft Earth
Experiment #101 Architectural Diagram
Cyberpunk 2077 and The Future
An Introduction to neural networks
Microsoft Mixer, streaming your life !
Introduction to Azure Notebooks applying Cognitive Services with Jupyter
AR [T] Walk
Return of Age of Empires
Idiwork and Uno Platform partnership!!
The differences between Augemented Reality, Mixed Reality and Virtual Reality !
Experiment #102 How to Create an Azure Notebooks Project and Deploy a Summarization Service
Uno Platform Conference
YouTube Video: Creator Kits, learn how to create a RPG with Unity3D !! 🤖
Experiment #102 How to construct and train a Deep Neural Network using Keras and deploy the model as an Azure Web Service 🧠☁️
Uno Platform Conference Recap 😎
How to create a Uno Platform project in Visual Studio 💻🤓
What is a Neural Network? by Alberto Pinedo 🧠💻
Experiment #102 How to Deploy and Integrate Azure Cognitive Services: Computer Vision and Text Analytics 💻📑
Next stop: Madrid Games Week 👉🤖
Our Madrid Games Week experience ! 😎🤖
Experiment #102 How to use Microsoft Flow to send an email when an event occurs 📧📌
How to create your own controllers for Mixed Reality ToolKit 🎮🤓
Experiment #102 Architectural Diagram 📍
The magic of Hytale ⚔️
Start programming your own app in Uno Platform 📲👨‍💻
Avalonia, a big candidate to create cross-platform apps with XAML 😎📲
The value of Blockchain for business by Pablo Junco ⛓️🏢
Living in the night: Bloodlines 2 🧛🎮
Uno Platform Workshop Recap 💻📌
EasyRPC. Be proud of your APIs (First Part) 🤓🚀
Paralives, reimagine your virtual life 👾👩‍💻
Experiment #103 How to Modify the Project to Work with Face Cognitive Service and Servo Motor 👩‍💻📙
Experiment #103 How to Set Up the IoT Device Hardware: Peripherals and Electronics 🔈💡
We are going to be in the GDG DevFest in Málaga! 😎👾
EasyRPC. Be proud of your APIs (Second Part) 🤓🚀
Experiment #103 How to Build a 3D Printed Box to Pack and Run the IoT Project 🚀
MediEvil, remember the fear💀
Never forget the Fallen Order 🏹🎮
Experiment #103 Architectural Diagram 📍
Grace: The perfect DI IoC container [part 1] 💻🤓
Death Stranding: a story of death and connection ☠🏹
Experiment #204 How to assembly the 3D printed parts and servo motors of the robotic arm 🦾🤖
TemTem: a dream come true 🐹💥
Grace: The perfect DI IoC container [part 2] 💻🤓
Exploring the Outer Worlds 🎇⚔
Our review from Hololens 2 👓👷
Learn to code on your iPhone for FREE 📲🚀
New life, new horizons in Animal Crossing 🎮🐱
What’s WinUI? 💻🚀
Half Life Alyx ☠🧟‍♂
How to deploy a Censorship Resistant Website for FREE 🔓🌎
Superpower: The parser combinator library [Part 1] 💻🤓
UnoPlatform and WinUI, what to expect? 🚀📲
Happiness begins in Stardew Valley 🍎🐓
Science fiction in Assassin’s Creed 👽
The Cyber Attack Lifecycle 🕵‍♀💻
Superpower: The parser combinator library [Part 2] 💻🤓
Learn more about UnoPlatform! 😜📢
Create cybernetically enhanced web apps with SvelteJS 💻👇
Six Fun Drag & Drop 🧩 Programming Languages To Learn How To Code! 💻
Riot and Hytale unite! 👾😉
A new home called EVE Online 👽👇
Rejoice with UnoPlatform! May 2020 📲👇
UnoPlatform arrives to macOS 💻👈
Your new empire in Civilization VI 🎮🏹
Play Station 5 is near!
Build and defend your city, this is Manor Lords
Customization, landscape generation and more in Hytale🧝🏻‍♀️🧝🏼
Welcome, MAUI! 💣📲
Zombies will be zombies (TLOU2) 👽🧟‍♂
Rejoice with UnoPlatform! August 2020 📲👇
Final Fantasy Crystal Chronicles is back🧝🏻‍♀️⚔️
Bolt is now free in Unity3D 🎮
Feel the Flutter! 🌐
Microsoft buys ZeniMax Media (including Bethesda!)
Intel and Microsoft team up to empower AI on Edge
Linux and WSL2 - Part 1 Linux and WSL2 – Part 1: How do you run Windows applications on Linux? Or vice versa.
Guide how to Run Windows applications on Linux Linux and WSL2 – Part 2: How do you run Windows applications on Linux? Or vice versa.
Domain-driven design Domain-Driven Design: the elephant in the room
azure object anchors Azure Object Anchors: the third tool
Experiment #205 Step by step 1 Experiment #205 Applied Artificial Intelligence, the real one 🤖📹
AI Assembling the system Experiment #205 Applied Artificial Intelligence – Assembling the system ⚙️🦾
Redit Conquer all the APIs Refit – Conquer all the APIs
Experiment #205 Applied AI: the Information analysis Experiment #205 Applied Artificial Intelligence – Analysis of the information
Brand Presence step by step 1 Blog Experiment #206 Brand Presence
Experiment #206 Brand Presence - The analysis Experiment #206 Brand Presence – The analysis

Stay up to date!



1 comment

Leave a comment