Skip to main content

IoT Home Automation | Backend infrastructure

Even if in the previous post I said that I will write about the integration points with garage gates, I decided to go forward with the development of the web interface and gateway software. I went on this path because once I have this part implemented I can play with ESP8266 as much as I want to integrate with all the devices that I have around the house.



Web Interface (UI)
I decided to go with a simple design. I’m pretty sure that I will become more complex in the future, but for now I will keep things as simple as possible. The web interface is done using AngularJS 5 together with a REST API exposed using ASP.NET Core. For now the web interface expose 2 buttons that allows me to trigger actions (open/close gates). This web interface is hosted as a web application inside an App Services. The plans is to secure using Azure AD, but this is another story, another post, but for now there is no need to do this because there is real device in the backend (yet).

Communication
The communication between the web interface and the gateway that will be inside the house is done using Azure Service Bus Topic. This simple messaging system allows me to send/receive commands between these two parties in a consistence and cheap level.
If you ask yourself why I did not used Azure IoT Hub, it is that at least for now I don’t need such a system. When the system will become too complex to manage in this way, I’m pretty sure that Azure IoT Hub will be integrated inside the solution.
A nice feature of Azure Service Bus Topic that I like to use in this context is duplicate detection. I set this value to 30 seconds and allows me to drop messages in the situations when you send the same command multiple times from the UI.
If you didn’t used Azure Service Bus with .NET core you should know that now there is a dedicated nuGet package for it named ‘Microsoft.Azure.ServiceBus’. This allows you to communicate with Service Bus in a similar manner that you used to do in .NET 4.XX.
The command that is send over Service Bus is added inside the message body (serialized as JSON). I only add a tag as message property that tells me what kind of message it is.
Below you can find an example on how to send and consume messages from Azure Service Bus using .NET Core library.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Send message
string messageBody = JsonConvert.SerializeObject(gateTrigger);
Message message = new Message(Encoding.UTF8.GetBytes(messageBody));
message.UserProperties.Add("type","gate");
TopicClient topicClient = new TopicClient(ConnectionString, TopicName);
await topicClient.SendAsync(message);

// Register to a subscription
SubscriptionClient subscriptionClient = new SubscriptionClient(ConnectionString, TopicName, SubscriptionName);
var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
{
 MaxConcurrentCalls = 1,
 AutoComplete = false
};
subscriptionClient.RegisterMessageHandler(GatewayCallback, messageHandlerOptions);

// New message callback action
public static async Task GatewayCallback(Message message, CancellationToken cancellationToken)
{
 string messageType = message.UserProperties["type"].ToString() ;
 switch(messageType)
 {
  case "gate":
   GateTrigger gateTrigger = GateTrigger.GenerateFromJson(Encoding.UTF8.GetString(message.Body));
   cacheService.Add<GateTrigger>(gateTrigger.GateId, gateTrigger);
   break;
 }

 await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
}

Gateway
On gateway side, I’m using ASP.NET Core that would run on top of Raspberry PI. This system will expose a REST API that will be called the ESP8266 controllers to check if there are new actions available for them. For now, based on what HTTP code I return to ESP8266, the controller will be able to a specific action.
Each controller has a unique ID that needs to provided when he check if there is something new for him. Using this ID, the gateway can provide the right content for him. I might use the MAC in a future release, but for now a hard-coded ID is enough.
To be able to store data that is read from Service Bus Subscription until will be consumed by the controller I’m using in-memory caching. An important thing related to this is the time period for how long I’m keeping this data inside memory. Because all controllers should be online all the time I don't want to keep data for a too long period of time cached. If the data that resides inside in-memory caching it is not consumed in 10 seconds it is automatically removed (expires).

Additional to this, if there is already another command for the same controller, the old one it is replaced by the new command. Below you can find a simple example of how you can manage the REST API exposed by gateway.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
.
[HttpGet("{id}")]
public IActionResult Get(int id)
{
                GateTrigger trigger = cacheService.Get<GateTrigger>(id);
                if (trigger == null)
                {
                                return new StatusCodeResult(201);
                }
 
                return new OkResult();
}

For now, the code that is running at Gateway level to expose the REST API for the controller is dummy (see below), but it is a good starting point that would allow me to test the E2E system.

For testing and only testing purposes, the Gateway will run as a Web App also. This means that controllers will call directly a Azure endpoint.

Controller 
I’m new in this area, so I prefer to go with Arduino. At a specific time interval (every 1 second for example) the controller will check the Gateway REST API to see if there is something new for him. The HTTP code 200 means for him that there is nothing to do. 201 HTTP code means that it should trigger the gate door open and so on. At this initial phase I prefer to use HTTP codes and nothing more than this.

Next I plan to start the integration with gate doors.

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