Home Automation: DIY with Huxon

Leonardo Cavagnis
16 min readSep 12, 2022

How to create a smart home with Huxon platform and STM32 ecosystem

“Home is where the TECH is”

Home automation (or Smart home) is the automatic control of electronic devices in a home such as heating, lighting, and other systems.
Smart building is the concept of a smart home applied to domestic and business buildings.

Smart home. Image by author.

How much effort is required to create a home automation system?
A lot!
You need to take into account so many aspects such as electronic control units, software, mechanic parts, cabling, and more.

There is a platform that greatly simplifies the development of software and the managing of the electronic control units while optimizing performance and it is called Huxon.

This platform allows users to easily develop, optimize and deploy sensor-based real-time algorithms in a network of distributed physical sensors.
You just have to instruct the platform on how your infrastructure is composed and what logic you want to implement. Huxon will automatically compile and deploy the algorithm on the electronic control units of your system.

Huxon features. Image from Huxelerate.

To show the platform functionalities, I will realize a domotics system for a two-room apartment to monitor and manage the heating and the alarm system.
Using Huxon, I will acquire and process measurements, coming from sensors distributed in the different rooms, to create specific control logic (e.g., turning off the heating system of a room if no person is present in the room). The data produced by the platform will be displayed on a simple web page for the remote monitoring of the smart home system.

The physical infrastructure

The apartment is distributed over one level and is composed of two rooms, a bathroom, and an entrance hall. The sensors of the domotics system are positioned on the windows of the two rooms and the entrance door.

The system features are:

  • Detecting tampering on windows and door, thanks to the accelerometer sensors.
  • Detecting the presence of people inside the rooms, thanks to the microphone sensors.
  • Evaluating the climatic conditions of the home, thanks to the temperature and humidity sensor.
Apartment map. Image by author.

The infrastructure is composed of 4 control units:

  • ST NUCLEO-H723ZG with IKS02A1 expansion kit
    installed on the living room window
    Sensors available: accelerometer, gyroscope, magnetometer, and microphone
  • ST NUCLEO-H743ZI with IKS02A1 expansion kit
    installed on the bedroom window
    Sensors available: accelerometer, gyroscope, magnetometer, and microphone
  • ST NUCLEO-H723ZG with IKS01A2 expansion kit
    installed on the entrance door
    Sensors available: accelerometer, gyroscope, magnetometer, barometer, temperature, and humidity
  • Raspberry Pi 3 Model B
    positioned in the living room

The boards are connected via Ethernet cables in a Local Area Network (LAN). The system also needs a router/modem to access Internet.

ST Nucleo boards and Raspberry Pi. Image by author.

NUCLEO-H723ZG and NUCLEO-H743ZI are evaluation boards produced by STMicroelectronics and equipped with a powerful microcontroller (STM32H7) and Ethernet connectivity.

Raspberry Pi is a single-board computer provided with numerous ports including HDMI, USB, Wi-Fi, and Ethernet.

Huxon platform

Huxon homepage. Image by author.

Huxon is a cloud service that builds on public cloud infrastructure such as Microsoft Azure, AWS, etc.
In this project, the platform interfaces to Microsoft Azure IoT to create and handle all the IoT resources.

Therefore, the first step is to obtain the Azure credentials to allow the communication with the Microsoft service: go to the “Organization Settings” section and follow the instructions on the page.

Organization Settings. Image by author.

To create a project, go to the “Projects” section and click on the “Create new project” button.
A project requires the following information:

  • Project Name: Home automation
  • Project Type: Smart building
  • Azure IoT Central details
    Each project leverages a specific Azure component called IoT Central to publish sensor data.
    It is a cloud service to connect and manage IoT devices:
    * Application Url: is the name of the IoT Central Application.
    * API token: is the access token to manage the resources of the application.
    To create an API token, go to the section “Permissions->API Tokens” of your IoT Central application.
API tokens section of IoT Central. Image by author.
Create Huxon sensor project. Image by author.

After clicking on the “Create” button, Huxon will start building all the necessary resources on your Azure platform. When the process is over, the project homepage will be displayed.

Project homepage. Image by author.

Project workflow consists of 4 steps:

  1. Infrastructure setup: specify the physical infrastructure of the system.
  2. Algorithm development: develop the algorithms to execute.
  3. Virtual sensor creation: define the system from a logical point of view.
  4. Virtual sensor deployment: deploy the logic on the physical infrastructure.

1. Infrastructure Setup

Each control unit of the infrastructure is called node.
You can define two types of physical nodes:

  • Sensor node: board equipped with sensors that runs an RTOS.
  • Local node: edge node that handles connection from sensor nodes.
    Each sensor node can’t connect directly to the Internet and need a local node (the parent) to do that.

There is a third category called Cloud node: a virtual machine deployed inside the Azure cloud. It is not used in this project.

As described before, the infrastructure consists of 4 nodes:

  • 3 sensor nodes
    * livingroom-sensorboard (NUCLEO-H723ZG with IKS02A1)
    * bedroom-sensorboard (NUCLEO-H743ZI with IKS02A1)
    * entrance-sensorboard (NUCLEO-H723ZG with IKS01A2)
  • 1 local node
    * rpi-localnode (Raspberry Pi 3): the “parent” of all sensor nodes.

Local node creation and configuration
Before creating the sensors, you first need to create the local “parent” node.
Click on the “New local node” button on the “Infrastructure setup” page and insert the following information:

New local node: rpi-localnode. Image by author.
  • Device name and Device ID: rpi-localnode
  • Local Node Type: Raspberry Pi 3 Model
  • Hostname: It is the IP address assigned to the Raspberry Pi inside your local network.

After creating the local node, follow the instructions you find on the rpi-localnode page to correctly configure the board.

Local node setup instructions. Image by author.

Sensor node creation and configuration
For each sensor node, click on the “New sensor node” button and insert the following information:

New sensor node: livingroom-sensorboard. Image by author.
  • Device name and Device ID: sensor board name (e.g., livingroom-sensorboard).
  • MAC Address: automatically generated by the platform.
  • Sensor Board type: select the board type in use (e.g., “Nucleo STM32H723 with IKS02A1” for the livingroom-sensorboard).
  • Parent Local Node: select the parent local node (rpi-local node).

When creation is completed, follow the instructions you find on the sensorboard page to install the firmware on the board.

Sensor node setup instructions. Image by author.

These procedures should be performed only at the first configuration. After that, it will be up to the platform to automatically install algorithms on the boards during the deployment phase.

If all the steps have been carried out correctly, the status and connectivity of each node will change from “waiting first connection” and “offline” to “ready” and “online”.

Status and connectivity of node. Image by author.
Infrastructure overview. Image by author.

2. Algorithm development

The algorithms contain the “brain” of your application.
An algorithm does not depend on the physical infrastructure of the system, but only on the availability or not of the physical sensors. This means that an algorithm is only interested in knowing which sensors are involved in the computation.

In this experiment, there are 4 algorithms to develop:

  • Climatic monitoring: measuring the temperature and the humidity of the home.
  • Open window detection: estimating the status of the two windows (open or close) thanks to the accelerometer measurements. The acceleration along the axis perpendicular to the window is measured to evaluate whether the window has been opened or closed.
  • Persons in room detection: evaluating the presence of people inside the two rooms. The algorithm is based on the “variance” measuring of the microphone which can be interpreted as the intensity of the noise. If the noise is above a certain threshold, it is most likely that there are people in the room.
  • Tampering detection: estimating if a tamper occurred on the windows or on the entrance door. The algorithm is based on the measurement of the three-axis accelerations. A tamper condition is triggered if the sum of the absolute values of the 3 accelerations is above a certain threshold.

Algorithms are developed using the Huxon Language (proprietary language based on C/C++) and Visual Studio Code IDE.
The platform provides a development container with all the required software and documentation to write and simulate algorithms locally.
The language is based on two main components: channel and processing element. An Huxon algorithm is a set of processing elements connected by channels.
The processing element is a code function, while a channel is a link used to pass data between processing elements.

Code development: Climatic monitoring
The climatic monitoring algorithm calculates the average temperature and humidity of the home every 60 sensor measurements. Results are available every 1 minute as the sensor output data rate is 1Hz.

The algorithm is divided into 4 steps:

  • Sensor configuration and creation: define which sensor is in use and how it is configured (HTS221 is the temperature and humidity sensor mounted on the IKS01A2 expansion board).
HUX_DECLARE_SENSOR_CONFIGURATION
(humtemp_cfg, hux::sensors::STMicroelectronics::HTS221,
.odr = hux::sensors::STMicroelectronics::HTS221::configs::odr_1);
HUX_DECLARE_SENSOR
(my_humtemp, hux::sensors::STMicroelectronics::HTS221,
sim_dataset, humtemp_cfg);
  • Measurements buffer: temperature and humidity data are read from the sensor and stored in two buffers of length 60 called channels.
HUX_DECLARE_CHANNEL(temperature_buf, buffer<60>,
my_humtemp.get_temperature());
HUX_DECLARE_CHANNEL(humidity_buf, buffer<60>,
my_humtemp.get_humidity());
HUX_DECLARE_CHANNEL
(humiditytemp_buf_time_ch,
zip_latest,
temperature_buf,
humidity_buf,
my_humtemp.get_timestamp());
  • Averages computation: the average temperature and humidity are calculated.
typedef struct {
float temp;
float hum;
hux::uint64_t timestamp;
} humiditytemp_timestamp_t;
HUX_DECLARE_PROCESSING
(humiditytemp_avg_node, humiditytemp_buf_time_ch, {
humiditytemp_timestamp_t result;

auto &temp_buffer = hux::get<0>(hux_input);
auto &pres_buffer = hux::get<1>(hux_input);
hux::uint64_t timestamp = hux::get<2>(hux_input);
size_t buffer_size = temp_buffer.size();
float sense_sum = 0.0f;
for(int i = 0; i < buffer_size; i++) {
sense_sum += temp_buffer[i];
}
result.temp = sense_sum / buffer_size;
buffer_size = pres_buffer.size();
sense_sum = 0.0f; for(int i = 0; i < buffer_size; i++) {
sense_sum += pres_buffer[i];
}
result.hum = sense_sum / buffer_size;
result.timestamp = timestamp;
return result;
});
  • Declaring of algorithm output: results are packaged to be sent to the Azure platform.
HUX_DECLARE_CHANNEL
(humiditytemp_avg_ch, merge, humiditytemp_avg_node);
HUX_DECLARE_PROCESSING
(climaticmonitor_output_node, humiditytemp_avg_ch, {
HUX_DECLARE_OUTPUT_VALUE
(temperature_average, Float, "temperature", hux_input.temp);
HUX_DECLARE_OUTPUT_VALUE
(humidity_average, Float, "humidity", hux_input.hum);
HUX_DECLARE_OUTPUT_VALUE
(timestamp, Long, "timestamp", hux_input.timestamp);
HUX_DECLARE_OUTPUT_VALUE
(climaticmonitor_obj,
Object,
"temperaturehumidity",
temperature_average,
humidity_average,
timestamp);
return climaticmonitor_obj;
})
HUX_REGISTER_OUTPUT(climaticmonitor_output_node);

Below, an example of algorithm output:

{
“temperaturehumidity”:{
“temperature”:20.5,
“humidity”:45.0,
“timestamp”:1646435958250
}
}
Climatic monitoring algorithm — flowchart. Image by author.

Algorithm upload
When the algorithm is ready, go to the “Algorithm development” section and click on the “Upload new algorithm” button.

Algorithm upload. Image by author.

Attach the algorithm package, insert the name and description and click on the “Submit” button.

3. Virtual sensor creation

A virtual sensor is a “virtual” processing unit that implements an algorithm.
An algorithm can involve multiple physical sensors, and a physical sensor can be shared across multiple algorithms.
This indicates that a virtual sensor is a logical representation of a set of one or more physical sensors.

Since there are 4 algorithms, you need to create 4 virtual sensors:

  • climaticmonitoring-vsens
    Physical sensors involved: Temperature and humidity sensor of entrance-sensorboard
  • openwindowdetection-vsens
    Physical sensors involved: Accelerometer sensors of livingroom-sensorboard and bedroom-sensorboard
  • personroomdetection-vsens
    Physical sensors involved: Microphone sensors of livingroom-sensorboard and bedroom-sensorboard
  • tamperingdetection-vsens
    Physical sensors involved: Accelerometer sensors of all sensor boards.

To create a virtual sensor, go to the “Virtual Sensors creation” section and click on the “New virtual sensor” button:

  1. Insert a Virtual Sensor name (climaticmonitoring-vsens) and select the algorithm to implement (ClimaticMonitoringAlgo).
  2. Select the physical sensors to use (HTS221 temperature and humidity sensor of entrance-sensorboard).
  3. Click on the “Create” button.
Virtual sensor creation: Definition. Image by author.
Virtual sensor creation: Sensors selection. Image by author.
Virtual sensor creation: Create. Image by author.

This page allows users to visualize the system overview from both physical and logical points of view.

System overview: physical. Image by author.
System overview: logical. Image by author.

4. Virtual sensors deployment

The “Virtual Sensors Deployment” is the stage in which the platform automatically builds and installs the algorithms (i.e., the virtual sensors) on the physical boards of the infrastructure.
The only thing to worry about is choosing the virtual sensors to deploy.
To do this, click on the “New deployment” button on the “Virtual Sensors Deployment” page and select the virtual sensors to use.

New deployment. Image by author.

The deployment procedure goes through multiple stages and takes some minutes to complete. In this phase, the platform optimizes the algorithms and automatically updates the software of all physical nodes.
No user intervention is required during this process, you can close the platform and come back when the process is finished.

Deployment in progress. Image by author.
Deployment finished. Image by author.

Once the procedure has been completed, the deployment status turns “ready” and virtual sensors start to send data to your Azure IoT Central platform.

Huxon automatically estimates resources needed on each node and implements a partitioning that takes into account latency requirements, communication channels, and node interconnections. This feature can be useful when dealing with complex infrastructure and/or time-critical applications.
By clicking on the “Workload distribution” button, you can see how the platform automatically distributes the workload (e.g., the algorithm “partitions”) on the infrastructure.

Workload distribution of all virtual sensors. Image by author.

As you can observe from the graph, a virtual sensor can be partitioned over multiple physical sensors. This allows you to realize a distributed and cooperative algorithm without worrying about it.

In this project, 2 different deployments are defined:

  1. Heating management deployment
    It involves the virtual sensors: climaticmonitoring-vsens, openwindowdetection-vsens, and personroomdetection-vsens.
    The scope of this deployment is to provide useful information to the home heating system to implement energy-saving strategies (e.g., if there is no one in the room and/or the window is open, turn off the heating system of the room).
  2. Alarm management deployment
    It involves the virtual sensor: tamperdetection-vsens.
    The scope is to inform the user about door and window tampering to prevent undesired home intrusions.

Deployment hooks
With the “New deployment” button, a manual deployment process immediately starts.
However, if you want to invoke a deployment launch outside the platform you need to use a “Deployment hook”.

Deployment hooks are useful when you want to enable/disable some algorithms on your system according to specific conditions, for instance: enabling only the alarm system when you are not at home.

For this purpose, it is possible to create 4 hooks:

  • Enable only Heating Management
  • Enable only Alarm management
  • Enable Heating and Alarm management together
    All virtual sensors are involved (climaticmonitoring-vsens, openwindowdetection-vsens, personroomdetection-vsens and tamperdetection-vsens).
  • Disable all
    No virtual sensors are involved: it is defined as Empty deployment.

To create a deployment hook, go to the “Virtual Sensors Deployment” section and click on the “New Deployment Hook” button.

New Deployment Hook. Image by author.

Select the virtual sensors you want to include and click on the “Register new deployment hook” button. The platform generates a “link” to click to start the deployment.

Deployment Hooks section. Image by author.

In this way, you can re-configure dynamically the home automation system only by calling the specified link.

Let’s get in action!

When a deployment is finished, virtual sensors are up and start to transmit data. To verify that a virtual sensor is working correctly: open your Azure IoT Central application and go to the “Devices” section.
Here, you find all the virtual sensors created in the Huxon platform.

Devices section of Azure IoT Central application. Image by author.

Click on the virtual sensor included in the active deployment and go to the “Raw data” section: here are listed the real-time messages coming from the physical boards. The message format is what you defined in the algorithm of the virtual sensor.

Raw data section of climaticmonitoring-vsens. Image by author.

The remote monitoring

To remotely control the home automation system, you can build a webpage composed of a dashboard with live information (climatic condition, windows status, etc.) and some buttons to perform operations such as: enabling/disabling heating and alarm management.

Azure Event Hub
To transmit sensor data from the Azure platform to the webpage, you can use the Azure Event Hub. It is an event ingestion service that receives and stores the data coming from the devices in a unified stream. It is a queue between who produces the data (e.g., the virtual sensors) and who consumes the data (e.g., the webpage).

Azure Event Hub dataflow. Image by author.

After creating the Event Hub on the Azure portal (here, you can find the instructions), you have to configure the Data Export of your IoT Central application to forward data into the Event Hub:

  1. Open the “Data Export” section.
  2. Click on the “+ New Export” button.
  3. Insert a name (e.g., “To Event Hub”) and leave the other fields as default values.
  4. In the “Destinations” part, click on “create new one” and insert information as in the figure. To communicate with an Event Hub you need the Connection string (here, the guide to obtain it).
Azure IoT Central: Data export section. Image by author.
Azure IoT Central: Data export creation. Image by author.

Web server
To display data on a web browser, the sensor data coming from the Event Hub have to be received and processed by a web server. That, in turn, forwards the data to the webpage through a channel called web socket.

Web server, Web socket, and Web client. Image by author.

Web server and web socket are developed using JavaScript language and Node.js: a run-time environment to execute JavaScript code outside the browser. It is widely used in server-side applications.

Below, are the steps to build communication between a web server and Azure:

  • Configure the web server to connect to Azure Event Hub
const { EventHubConsumerClient, 
latestEventPosition,
earliestEventPosition } = require("@azure/event-hubs");
// event hub configuration
const eventHubEventPosition = latestEventPosition;
// websocket configuration
const websocketPort = 8889;
// event hub connection string
const connectionString = "Endpoint=sb://...";
// name of the default consumer group
const consumerGroup = "$Default";
  • Create the web socket to send event to the web client
// create web socket server to send event to web client
const WebSocketServer = require('ws').Server;
var webSocketServer = new WebSocketServer({ port: websocketPort });
// create a consumer client for the event hub
const consumerClient = new EventHubConsumerClient(consumerGroup,
connectionString,
eventHubName);
  • Retrieve data from the Event Hub and forward it to the web socket
// subscribe to the events and specify event handler.
const subscription = consumerClient.subscribe({
processEvents: async (events, context) => {
if (events.length === 0) {
console.log(`No events received within wait time`);
return;
}
for (const event of events) {
console.log(`Received event: '${event.body}'`);
webSocketServer.clients.forEach(function each(client) {
client.send(JSON.stringify(event.body));
});
}

await context.updateCheckpoint(events[events.length - 1]);
},
processError: async (err, context) => {
console.log(`Error : ${err}`);
},
},
{ startPosition: eventHubEventPosition }
);

Webpage
Remote monitoring dashboard is developed using HTML language and the live data, coming from the web server, are manipulated using a client-side JavaScript script.

<html>
<head>
<script type=”text/javascript” src=”view.js”></script>

</head>

</html>

The view.js script is composed by:

  • Web socket initialization
// initialize websocket
let socket = new WebSocket(“ws://localhost:8889”);
// websocket connection
socket.onopen = function(e) {
console.log(“[open] Connection established”)
};
  • Incoming message handling.
    Each event is analyzed and parsed to identify which virtual sensor had generated the message and what information is contained in it.
socket.onmessage = function(event) {
handleMessage(JSON.parse(event.data));
};
function handleMessage(message) {
if (message.deviceId == "climaticmonitoring-vsens") {
document.getElementById('temp_id').innerHTML =
message.telemetry.temperaturehumidity.temperature;
[...]
}
if (message.deviceId == "tamperingdetection-vsens") {
[...]
}
if (message.deviceId == "personroomdetection-vsens") {
[...]
}
if (message.deviceId == "openwindowdetection-vsens") {
[...]
}
}

The dashboard is divided into 5 areas:

  • Settings: shows the deployment status and allows the user to activate/deactivate a specific deployment with buttons.
  • Home ambient monitor: shows information about temperature and humidity of the home (climaticmonitoring-vsens virtual sensor).
  • Living room and Bedroom: shows the window status and the occupancy status of the room (personroomdetection-vsens and openwindowdetection-vsens virtual sensor).
  • Alarm: shows the door and windows tampering information. (tamperingdetection-vsens virtual sensor).
Remote monitoring dashboard. Image by author.

…Already done?

In this article, you have seen how to easily create a smart home system by exploiting the potential of the Huxon platform in combination with Microsoft Azure IoT.

Huxon is a very powerful tool since allows you to dynamically reconfigure the behaviour of your infrastructure without physically acting on each node. Without this platform, you should have to write and update the software of each board manually whenever you want to change the infrastructure’s operation.
Another positive aspect is the automatic distribution of the calculation: the platform divides automatically the computation on the various boards to optimize and speed up the execution of each algorithm.

Huxon currently supports few STMicroelectronics and Raspberry PI boards and the infrastructure is based on Ethernet connection.
I hope that in the future this platform will expand the supported hardware with other development boards (Arduino, NXP, Microchip, etc.) and with boards equipped with Wireless connectivity.

For further details, I refer you to the official Huxon documentation.

Here, you can find the source code of all algorithms and the webpage described in this tutorial.

--

--

Leonardo Cavagnis

Passionate Embedded Software Engineer, IOT Enthusiast and Open source addicted. Proudly FW Dev @ Arduino