This chapter applies many of the lessons taught throughout this book to the construction of an example software solution. It goes from initial problem description through to testing the finished product. The solution it presents is simplified and intended to highlight certain concepts. Opportunities for making it more sophisticated are discussed at the end of the chapter.

PROBLEM DEFINITION

Design a computer-controlled home automation system. The system should control the following parts of the house.

Ventilation

This regulates moisture content in the air. Moisture levels should never exceed 70 per cent. Furthermore, the ventilation regularly supplies outdoor air into the house. To do this, ventilation should run regularly at programmed times.

Heating

Radiators can be turned on or off to regulate the house temperature. Each room has one radiator. A pleasant temperature is around 22 degrees. The temperature of a room should not fall below 18 degrees.

Lighting

The lighting in each room should be sensitive to whether the room is occupied or not. When the room is occupied, the lights should be on. If a person leaves the room, the lights should be turned off.

Control panel

The automation system should be capable of being centrally controlled via a control panel. Functions of the control panel:

  • The ventilation system can be programmed to come on at certain times of day.
  • The heating system’s lowest and optimum temperatures can be configured.

DISCLAIMER: do not take any material herein as advice on how to build proper automation systems.

PROBLEM DECOMPOSITION

I’ll begin by decomposing the problem layer by layer into smaller addressable pieces.

Examination of the problem reveals its essence concerns automation and user control. Each subsystem in the proposed system either carries out actions automatically or allows the user to control/configure it. The leads to the first stage in the breakdown ( Figure 13.1 ).

Figure 13.1 Decomposition stage 1

Hierarchical diagram: A diagram labelled Problem definition with branches to Automation and Control. These represent categories under the main problem.

In both cases, these actions concern all three major subsystems: ventilation, lighting and heating ( Figure 13.2 ).

Figure 13.2 Decomposition stage 2

Detailed hierarchical diagram: An expanded hierarchy under Problem definition, with Automation and Control branching into categories like Ventilation, Lighting, and Heating.

At the next level, I identify what the action means when applied to the subsystem in each case. For example, automatic behaviour of the lighting subsystem includes:

  • measuring occupancy;
  • reacting to a change in occupancy.

The resultant breakdown is in Figure 13.3 .

At this point, I believe the sub-problems at the leaves of the tree are solvable individually.

FINDING PATTERNS

Next, I’ll look at the problem description and the decomposition to identify any suitable patterns I could exploit.

Entities

Entities in the system are:

  • rooms;
  • central control panel;
  • subsystems, that is:
    • heating;
    • lighting;
    • ventilation.
  • components, that is:
    • radiators;
    • lights;
    • ventilator.
  • sensors, 70 that is:
    • temperature sensor;
    • occupancy sensor;
    • moisture sensor.

Clearly, many distinct entities exist, but the majority of them can be combined into a more general concept, namely subsystems, components and sensors.

Figure 13.3 Decomposition stage 3

Comprehensive hierarchical diagram: A hierarchical diagram starting with Problem definition, branching into Automation and Control, with subcategories for various tasks like React to occupancy and Program temperature range.

Actions

Actions in the system are:

  • take measurements, that is:
    • temperature;
    • occupancy;
    • moisture level;
    • time.
  • react to environmental change, that is:
    • switch radiators on/off;
    • switch lights on/off;
    • switch ventilator on/off.
  • manually control the system, that is:
    • activate/deactivate an automation subsystem;
    • switch a component in a room on or off;
    • program ventilator time ranges;
    • program target temperature.

Like entities, most actions can be grouped into a smaller number of more general actions. You might have noticed two similar-sounding concepts in the list of actions: activating/deactivating and switching. Are they different names for the same thing? This exemplifies the need to have clear and well-defined terms.

In this case, I think they’re distinct. Activating/deactivating applies to an automation subsystem (that is, moving it between automatic and manual modes), whereas switching means turning on or off a component in a room.

Properties

Properties in the system:

  • environmental:
    • temperature;
    • occupied/unoccupied;
    • moist/dry.
  • Mechanical:
    • subsystem active/inactive;
    • component on/off.

The system is rather a simplistic one, considering most properties have a binary nature. Hence, a room is either occupied or not, it’s cold or not and so on. This greatly simplifies things.

Rules

Fortunately, this problem specification provides some relatively clear logical rules about how the solution should operate:

  • If the temperature is less than 18 degrees, then radiator should activate.
  • If the temperature is greater than the target temperature, then radiator should be inactive.
  • If a room is occupied, then lights should be active otherwise lights should be inactive.
  • If the moisture level is greater than 70 per cent or the current time is within the ventilator programmed time range, then the ventilator should be active, otherwise the ventilator should be inactive.

FORM GENERALISATIONS AND ABSTRACTIONS

As we look back over the decomposition, the following abstractions suggest themselves:

  • The whole system consists of three subsystems and a control panel .
  • Each subsystem consists of a collection of sensors and components .
  • Each sensor is positioned in a room .
  • A subsystem monitors sensors and reacts to their readings, ordering components to switch on/off according to rules .
  • Rules map readings to responses .

Remarks

Some reasons why I judge certain abstractions to be valuable:

  • Control panel: for the moment, we can refer to a control panel without deciding on its implementation. It could be a physical control panel or just as easily a smartphone app.
  • Component: all components are essentially objects in rooms that can be switched on and off, so I can simplify the solution by considering one component entity instead of three different ones.
  • Sensor: similarly, all sensors take readings, giving me one sensor entity instead of four.
  • Rules: each subsystem has different logic driving its behaviour. However, the concept of a rule adequately encapsulates any piece of logic at the moment, so at this stage I don’t have to worry about the intricacies of each one. Rules also raise the possible need for something that carries out the monitoring and reacting in a subsystem, which we could call a regulator .
  • Responses: a response, at the moment, is simply a switch on/off command, so this abstraction is probably overkill at this time. For simplicity’s sake, I’ll leave this abstraction out of the solution. However, it’s not inconceivable to imagine that other components with gradated controls get added to the system in future, meaning that the nature of a response would vary depending on the type of component.

MODELS

By extracting and analysing some generalised concepts, I’ve come to a tentative understanding of their behaviour. Next, I want to come to a better understanding of some of them, so I’ll create models of those key parts.

Conceptual overview

By modelling the structure of the entities, I create a template for the objects that will eventually exist.

Figure 13.4 depicts the generalisation of rules. It’s a fairly straightforward structure. In general, a rule can be applied (hence the apply function), and four specific types of rule exist.

Figure 13.4 Class diagram of rules

Class hierarchy diagram: A class hierarchy starting with Rule, including apply method, and branching into classes like Temperature Rule, Occupancy Rule, Time Rule, and Moisture Rule.

The story is very similar with components and sensors ( Figure 13.5 ). A sensor can take readings and return the result. A component can be switched on or off. One notable thing is that the system can include multiple sensors and components. In order to control them individually, the solution needs to identify each uniquely, hence each possesses an ID number denoting which room it resides in.

Figure 13.5 Class diagrams of components and sensors

Sensor-component hierarchy diagram: A class diagram with Sensor and its subclasses Temperature Sensor, Moisture Sensor, and Occupancy Sensor. Component connects with subclasses Radiator, Light, and Ventilator.

It seems now that the idea for a regulator was prescient. I can use one to bring all these concepts under its control ( Figure 13.6 ). A regulator collects multiple sensors and components of a subsystem together and applies a rule when processing readings.

States and workflow

The system involves very careful control of multiple parts based on rules, so it’s essential to understand that behaviour clearly, long before any code is written. Some workflows appear simple so I won’t model everything, but I’ll examine a few places that strike me as probable sources of complexity.

As a central controlling node in the solution, the regulator’s behaviour involves a potentially complex interaction of several things. So, I’ll create an activity diagram to model what a regulator does when it processes readings ( Figure 13.7 ).

From the model, the regulator seems to cycle in a loop, taking measurements and switching components when necessary. One spot conceals some potential complexity, namely the activity where readings are mapped to a component state.

Figure 13.6 Class diagram of regulator

Class relationship diagram: A diagram showing relationships between Sensor, Regulator, Rule, and Component. Associations like 1 are shown to indicate multiplicity.

To explore this complexity, I could create state machine diagrams for each component that describe how state changes happen. Since space is limited, I’ll just show one: the lighting.

Figure 13.8 shows what happens in terms of state alterations in the lighting subsystem. To switch the lighting on, the room must be occupied. Conversely, if the room subsequently becomes unoccupied, the system switches the lights back off.

This seems very simple. However, by modelling this process I forced myself to think it through, and this raised some practical questions. Specifically, I asked myself how occupancy might be measured. The industry standard for automatic lighting systems is through motion detection. The problem is, for a regulator to react promptly when someone enters the room, it would have to process sensor readings continuously (let’s say once per second). But that would also mean the lights switch off whenever a room occupant happens to be motionless for a second or two. You can imagine how annoying that would be if you were sitting in a chair trying to watch TV.

Figure 13.7 Activity diagram of regulator

Activity diagram: A diagram showing actions like Take sensor reading and Map reading to state, with conditions like Change required leading to Switch component.

Figure 13.8 State diagram of applying a lighting rule

State transition diagram: A state machine with states Off and On, connected by transitions labelled Room occupied and Room unoccupied.

To take account of this, I’ve altered the rule for a lighting regulator by adding a time buffer (see Figure 13.9 ). Instead of switching the lights off immediately when no motion is detected, the regulator initiates a countdown. The lights will only be switched off when the countdown reaches zero. If, at any point, motion is again detected, the countdown is reset.

Figure 13.9 Revised state diagram of applying a lighting rule

State Machine Diagram: A state machine showing three states. Off, On, and On counting down, with transitions labelled based on room occupancy, time values, and elapsed seconds.

ANNOTATED SOURCE CODE

Let’s look through the code that implements the solution. First, the overall structure of the system:

images

The system is divided into two packages:

  1. core: the central parts of the home automation system.
  2. subsystems: the different subsystems that make up a home automation system.

The tour begins with the core parts module. (Comments offer some description of what’s happening in each module.)

images

These are abstract classes, not really intended as concrete parts, so let’s turn our attention to how these core parts can be implemented as concrete subsystems. (We’ll come back to the core package later.)

The simplest subsystem is heating:

images

The ventilation subsystem is not too much more taxing:

images

images

Finally, the lighting subsystem:

images

images

That concludes the subsystems. Let’s turn to the core package and look at the regulator:

images

TESTING

Let’s look at a few illustrative test cases. I’ll update the project layout to look like this:

images

Unit tests

The unit tests will be recorded in files inside the test directory. First, unit testing the lighting rule. This tests only the LightingRule class.

images

images

The test run looks like this:

python -m unittest test/test_ lighting.py
…
---------------------------------------
Ran 3 tests in 0.000s

OK

System testing

Once individual units are shown to work well, we should put those units together to simulate use of the whole system. The following example integrates all parts of the heating subsystem and verifies that they work together properly.

images

images

OPPORTUNITIES FOR IMPROVEMENT

As I said at the beginning, this is a very simplistic solution, optimised to show a few, easy-to-understand concepts. Many opportunities exist to make this example a more sophisticated and functional solution.

Here are a few I can think of:

  • Add the code for the control panel.
  • A regulator that supports multiple rules, so, for example, a ventilator can have separate rules for moisture and time.
  • A component that has a more sophisticated status (such as dimmable lights).
  • Add logging messages at appropriate places to aid debugging and monitoring.
  • Write a system test that simulates three subsystems running at the same time.
  • An improved countdown in the lighting subsystem, for example:
    • The lighting rule currently assumes that a regulator processes readings once per second. That may not be true in future and would break existing functionality if it changed (for example, a lighting regulator that processes two readings per second will run down the countdown after only 2.5 minutes). Alter the way the countdown measures time, so the LightingRule’s countdown doesn’t depend on the regulator. 71
    • Advanced: make the countdown process a concurrent thread of execution. 72

What improvements can you think of?

Consider it an exercise to take whichever ideas you prefer and turn this simple system into a great home automation solution of your own.