Tag Archives: DIY

Logs, logic and inspiration: Managing a complex home control setup

You know how it goes.  You start with one or two home control devices.  You find it amazing that you can control them from your phone.  You want more.  And more…

Here’s a quick diagram of my current setup at home.

setup.png

There are at least 77 items for the home control system to control.  Each one has a unique set of capabilities, and inter dependencies with other devices.  Certain groups of these items require different communication protocols, some radio, some infrared, some HTTP and some via a webserver.

As my system has been created from several protocols and brands, I find it engaging and a full-on hobby to ensure they perform perfectly in concert.  Basic scripting has become more in-depth as I attempt to squeeze out the most from every device.  Although adding additional functionality is stimulating for me and ultimately rewarding for me and my flatmate, each iteration adds a new layer of complexity – and like every complex system, the bigger it is, the harder it can fall.

I’ve recently been faced with a problem.  A few times in a row, the Raspberry Pi 2 has frozen overnight. The controls and automatic lighting obviously do not respond, and then something as simple and as taken for granted as getting light and audio into the shower requires scrabbling through phone apps: not good if the water is already running!  Worse, the switches that are supposed to be triggered in the early morning, such as the “it is dawn” variable do not fire.  So with such a complex system how do you diagnose the problem?

Logs

The first answer is logs.  Loads of logs.  Ensure each of your subsystems are writing down what they are doing and just as importantly when they are doing it.  You can then rifle through the logs and find anything that is not behaving as you’d planned.

Inter-dependency diagrams

Okay, so this may be the most geeky thing I have said on this blog so far, but I like to keep diagrams and spreadsheets showing which systems and activities are inter-related.  And in the event of a catastrophic failure, they pay dividends.  You can literally trace your finger through the lines and see which scripts you need to check if something is not working right.  You can also keep track of things like ID codes and group codes for all your connected devices.

Logic

To do this you need to empty the house of unexpected variables (i.e. the rest of the family and pets large enough to trigger any sensors) and then physically run through each process that you think may be causing the problem.  If you are anything like me this usually involves an embarrassing and potentially uncomfortable period where you are remaining totally motionless right in front of a motion sensor to see what happens when the “no movement here” signal is sent.

Inspiration

You may be surprised by the other users’ perception and understanding of your home control system.  Ask other occupants what they think is happening.  At best they could hit the nail on the head, and if not they just may throw something so left-of-centre out there that is provides you with the fresh outlook you need to trace the problem.

Summary

I feel this entry will become outdated very soon.  As consumers we are on the cusp of having our cake and eating it: a fully integrated one-stop solution for home automation that will work seamlessly and without requiring manual programming.  It may even have the ability to provide reasons for failure and suggest ways to work around it, especially if open-source and app-based: a fellow user in the Netherlands could be granted temporary access to help sort out the problem you’re having with your garage door in California.

This new way will remove the complexity involved in getting disparate systems to work together, but will it provide the level of control we ‘first gen’ full home control aficionados will require?  Either way, I’m glad I’ll be able to say “In my day, we had to fumble around to find the solutions to these issues, and sometimes create our own!”

 

 

Advertisement

Writing a home control front end in HTML.

I’ve been asked a few times about my custom front-end for my Domoticz, Hue and Sonos setup, so here are a few HTML snippets and where to put them, assuming you are running Domoticz on your home control server.

Right from the offset I must stress that the Icons I have used are made by various incredibly skilled designers at http://www.flaticon.com/ and therefore this front end cannot be used for any commercial purpose.

I have previously written an extensive post about the continuous development of a home control user interface and have posed a video containing my front end, so this post will not be about the thought process behind creating a UI, rather how I have managed to put one together using HTML.

I must also stress that I am not an expert in baking a web app.  Developers may read my code and scoff at its inefficiency but it works for me, and hopefully can give you some inspiration.

Layout

The layout of all panels follows the same template: A main area where the actual buttons and controls live, changing depending on which screen the user selects; the ‘scenes’ bar, a blue strip towards the bottom of the display which is a kind of ‘quick access’ ribbon for regularly used commands; and a Links bar which permanently shows the pages that can be displayed.

layout

There is also a ‘notifications’ display which shows up just above the scenes bar with information provided by a variable in Domoticz.  This text can be ‘cleared’ by touching it (more on this later).

All screens use variations on the same HTML so not every screen is shown in detail in this post.

Home Screen

Home

Home is where the heart is.  I like the home screen to be simple, uncluttered and good looking.  It’s by far the screen shown most regularly so less is more here.

The interesting part of this screen is the background.  It changes depending on the weather.  First I saved six 2000×600 backgrounds with names ranging from weatherback-rain.png to weatherback-fog.png.  You need cloudy, fog, partlycloudy, rain, snow and sunny.  I set the size of these backgrounds to fit the tablet which the screen is displayed on so you may need to adjust accordingly.

The HTML code to change the background depending on the weather is as follows (change xx, yyyy and zz to the address of your Domoticz server, the port Domoticz is using and the idx code of your weather source in Domoticz):

function updateweather(){

                var forecast

                var xmlhttp = new XMLHttpRequest();

                var url = "http://192.168.1.xx:yyyy/json.htm?type=devices&rid=zz";

                var forecast

                xmlhttp.onreadystatechange = function() {

                 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

                 var myArr = JSON.parse(xmlhttp.responseText);

                                                forecast = myArr.result[0].ForecastStr;

                                                console.log("Forecast is " + forecast + ".")

       // myFunction(myArr);

                                                 if (forecast == "Partly Cloudy") {

                                                 document.getElementById("weatherindicator").src = "weatherback-partlycloudy.png";

                                                                }

                                                 if (forecast == "Sunny") {

                                                 document.getElementById("weatherindicator").src = "weatherback-sunny.png";

                                                                }                                                              

                                                if (forecast == "Rain") {

                                                 document.getElementById("weatherindicator").src = "weatherback-rain.png";

                                                                }              

                                                if (forecast == "Fog") {

                                                 document.getElementById("weatherindicator").src = "weatherback-fog.png";

                                                                }                              

                                                if (forecast == "Snow") {

                                                 document.getElementById("weatherindicator").src = "weatherback-snow.png";

                                                                }

                                                if (forecast == "Cloudy") {

                                                 document.getElementById("weatherindicator").src = "weatherback-cloudy.png";

                                                                }                                              

                                                }

                }

xmlhttp.open("GET", url, true);

xmlhttp.send();

setTimeout(updateweather,60000);

}

Notice that the last line of this code sets up the web page to update the weather picture every 60 seconds.  Ok, in the body of your HTML you’ll need something like

<div id="weatherdisplay" align="left" class="weatherback"><img id="weatherindicator" src=""></div>

And you’ll need something like this wherever you save your CSS:

div.weatherback {

    position: fixed;

    top: 0px;

    left: 0px;

    width: 1000px;

                height:600px;

}

Activating Hue scenes

The API for Hue is relatively easy to use.  I used the API to save scenes to each room and then can recall them from the press of an icon on the scenes bar.  The HTML at the scene bar is easy:

<a href="javascript:;" onClick="groupscene(1,7);switchoff(24)"><img src="scene-cinema.png" width="150" height="150" border="0"></a>

The button called scene-cinema.png does two things actually, sets the group 1 to scene 7 and then switches of a switch in Domoticz.  Let’s see the code for each of these functions:

function groupscene(group,scene){

                execute('PUT', 'http://192.168.1.aa/api/bbbbbbb/groups/'+group+'/action', '{"scene":"'+scene+'"}');

}

Change aa to the address of your Hue bridge and bbbbbb to the name of the developer (if you followed the Hue API instructions from the Hue website this might be “newdeveloper”.  If your scene does not change straight away then your control panel might not be authorised to the Hue bridge.  If this is the case, press the button on the Hue bridge and then try again a couple of times.

function switchon(devicecode){

                execute('PUT', 'http://192.168.1.xx:yyyy/json.htm?type=command&param=switchlight&idx='+devicecode+'&switchcmd=On', '');

}

 

function switchoff(devicecode){

                execute('PUT', 'http://192.168.1.xx:yyyy/json.htm?type=command&param=switchlight&idx='+devicecode+'&switchcmd=Off', '');

}

 

function toggle(devicecode){

                execute('PUT', 'http://192.168.1.xx:yyyy/json.htm?type=command&param=switchlight&idx='+devicecode+'&switchcmd=Toggle', '');

}

 

function dim(devicecode,dimlevel){

                execute('PUT', 'http://192.168.1.xx:yyyy/json.htm?type=command&param=switchlight&idx='+devicecode+'&switchcmd=Set%20Level&level='+dimlevel, '');

}

The above codes (again change xx to the address of your Domoticz server and yyyy to the port number) are all similar. Switchon, switchoff do what they say on the tin.  Toggle changes the state of an on/off switch and then dim sets a certain switch you specify (idx) to the dim level you select (dimlevel).

While we’re here, here’s a list of the other Hue functions I put into the home control system:

function lightoff(light){

                execute('PUT', 'http://192.168.1.aa/api/bbbbbb/lights/'+light+'/state', '{"on":false}');

}

 

function lightmax(light){

                execute('PUT', 'http://192.168.1.aa/api/bbbbbb/lights/'+light+'/state', '{"on":true,"bri":255,"sat":0,"hue":0}');

}

 

function briup(group){

                execute('PUT', 'http://192.168.1.aa/api/bbbbbb/groups/'+group+'/action', '{"bri_inc":40}');

}

 

function bridn(group){

                execute('PUT', 'http://192.168.1.aa/api/bbbbbb/groups/'+group+'/action', '{"bri_inc":-40}');

}

 

function groupcontrol(group,hue,bri,sat){

                execute('PUT', 'http://192.168.1.aa/api/bbbbbb/groups/'+group+'/action', '{"on":true,"bri":'+bri+',"sat":'+sat+',"hue":'+hue+'}');

}

 

function groupscene(group,scene){

                execute('PUT', 'http://192.168.1.aa/api/bbbbbb/groups/'+group+'/action', '{"scene":"'+scene+'"}');

}

So these are the main components of the home page – and here’s a snippet of how I go the inside and outside temperature (change zz to the idx of your temperature sensor):

function updateintemp(){

                var instatus

                var xmlhttp = new XMLHttpRequest();

                var url = "http://192.168.1.xx:yyyy/json.htm?type=devices&rid=zz";

                xmlhttp.onreadystatechange = function() {

                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

               var myArr = JSON.parse(xmlhttp.responseText);

                                                instatus =  "Inside: " + myArr.result[0].Data;

                                                console.log(instatus)

                                                document.getElementById("intemp").innerHTML = instatus

                }

                }

xmlhttp.open("GET", url, true);

xmlhttp.send();

setTimeout(updateintemp,20000);

}

You need a div with id “intemp” positioned where you like, and again the last part of the above code sets up the web app to update the temperature each 20 seconds.

Devices screen

devices

The devices screen updates the icons with a green bar when the switch is on and a grey bar when off.  I save two identical png pictures, one with -on.png at the end and one with -off.png.  I enter this HTML repeatedly, changing the id and the source of the picture for each button:

<a href="javascript:;" onClick=”toggle(xx)"><img src="chesterlampoff.png" width="125" height="125" hspace="5" vspace="5" border="0" id="chesterlamp"></a>

Change xx to the idx of the device in Domoticz (you can find the idx of the device in the ‘Devices’ tab of the Domoticz interface.

Change the id=”chesterlamp” to id=”whateveryourdeviceiscalled” then change the img src to the ‘off’ picture for your device.

In the code part you need the following:

function updatedevice(idx,location,onimage,offimage){

                console.log("checking status of idx "+idx)

                var xmlhttp = new XMLHttpRequest();

                var url = "http://192.168.1.94:8080/json.htm?type=devices&rid="+idx;

                var onoff

                xmlhttp.onreadystatechange = function() {

                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

               var myArr = JSON.parse(xmlhttp.responseText);

                                                onoff = myArr.result[0].Status;

       // myFunction(myArr);

                }

                                if (onoff == "On") {

                                document.getElementById(location).src = onimage;

                                }

                                if (onoff == "Off") {

                                document.getElementById(location).src = offimage;

                                }

                                if (onoff == "Open") {

                                document.getElementById(location).src = onimage;

                                }

                                if (onoff == "Closed") {

                                document.getElementById(location).src = offimage;

                                }

                }

xmlhttp.open("GET", url, true);

xmlhttp.send();

}

Then another function where you will put all the code to tell the web app to update the icons depending on how Domoticz reports the switch (on or off, or even open or closed if you’re using door sensors too):

window.setInterval(function(){

                updatedevice(187,'chesterlamp',"chesterlampon.png","chesterlampoff.png");

                updatedevice(132,'washingmachine',"washingmachineon.png","washingmachineoff.png");

                countup();

                updatenotification(11)

                }, 1000);

I’ve put two switches here, Chester’s lamp and the washing machine.  You can add as many switches as you like here, as long as they have been set up in the body of the HTML.

There are two other functions that are called each second too: countup() and updatenotification(11)

Automatically reverting to the Home Screen

If you want the screen to revert to home after two minutes of inactivity, you can use this code:

First put

var ticker = 0;

at the start of your code block, then put:

function countup(){

                ticker=ticker+1

                console.log("Ticker is " + ticker);

                if (ticker>120) {

                                console.log("Moving to index...")

                                MM_goToURL('self','index.htm');

                                }

                }

This means that once the variable ‘ticker’ has incremented to 120, the screen will go to the page called index.htm.  If you use this code, remember to put this at the end of each function:

ticker = 0;

This will reset the timer so that another 2 minutes have been added to the time before the page will switch to the Home Screen.

Notifications from Domoticz

I have set up the screens to show a strip which indicates what Domoticz is up to.  Some of my LUA scripts in Domoticz update a variable with a string of text in English to tell the user what Domoticz is doing.  This could be confirmation that a switch has been turned on/off or it could report is something has been triggered automatically.

First, create a string variable in Domoticz called LastEvent and then note down its idx.  In the below case the idx is 11 (and there’s already a string update in there too, yours will be empty when you first set it up).

variables

Back to the home control HTML:

function updatenotification(idx){

                console.log("checking status of idx "+idx)

                var xmlhttp = new XMLHttpRequest();

                var url = "http://192.168.1.xx:yyyy/json.htm?type=command&param=getuservariable&idx="+idx;

                var textentry

                xmlhttp.onreadystatechange = function() {

                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

               var myArr = JSON.parse(xmlhttp.responseText);

                                                textentry = myArr.result[0].Value;

       // myFunction(myArr);




                                document.getElementById("notification").innerHTML = textentry;

                                }

                                }

xmlhttp.open("GET", url, true);

xmlhttp.send();

}

And:

function clearnotification(idx){

                execute('PUT', "http://192.168.1.94:8080/json.htm?type=command&param=updateuservariable&idx="+idx+"&vname=LastEvent&vtype=2&vvalue=%00", '');

}

And in the body of the HTML (so once the text is clicked the variable in Domoticz is reset to null):

Something like this for the CSS: div.notificationpane {     position: fixed;     bottom: 250px;     left: 0px;                 width: 100%;                 font-size: 30pt;                 background-color: #333333;                 text-indent: 25px;                 opacity: 0.6; }

Then in the LUA script, when you want to notify the user about something, you can add a line like this:

commandArray['Variable:LastEvent'] = tostring(os.date("%H") .. ':' .. os.date("%M") .. ' Rear balcony door opened, lights on for 15 minutes.')

This adds the time and the text to the variable, which then almost immediately pops up on the Home Control screen until it is clicked.

Where to store your HTML

When you have created your masterpiece, you can save it in a new folder of your choice below the /domoticz/www/ folder.  You can use something like WinSCP to create a folder and then transfer all your files in one go.

Then, when you usually navigate to 192.168.1.1:8080 to go to the Domoticz home screen, add / then the name of your folder then /index.htm or whatever your home screen address is.

Summary

Due to the jerry-rigged nature of my HTML code I am not going to publish it in its entirety.  I also don’t know the ins and outs of using the flaticons.com icons and publishing them directly.  Hopefully, however, this post will give you some inspiration to write your own home control front end.

Creating a security system

A major plus for home automation is the ability to give any device multiple purposes.  With a little imagination, a Sonos speaker can become a voice announcer, a lightbulb can become an effective method of simulating occupancy in a home.

Everyone wants to feel their possessions are secure.  A standard house alarm is useful- and many are becoming smarter- but there is always the chance that a ringing alarm box is less of a call-to-arms and more of an annoyance to be ignored.  With that in mind, I would suggest building your own security system to notify you as soon as something is out of the ordinary.

This security system is created wholly from home automation products and is armed when you select a switch called “Leaving” on Domoticz, waits for 5 minutes to allow you time to come back in if you have forgotten anything (which I always do!), then after a further 5 minutes attempts to detect your phone(s) and if they are in wifi range, disarms the system again.

What you’ll need

  • Raspberry Pi running Domoticz
  • RFXCOM RFXtrx433
  • A number of door sensors, vibration sensors or PIRs (or any combination of these)
  • Python running on the Raspberry Pi
  • Maybe a network IP camera if you want to capture a photo when the alarm is triggered

How long it will take

Depending on the number of door sensors/PIRs/Cameras that you want to install, it could take anything from 15 minutes to several hours.

Step One – Install your devices

Choose entry points to your home.  The obvious one is the front door but also think about other places where someone may try to gain entry.

For doors, place the sensor towards the top of the door.  Remember to look at where the battery will need changing from, and ensure this will be easy to access by orienting the battery compartment/drawer towards the ground.  If space is limited, remember that there’s nothing to stop you attaching the larger part of the sensor (the transmitter) on the door itself and the smaller part (housing the magnet) on the frame of the door.  Use sticky strips first to test, even if you plan to screw the sensor to the door later.

For vibration sensors you can usually affix these directly to the window using suction cups.  If the type you have requires a more permanent fixing, try taping the sensor to the window first to ensure you (and other family members) are happy with their placement.

For PIRs, install these unobtrusive but accessible areas.  Remember that as these devices are wireless, you can even place them on shelves.  You don’t need to put them in corners of rooms like wired sensors.  Choose places where it would be impossible not to cross the detector if moving from room to room (hallways are a great position).  Remember that if you have pets the sensors should be raised up so that they can only be activated by humans.

Learn and name each sensor into Domoticz.  Remember to specify what type of device you are adding (PIR, Door sensor etc).

Step Two – Create a few Dummy switches

Create a dummy switch called “Leaving”.  This will be ON when you have left the home and OFF when you return.

Another dummy switch called “Security Alarm” is needed.  This is the switch that tells the scripts whether to send you an alert when a sensor is triggered.  You don’t want to get alerts when you are at home (as you’re probably the one triggering them!)

Another dummy switch called “Waiting for Phones” needs to be created.  This will be ON when the security system is waiting for you to return home.

Then create a switch for each phone you want to automatically disarm the system with.  I use two switches (“Chesters Phone” and “Harrys Phone”).

Finally, we need one more dummy switch – “Arm Security”.

Step Three – Write the scripts

A few scripts are needed now.  What will happen when you switch on the “Leaving” switch?  What about when it is turned off?  What happens when a sensor is activated and the “Security Alarm” switch is on?

The first code I write is saved as “device_SECURITY_Leave.lua” and is saved in the domoticz/scripts/lua/ folder

commandArray = {}
if devicechanged['Leaving'] == 'On' then
 commandArray['Environment Automation'] = 'Off'
 commandArray['Living Room Camera'] = 'On'
 commandArray['Security Alarm'] = 'Off'
 commandArray['Arm Security'] = 'On'
 commandArray['TEMP Set to 15'] = 'On'
 end
 return commandArray


This script (which I have reduced down as there are tens more switches to change when the flat is left unoccupied) runs once the Leaving switch is turned on.

We need a script to say when the alarm is activated – notice that I don’t switch the “Security Alarm” switch on with the above code.  If I did, once the Leaving switch was set, notifications would be sent to my phone as I walk through the flat to leave and open the front door.  I want to add a delay to the arming of the system.  This script is a timed script so starts with the text”script_time” instead of “script_device” – I’ve called it “script_time_SECURITY_Leaving.lua”

t1 = os.time()
s = otherdevices_lastupdate['Arm Security']
 
year = string.sub(s, 1, 4)
month = string.sub(s, 6, 7)
day = string.sub(s, 9, 10)
hour = string.sub(s, 12, 13)
minutes = string.sub(s, 15, 16)
seconds = string.sub(s, 18, 19)
 
commandArray = {}
 
t2 = os.time{year=year, month=month, day=day, hour=hour, min=minutes, sec=seconds}
difference = (os.difftime (t1, t2))
print ('Leaving difference ' .. difference)

if (difference > 300 and otherdevices['Security Alarm'] == 'Off' and otherdevices['Arm Security'] == 'On') then
 commandArray['Security Alarm'] = 'On'
 commandArray['Arm Security'] = 'Off'
 print ('Security Alarm is now armed.')
 commandArray['SendNotification']='Security Armed#Security alarm is now armed.'
end 

if (difference > 600 and otherdevices['Waiting for Phone'] == 'Off' and otherdevices['Leaving'] == 'On') then
 commandArray['Waiting for Phone'] = 'On'
 commandArray['Harry Phone'] = 'Off'
 commandArray['Chester Phone'] = 'Off'
 print ('Waiting for phones to return.')
end 

return commandArray

Again, I’ve removed quite a few of the potential sensors to activate the alarm, but you get the idea.  You may notice another switch in there – “SECURITY Living Room”.  This switch is linked to a network camera we have in the living room, and thanks to the inbuilt scripting in Domoticz, sends a picture from the camera via email to multiple recipients.

The Security Screen of my homemade home control panel

The above script checks how long it has been since the “Arm Security” switch has been activated.  If 5 minutes, then the “Security Alarm” switch is turned on.  If 10 minutes, then the system starts searching for phones.  Living in a block of flats it is hard to judge the best interval for this.  On more than one occasions Chester and I have left the flat for the day, only to bump into a neighbour on the stairwell and have a gossip with them.  This has turned into more than a 10 minute delay, and as we’re still in range of our WiFi, this in turn switches off the “Security Alarm” switch.

Now we need the script to watch out for our phones to automatically disarm the system.  This is in three parts.  One part controls the timing (i.e. run a script every minute if waiting for phones to return) while the other two try to find our phones using a quick Python script.  The first goes in the domoticz/scripts/lua folder and I have called it script_time_SECURITY_Phones.lua:

commandArray = {}
if otherdevices['Waiting for Phone'] == 'On' then
 os.execute('python3 ./Security-Detection-Harry.py &')
 os.execute('python3 ./Security-Detection-Chester.py &')
end 
return commandArray

As you can guess, we now need some Python programs.  They are both the same (except each phone has its own static IP address and its own switch in Domoticz).  These are stored in the domoticz folder itself (not in any subfolder):

This one is called Security-Detection-Harry.py

import urllib
import requests
from random import randint 
import base64,requests,json,time,datetime
import os
"""
Detects Harry's phone and switches Domoticz if found.
"""
hostname = "192.168.1.1"
response = os.system("ping -c 1 " + hostname)
#and then check the response...
if response == 0:
   print (hostname, 'is up!')
   req = requests.get('http://192.168.1.94:8080/json.htm?type=command&param=switchlight&idx=176&switchcmd=On')
else:
   print (hostname, 'is down!')
   req = requests.get('http://192.168.1.94:8080/json.htm?type=command&param=switchlight&idx=176&switchcmd=Off')

So the above script searches for my phone (the IP address of my phone is fixed to 192.168.1.1) and switches a switch in Domoticz if my phone is detected or not.  In the above example Domoticz has given my “Harrys Phone” switch the number 17, so that’s the one I want to alter depending on whether the phone is present or not.

The next script deactivates the security alarm if the phones are detected.  Saved in domoticz/scripts/lua it is called script_device_SECURITY_Phones.lua:

commandArray = {}
if devicechanged['Waiting for Phone'] == 'On' then
 commandArray['Harry Phone'] = 'Off'
 commandArray['Chester Phone'] = 'Off'
end
if (devicechanged['Chester Phone'] == 'On' and otherdevices['Waiting for Phone'] == 'On' and otherdevices['Leaving'] == 'On') then
        commandArray['Leaving'] = 'Off'
        print("Chester's phone detected.")
 commandArray['SendNotification'] = 'Security Message#Chesters phone detected.  Disarming system and switching on devices.'
end
if (devicechanged['Harry Phone'] == 'On' and otherdevices['Waiting for Phone'] == 'On' and otherdevices['Leaving'] == 'On') then
        commandArray['Leaving'] = 'Off'
        print("Harry's phone detected.")
 commandArray['SendNotification'] = 'Security Message#Harrys phone detected.  Disarming system and switching on devices.'
end
if (devicechanged['Chester Phone'] == 'On' and otherdevices['Waiting for Phone'] == 'On' and otherdevices['Leaving'] == 'Off') then
        commandArray['Waiting for Phone'] = 'Off'
        print("Chester's phone detected.  No action taken.")
end
if (devicechanged['Harry Phone'] == 'On' and otherdevices['Waiting for Phone'] == 'On' and otherdevices['Leaving'] == 'Off') then
        commandArray['Waiting for Phone'] = 'Off'
 print("Harry's phone detected.  No action taken.")
end
return commandArray

Very nearly there!  This script is saved in domoticz/scripts/lua and is called script_device_SECURITY_Return.lua and tells Domoticz what to switch back on when one of us arrives home.

commandArray = {}
if devicechanged['Leaving'] == 'Off' then
        commandArray['Power Up'] = 'On'
        commandArray['Living Room Camera'] = 'Off'
        commandArray['Arm Security'] = 'Off'
        commandArray['Waiting for Phone'] = 'Off'
        commandArray['Security Alarm'] = 'Off'
        commandArray['Environment Automation'] = 'On'
 if otherdevices['VAR Dusk'] == 'On' then
         commandArray['DIMMER TV Lamps'] = 'Set level 100'
         os.execute('./Hue-LR-Darkday.py')
  commandArray['Front Balcony Lights'] = 'On'
 end
        commandArray['Air Purifier'] = 'On'
        commandArray['Living Room TV'] = 'On'
        commandArray['Washing Machine'] = 'On'
 commandArray['Cat Sitter'] = 'Off'
end
return commandArray

Now there’s only one thing left to do: decide what happens when the alarm is activated.  You could turn on lights, make sound come out of a network speaker, switch on the TV, contact you using the Domoticz alerts function… the list is endless.  Here’s some of my code, again stored in domoticz/scripts/lua and this is called script_device_SECURITY_Sensors.lua

commandArray = {}

if (devicechanged['DOOR Entrance'] == 'Open' and otherdevices['Security Alarm'] == 'On') then
 commandArray['SendNotification'] = 'Security Message#Front door opened.'
 commandArray['VAR Entrance'] = 'On'
        commandArray['SECURITY Entrance'] = 'On'
 print('ALARM ACTIVATED - FRONT DOOR SENSOR')

elseif (devicechanged['DOOR Hallway'] == 'Open' and otherdevices['Security Alarm'] == 'On') then
 commandArray['SendNotification'] = 'Security Message#Hallway door opened.'
        commandArray['SECURITY Living Room'] = 'On'
        print('ALARM ACTIVATED - HALLWAY SENSOR')

elseif (devicechanged['DOOR Hallway'] == 'Closed' and otherdevices['Security Alarm'] == 'On') then
 commandArray['SendNotification'] = 'Important Security Message#Hallway door closed!'
        commandArray['SECURITY Living Room'] = 'On'
        commandArray['VAR Entrance'] = 'On'
        print('ALARM ACTIVATED - HALLWAY SENSOR')end
return commandArray
This is a small (but functioning) fragment of all the sensors that will trigger a security alert in the flat if we are away and something unexpected happens.
Summary
I have probably made this system more difficult than it needs to be over time, but this security system does work flawlessly and does provide peace of mind when we’re away.  If you have some home automation sensors doing one type of job, why not get them involved in creating a bespoke security system… and make them earn their keep around your home.  Your family will thank you for it – as long as the process of arming and disarming the system is as user friendly as possible.

Outdoor lighting

Unless you are lucky enough to have pre-wired lighting in outdoor spaces, it can be hard to link outdoor lighting to a home automation setup.  There aren’t many wireless and battery powered lights that can be controlled with radio signals, because ‘listening’ for the radio signals all the time will drain the batteries pretty quickly.

As part of my ‘ready for summer’ programme, we’ve just attached a reed fence to the back balcony, primarily so we can let our cat out for a bit of sun now and then so she doesn’t launch herself off the 3rd floor.  But me being me, I wanted some form of home control out there,  Of course, I could take out the Hue Go and I’m sure I will especially when summer (and wine) comes.  But it would be nice to have something permanent out there.

I remembered that I had a couple of the Lightwaverf LED lights we used to use in the kitchen and bathroom.  These are small white blocks, with a cluster of 3 bright LEDs (powered by 3 AAA batteries) encapsulated in a transparent circle that also acts as an on/off button.  The boffins at Lightwaverf have managed to work out how to use very little energy with these lights, so replacing the batteries does not need to happen as often as you might guess.

They’re perfect for mood lighting so I guessed they would have enough oomph for a double balcony.  They do indeed as the below images will testify!

backbalc1

balcony2

The lights themselves are not waterproof, so after some careful consideration (and rummaging around the house) I gathered together 2 old (clean!) takeaway boxes and some trusty super-strength double-sided sticky foam.  I stuck the top (the flat end) of the box to the wall, then the whole LED unit onto the surface, then pushed what was the bottom of the box (now the front of the light) on.  To replace the batteries I’ll just have to remove the ‘cover’ and then slide out the LED from its integrated holder.

Although (as in the picture) the lights look rather industrial, I like them!  Of course, you could encase the lights in whatever waterproof enclosure you want, just remember that you will have to open them at some stage to replace the batteries.

Now the lights were not accessible by human hands, I had to devise a way of switching them on and off.  I’d already linked them up with Domoticz, so we could use the app to control the lights.  But that’s not enough, is it!  As all 3 doors to the flat (and some doors inside the flat) have open/closed sensors, I hooked up the lights to the balcony door.  When the door opens, the lights come on for 5 minutes.  That’s enough to find a seat, set up a table and then decide if you’re staying out there, in which case you can use the Domoticz interface to keep the lights on.

One more thing… I didn’t want the lights to come on during the day when the door is opened.  That would just be wasteful.  As I had already set up a dummy switch called ‘Dusk’ that switches on just before sunset and switches off at sunrise, I could add this to the mix.

Just this much text as a script in your domoticz folder on your Pi achieves this.  It’s really that simple.

commandArray = {}
if (devicechanged['DOOR Chester Balcony'] == 'Open' and otherdevices['VAR Dusk'] == 'On' and otherdevices['Rear Balcony Lights'] == 'Off') then
 commandArray['Rear Balcony Lights'] = 'On FOR 5'
end
return commandArray

So even for someone who has no knowledge of programming, you can see what’s going on here.  In English:

If Chester’s door has just opened, and it’s dark enough to need lights and the balcony lights are not already on, switch on the balcony lights for 5 minutes.

Interestingly, the lights as in the picture were just too far away from the transceiver attached to the Pi to receive the signals reliably.  So there could have been the potential for one or both of the lights to stay on, even after they had been told to switch off.  To solve this, I used a LightwaveRF branded signal repeater, a really useful device that acts like a wifi repeater, but for home automation radio commands.

backbalc3

As for the balcony, it’s going to be great for summer.  But the cat might not be allowed on it as much as we’d hoped – within 5 minutes of her exploring her new space, I was prising her off the banister as she determinedly tried to fling herself off from the third floor.  I’ll have to think of a way that our home automation setup can prevent this!

DIY: Make a better handset controller

Although I like the look of the standard LightwaveRF hanset controllers, the user of said controller has to remember what device is switched on and off when a numbered button is pressed.  This requires Mastermind-level memory.

Besides, I don’t use the controllers for ‘On’ and ‘Off’ per se, rather just to send a signal to Domoticz, so that the computer can decide what to do (or to reject the command altogether).  This means that the same button can be used for ‘On’ and ‘Off’, and therefore the same handset can be used for multiple functions (lighting moods and audio for example).

So a way to make these controllers more intuative is to add personally created templates to them so that the controller becomes part of your home setup.  You can choose a theme and run with it (as shown).

Firstly, this procedure is reversible, so if you don’t like what you’ve done, you can undo it all and revert back to your original handset.  Just remember to keep all the bits that come off the controller safe.

Secondly, you will lose some functionality.  Because the switch is removed, you don’t have the ability to select button set A, B, C or D.  I personally don’t care about this because the whole reason I wanted to make a custom cover for my remotes was to make them as user friendly as possible.

And if your family can remember that C4 controls the TV power, and D2 controls the garage door, and B1 to B4 control the kitchen lights, then you shouldn’t be reading this blog: you should all be at Cape Canaveral getting ready to take off a-la-Lost in Space.  Danger, Will Robinson!

Basically, you’ll end up with 10 buttons per customised handset.

 

1. Peel off the backing sticker from the controller to expose a screw and unscrew it.

1

2. Prise open the controller.  The things that should come off (quite easily are: The front cover, the rubber keys, the switch (which may come off in one part or may split into the plastic part of the switch and the metal part).  And the screw of course.  If the circuit board has come off from the base of the remote then I think you used a little too much force!  Get you, butchy.

2

You’ll notice that the rubber buttons are not needed – the ‘pads’ you can see in the image are self-contained switches.  Like the ones you get on blister-remotes.

3. Design your overlay.  I will post a template that you can use (search for the ‘Templates’ tag).  Don’t forget to leave a space where the led will shine when a button is pressed.

I used icons from Flat Icon.

4. Print and cut out the overlay.  I found that good quality bright white matt card worked best.

You may need to cutoff tiny strips from any side to make the overlay fit correctly.

3

5. Put one or two layers of the same card underneath the overlay (between the keys and the overlay).  This will make the control pad seem more springy.

6. Tape on the overlay onto the front of the controller.  I used normal tape here but I should have used a thick tape so that I only needed to use 1 pass, rather than 3 passes as I have done in the above picture.

Make sure that you don’t tape up the drawer on the back, otherwise you’ll have probelms when it comes to changing the battery.

7. Voila!  The below example is for the kitchen.  That’s why there is a cute chef as one of the buttons: when you press the chef button, all the devices in the kitchen switch on.

4

8. Now it’s time to program what happens when you press the keys.  More on that elsewhere in this blog.

5

Here’s an example handset (this one is for my bedroom).  It’s been created in the same style as all the ‘hardware controllers’ in the flat, so that picking it up and using it should be second nature.

You can for once use your creative side and your geek side together for this project.  Why not speak to members of your family to get an idea of what they’d like to see on the controllers (favourite colours, family member/pet’s faces etc).  Maybe they could even design the templates for you!