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(

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine: threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration: TeamCity .NET 4.51 EF 6.0.2 VS2013 It see

Navigating Cloud Strategy after Azure Central US Region Outage

 Looking back, July 19, 2024, was challenging for customers using Microsoft Azure or Windows machines. Two major outages affected customers using CrowdStrike Falcon or Microsoft Azure computation resources in the Central US. These two outages affected many people and put many businesses on pause for a few hours or even days. The overlap of these two issues was a nightmare for travellers. In addition to blue screens in the airport terminals, they could not get additional information from the airport website, airline personnel, or the support line because they were affected by the outage in the Central US region or the CrowdStrike outage.   But what happened in reality? A faulty CrowdStrike update affected Windows computers globally, from airports and healthcare to small businesses, affecting over 8.5m computers. Even if the Falson Sensor software defect was identified and a fix deployed shortly after, the recovery took longer. In parallel with CrowdStrike, Microsoft provided a too