Skip to main content

[IoT Home Project] Part 8 - Connecting to Azure Function and to a virtual heat pump

In this post we will discover how to:
  • Push content from Azure Stream Analytics to Azure Service Bus
  • Write an Azure Function in Node.JS that fetch data from Azure Service Bus Topic and push it to Azure Table
  • Develop a ASP.NET Core application that plays the role of a heating system that start/stop the heating in a house
Story:
  • Use temperature data collected from sensors connected to Raspberry PI to start/shop a heating system from a house
Previous post: [IoT Home Project] Part 7 - Read/Write data to device twin
GitHub source code: https://github.com/vunvulear/IoTHomeProject 

Push content from Azure Stream Analytics to Azure Service Bus
This step is the most simple one. We just need to Add a new output to Stream Analytics and specify the Service Bus Topic where we want to push data. After this, we'll need to update the Stream Analytic query by adding:
SELECT 
    *
INTO 
    outputSensorDataTopic
FROM
    avgdata
, where 'outputSensorDataTopic' is the name of the output that we created a few seconds ago.

Remarks: Don't forget to create a subscription for the topic. I send all the information to topic (not only temperature), because I plan in the future to add filters to each subscription and root data based on this parameters.

Azure Function to push data from Service Bus Topic to Azure Table
Offtopic: This step is done artificially in our case, we could forward content directly to Azure Table from Stream Analytics. I wanted to do this because the main scope is to play with as many Azure Services as possible. Additional to this, inside Azure Function we could aggregate information from other sources to decide if we want to start/stop the heating system.

Now, we will create a Azure Table in our storage with two rows, that contain current temperature and desired temperature. We could also add another row that contain a flag that specify to the system to start/stop the heating system, but for now we will not add it.
The table should look like this:
From Azure Portal, in the moment when we want need to create the Function itself we shall specify that for Trigger we want to have Service Bus Topic. For output we'll specify Azure Tables. At this step you need to specify connection information for Service Bus and Azure Table. Once you done this, you'll be ready to write your first Azure Function in Node.JS
  module.exports = function (context, myQueueItem) {    
    context.bindings.outputtable = {
        "partitionkey": "system",
        "rowkey":"currenttemperature",
        "status": myqueueitem.avgtemp
     };
    
    context.log('Avg. temp: ', myQueueItem.avgtemp);
    context.done();
  };

Surprise! Even if the function is written as in the book, an error will pop-up. This happens because in this moment Azure Function allows us only to add new rows to an Azure Table. Updating existing one is not possible.
The good news is that there is a small hack that we can do. Nothing block us to install Azure Storage module from npm and use it directly inside our function. To do this, you'll need to access the Kudu portal of you Azure Function. The URL is https://[FunctionAppName]scm.azurewebsites.net/ and you'll authenticate with Azure credentials.
From there, go to 'Debug Console' and type 'npm install azure-storage'. Once you install this module you can make any calls to Azure Storage using Node.JS module.
process.env["AZURE_STORAGE_ACCOUNT"] = "vunvuleariotstorage";
process.env["AZURE_STORAGE_ACCESS_KEY"] = "@@@";
process.env["AZURE_STORAGE_CONNECTION_STRING "] = "@@@";


module.exports = function (context, myQueueItem) {
    var azure = require('azure-storage');
    var tableSvc = azure.createTableService();
    tableSvc.createTableIfNotExists('systemstatus', function (error, result, response) {
        if (!error) {
            var entityToUpdate = new Object();
            entityToUpdate.PartitionKey = "system";
            entityToUpdate.RowKey = "currenttemperature";
            entityToUpdate.Status = myQueueItem.avgtemp.toString();

            tableSvc.insertOrReplaceEntity('systemstatus', entityToUpdate, function (error, result, response) {
                if (!error) {
                    context.log('Avg. temp: ', myQueueItem.avgtemp);
                }
            });
        };
    });

    context.done();
};

I prefered to use process environments values to specify storage connection information. There is another way to do this, by specifying this data when you make the call to 'createTableService'. There is no error handling done, being a sample code.

ASP.NET Core that plays the role of heating system
There not to many things to say about it. It is a simple web application, that display minimum temperature, current temperature and heating system status.

Remember:

  • There is not yet full support for all Azure Storage actions from Azure Function
  • You can load any module in Azure Function using NPM
  • You can add or remove inputs and outputs for of a Stream Analytics as you wish

Comments

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(

Azure AD and AWS Cognito side-by-side

In the last few weeks, I was involved in multiple opportunities on Microsoft Azure and Amazon, where we had to analyse AWS Cognito, Azure AD and other solutions that are available on the market. I decided to consolidate in one post all features and differences that I identified for both of them that we should need to take into account. Take into account that Azure AD is an identity and access management services well integrated with Microsoft stack. In comparison, AWS Cognito is just a user sign-up, sign-in and access control and nothing more. The focus is not on the main features, is more on small things that can make a difference when you want to decide where we want to store and manage our users.  This information might be useful in the future when we need to decide where we want to keep and manage our users.  Feature Azure AD (B2C, B2C) AWS Cognito Access token lifetime Default 1h – the value is configurable 1h – cannot be modified

What to do when you hit the throughput limits of Azure Storage (Blobs)

In this post we will talk about how we can detect when we hit a throughput limit of Azure Storage and what we can do in that moment. Context If we take a look on Scalability Targets of Azure Storage ( https://azure.microsoft.com/en-us/documentation/articles/storage-scalability-targets/ ) we will observe that the limits are prety high. But, based on our business logic we can end up at this limits. If you create a system that is hitted by a high number of device, you can hit easily the total number of requests rate that can be done on a Storage Account. This limits on Azure is 20.000 IOPS (entities or messages per second) where (and this is very important) the size of the request is 1KB. Normally, if you make a load tests where 20.000 clients will hit different blobs storages from the same Azure Storage Account, this limits can be reached. How we can detect this problem? From client, we can detect that this limits was reached based on the HTTP error code that is returned by HTTP