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).

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.

// Send message
string messageBody = JsonConvert.SerializeObject(gateTrigger);
Message message = new Message(Encoding.UTF8.GetBytes(messageBody));
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() ;
  case "gate":
   GateTrigger gateTrigger = GateTrigger.GenerateFromJson(Encoding.UTF8.GetString(message.Body));
   cacheService.Add<GateTrigger>(gateTrigger.GateId, gateTrigger);

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

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.

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.

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.


Popular posts from this blog

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 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 …

Entity Framework (EF) TransactionScope vs Database.BeginTransaction

In today blog post we will talk a little about a new feature that is available on EF6+ related to Transactions.
Until now, when we had to use transaction we used ‘TransactionScope’. It works great and I would say that is something that is now in our blood.
using (var scope = new TransactionScope(TransactionScopeOption.Required)) { using (SqlConnection conn = new SqlConnection("...")) { conn.Open(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = conn; sqlCommand.CommandText = ... sqlCommand.ExecuteNonQuery(); ... } scope.Complete(); } Starting with EF6.0 we have a new way to work with transactions. The new approach is based on Database.BeginTransaction(), Database.Rollback(), Database.Commit(). Yes, no more TransactionScope.
In the followi…

GET call of REST API that contains '/'-slash character in the value of a parameter

Let’s assume that we have the following scenario: I have a public HTTP endpoint and I need to post some content using GET command. One of the parameters contains special characters like “\” and “/”. If the endpoint is an ApiController than you may have problems if you encode the parameter using the http encoder.
using (var httpClient = new HttpClient()) { httpClient.BaseAddress = baseUrl; Task<HttpResponseMessage> response = httpClient.GetAsync(string.Format("api/foo/{0}", "qwert/qwerqwer"))); response.Wait(); response.Result.EnsureSuccessStatusCode(); } One possible solution would be to encode the query parameter using UrlTokenEncode method of HttpServerUtility class and GetBytes method ofUTF8. In this way you would get the array of bytes of the parameter and encode them as a url token.
The following code show to you how you could write the encode and decode methods.