Reader small image

You're reading from  Hands-On Embedded Programming with C++17

Product typeBook
Published inJan 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781788629300
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Maya Posch
Maya Posch
author image
Maya Posch

Maya Posch is a senior C++ developer with more than 15 years of experience. Discovering the joys of programming early on, and later the joys of electronics, she has always expressed a profound interest in technology, a passion that she gladly shares with others. Describing herself as a C developer who happens to like C++ and Ada, she likes to seek the limits of what can be done with the minimum of code and hardware to accomplish everything that is cool, new, and exciting. She also enjoys FPGA development, AI, and robotics research, in addition to creative writing, music, and drawing.
Read more about Maya Posch

Right arrow

Chapter 9. Example - Building Monitoring and Control

The monitoring of conditions within a building, including the temperature, humidity, and CO2 levels is becoming increasingly more common, with the goal being to adjust heating, cooling, and ventilation systems to keep the occupants of the building as comfortable as possible. In this chapter, such a system is explored and implemented. The following topics will be covered:

  • Creating complex firmware for the ESP8266
  • Integrating an MCU into an IP-based network
  • Adding CO2 and I2C-based sensors
  • Using GPIO and PWM to control relays and DC voltage-controlled fans
  • Connecting networked nodes using a central controller

Plants, rooms, and beyond


In Chapter 5, Example - Soil Humidity Monitor with Wi-Fi, we looked at developing firmware for the ESP8266 MCU to complement a soil humidity sensor and pump, to ensure that a connected plant would be provided with sufficient water from the water tank.

As we noted in that chapter, the firmware used is highly modular and has the highly flexible MQTT-based interface so that it can be used for a wide variety of modules. This chapter covers the system in which the firmware originated: Building Management and Control (BMaC), originally developed just to monitor rooms for their temperature, humidity, and CO2 levels, but later expanded to keep tabs on coffee machines and meeting room occupancy, and ultimately to control the air-conditioning throughout the building.

 

The BMaC project's current development status can be found at the author's GitHub account at https://github.com/MayaPosch/BMaC. The version we are covering here is as it exists at this point, with us covering...

Developmental history


The BMaC project started when sensors were to be added around an office building in order to measure temperature and other parameters, such as relative humidity. After deciding to use ESP8266 MCUs along with DHT22 temperature and humidity sensors, a simple prototype was put together, using a basic firmware written using the Sming framework.

It was found that DHT22 sensors were generally rather bulky and not very precise. The breakout boards used also had an improper resistor mounted on them, leading to the wrong temperature being reported. This sensor type also had the disadvantage of using its own one-wire protocol, instead of a standard interface method.

The DHT22 sensors got swapped out with BME280 MEMS sensors, which measure temperature, humidity, and also air pressure. A CO2 sensor was added as well, in the form of the MH-Z19. This required the firmware to support these additional sensors too. The sensor readings would be sent as MQTT messages, with a backend service...

Functional modules


Here is a list of modules in this firmware:

Firmware source


In this section, we look at the source code for the ESP8266 firmware as used with the BMaC system.

Core

The core of the firmware we already looked at in Chapter 5Example - Soil Humidity Monitor with Wi-Fi, including the entry point, the OtaCore class, and the BaseModule class, which provide all of the functionality needed to make individual modules initialize and to allow them to be enabled and disabled using the MQTT interface.

 

Modules

Of the firmware modules, we already looked at the plant module inChapter 5Example - Soil Humidity Monitor with Wi-Fi. Here we will look at the remaining modules, starting with the THP module:

#include "base_module.h"
class THPModule {
    public:
    static bool initialize();
    static bool start();
    static bool shutdown();
};
#include "thp_module.h"
#include "dht_module.h"
#include "bme280_module.h"
bool THPModule::initialize() {
    BaseModule::registerModule(MOD_IDX_TEMPERATURE_HUMIDITY, 
    THPModule::start, THPModule::shutdown);...

Command and control server


As alluded to earlier in this chapter, a so-called command and control (C&C) server is essentially a database containing information on individual nodes and their configuration, for use by the nodes themselves and administration tools like the one in the next section.

It also includes an HTTP server, for use with HTTP-based over-the-air (OTA) updates. Since the BMaC system is MQTT-based, this server is also written as an MQTT client:

#include "listener.h"  
#include <iostream> 
#include <string> 
 
using namespace std; 
 
#include <Poco/Util/IniFileConfiguration.h> 
#include <Poco/AutoPtr.h> 
#include <Poco/Net/HTTPServer.h> 
 
using namespace Poco::Util; 
using namespace Poco; 
using namespace Poco::Net; 
 
#include "httprequestfactory.h" 
  
int main(int argc, char* argv[]) { 
   cout << "Starting MQTT BMaC Command & Control server...\n"; 
    
   int rc; 
   mosqpp::lib_init(); 
    
   cout << "Initialised C+...

Administration tool


Using the APIs implemented by the C&C server, a GUI-based administration tool was created using the Qt5 framework and the Mosquitto MQTT client library was developed, allowing for the basic management of nodes. They were overlaid on top of a layout graphic of buildings.

While basically usable, it was found that a graphical tool was fairly complicated to develop. It was also limited to a single floor of a building, unless one were to have a really large map containing all of the floors with the nodes mapped onto this. This would have been quite clumsy, obviously.

In the source code provided with this chapter, the administration tool can be found as well, to serve as an example of how one could implement it. For the sake of brevity, the code for it has been omitted here.

 

Air-conditioning service


To control air-conditioning units, a service much like the C&C one was developed, using the same basic template. The interesting parts of its source are the following:

#include <string>
 #include <vector>

 using namespace std;

 #include <Poco/Data/Session.h>
 #include <Poco/Data/SQLite/Connector.h>

 #include <Poco/Net/HTTPClientSession.h>
 #include <Poco/Net/HTTPSClientSession.h>

 #include <Poco/Timer.h>

 using namespace Poco;
 using namespace Poco::Net;

 class Listener;


 struct NodeInfo {
    string uid;
    float posx;
    float posy;
    float current;    
    float target;
    bool ch0_state;
    UInt8 ch0_duty;
    bool ch0_valid;
    bool ch1_state;
    UInt8 ch1_duty;
    bool ch1_valid;
    bool ch2_state;
    UInt8 ch2_duty;
    bool ch2_valid;
    bool ch3_state;
    UInt8 ch3_duty;
    bool ch3_valid;
    UInt8 validate;
 };


 struct ValveInfo {
    string uid;
    UInt8 ch0_valve;
    UInt8 ch1_valve...

InfluxDB for recording sensor readings


Recording the sensor readings and later the statistics read from the coffee machines was a priority from the beginning. The ideal database for this kind of data is a time series database, of which Influx is a common one. The biggest problem with this database is that it does not support MQTT, only offering its HTTP and native interface.

To fix this, a simple MQTT-to-Influx HTTP line protocol bridge was written, again using the Mosquitto client library as well as the POCO framework's HTTP functionality:

#include "mth.h"

#include <iostream>

using namespace std;

#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/StringTokenizer.h>
#include <Poco/String.h>

using namespace Poco;


MtH::MtH(string clientId, string host, int port, string topics, string influxHost, 
                int influxPort, string influxDb, string influx_sec) : mosquittopp(clientId.c_str()) {
    this->topics  = topics...

Security aspects


During the development of this system it became soon obvious that security would be a paramount aspect of the system. For that reason we looked at adding transport layer security (TLS) encryption. This would use the integrated axTLS encryption library in the Sming framework together with AES certificates (host and client) to provide both verification that the host (servers) and clients (nodes) are who they say they are, but also provide a secure encrypted link.

In Chapter 5Example - Soil Humidity Monitor with Wi-Fi, we already looked at the handling of these client certificates and setting up of an encrypted MQTT connection. One detail which is not obvious from that were the troubles which we encountered while setting up this certificate system. As mentioned in Chapter 5Example - Soil Humidity Monitor with Wi-Fi, the ESP8266 does not have enough memory to allocate the default TLS handshake buffers and requires the use of the SSL fragment size extension on the side of...

Future developments


There are still many additions that can be made to this system. From the number of sensors that could be supported, further GPIO expander chips, air-conditioning system configurations, room occupancy detection linked into a calendar backend, to clearing out scheduled meetings at an office where nobody showed up, and so on.

There is also the option of switching from ESP8266 as the MCU to a different one, such as ARM-based MCUs, to get wired Ethernet options, along with better debug and development tools. As convenient as it is to have an MCU with Wi-Fi, which one can just stick anywhere and theoretically have it work, the development tools for the ESP8266 aren't that great, and the lack of wired communication options (without using external chips) means that everything either works or doesn't depending on the quality of the Wi-Fi network.

As BMaC involves the automation of a building, it is desirable to have a certain level of reliability, which is hard to guarantee with...

Summary


In this chapter, we looked at how a building-wide monitoring and management system was developed, what its components looked like, and what lessons were learned during its development.

The reader is expected to understand now how such a large-scale embedded system is constructed and functions, and should be able either to use the BMaC system themselves or implement a similar system.

In the next chapter we will look at developing embedded projects using the Qt framework.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Hands-On Embedded Programming with C++17
Published in: Jan 2019Publisher: PacktISBN-13: 9781788629300
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Maya Posch

Maya Posch is a senior C++ developer with more than 15 years of experience. Discovering the joys of programming early on, and later the joys of electronics, she has always expressed a profound interest in technology, a passion that she gladly shares with others. Describing herself as a C developer who happens to like C++ and Ada, she likes to seek the limits of what can be done with the minimum of code and hardware to accomplish everything that is cool, new, and exciting. She also enjoys FPGA development, AI, and robotics research, in addition to creative writing, music, and drawing.
Read more about Maya Posch

Name

Feature

Description

THP

Temperature, Humidity, Pressure

Central class for THP sensors. Enables BME280 functionality by default.

CO2

CO2 value

Measures CO2 <indexentry content="functional modules, Building Management and Control (BMaC):CO2">values using an MH-Z19 or compatible sensor.

Jura

TopTronics EEPROM counters

Reads out the counters for various products from the EEPROM.

JuraTerm

TopTronics remote control

Allows a remote service to send TopTronics (classic, v5-style) commands to a supported coffee machine.

Motion

Motion detection

Uses an HC-SR501 PIR motion sensor or compatible to detect motion.

PWM

PWM output

Sets a pulse-width modulation output on one or more pins.

I/O

I/O expansion

Supports the MCP23008 eight-channel I/O expander module via I2C.

Switch

Persistent switch

Controls a switch that uses a latching relay or equivalent for switching.

Plant

Watering plants

Reads out an analog soil sensor to determine soil humidity, activating a pump...