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

How to check in AngularJS if a service was register or not

There are cases when you need to check in a service or a controller was register in AngularJS.
For example a valid use case is when you have the same implementation running on multiple application. In this case, you may want to intercept the HTTP provider and add a custom step there. This step don’t needs to run on all the application, only in the one where the service exist and register.
A solution for this case would be to have a flag in the configuration that specify this. In the core you would have an IF that would check the value of this flag.
Another solution is to check if a specific service was register in AngularJS or not. If the service was register that you would execute your own logic.
To check if a service was register or not in AngularJS container you need to call the ‘has’ method of ‘inhector’. It will return TRUE if the service was register.
if ($injector.has('httpInterceptorService')) { $httpProvider.interceptors.push('httpInterceptorService&#…

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.51EF 6.0.2VS2013
It seems that there …

Fundamental Books of a Software Engineer (version 2018)

More then six years ago I wrote a blog post about fundamental books that any software engineer (developer) should read. Now it is an excellent time to update this list with new entries.

There are 5 different categories of books, that represent the recommended path. For example, you start with Coding books, after that, you read books about Programming, Design and so on.
There are some books about C++ that I recommend not because you shall know C++, only because the concepts that you can learn from it.

Coding

Writing solid codeCode completeProgramming Pearls, more programming pearls(recommended)[NEW] Introduction to Algorithms

Programming

Refactoring (M. Fowler)Pragmatic ProgrammerClean code[NEW] Software Engineering: A Practitioner's Approach[NEW] The Mythical Man-Month[NEW] The Art of Computer Programming

Design

Applying UML and Patterns (GRASP patterns)C++ coding standards (Sutter, Alexandrescu)The C++ programming language (Stroustrup, Part IV)Object-oriented programming (Peter Coad)P…