Tag Archives: Philips Hue

Philips Hue in partnership with The Voice UK will bring the studio into your living room

I don’t think I have ever been more excited about Philips Hue, and that is saying something as I am a great lover of the whole range of products.

In January ITV (the UK television network) announced that during later stages of The Voice UK, the companion app will control connected Hue devices and sync them to the stage lighting.  This means in effect that the lighting director will not only be controlling the stage where the contestants sing, but also the lights wherever you are watching.

I have downloaded the app in anticipation and have selected the lights I want to be controlled during the live performance, and also tested the setup via a short sample video supplied in the app.  If the live shows sync up as well as the sample video did, I can only tremble with anticipation before the live head-to-head shows begin.

THIS is what we have been waiting for.  Ambilight and the projection version of Ambilight from Philips proved that extending the lighting effects beyond the visible window you can see on television creates a much more immersive experience.  This new innovation (similar – but possibly an evolution of – the SyFy Sync app)  brings us one step closer to all action/music/performance programmes having “light encoding” similar to the way subtitles are currently saved alongside video.  I cannot wait to see this in action: Philips, if you are reading this and you need a “real” home to preview The Voice integration: pick me!

Advertisement

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!”

 

 

Syncing your Hue lights to Sonos – part 2

I successfully built a program to sync up Phillips Hue lights with Sonos in this post.  Unfortunately the Echonest API is no longer in use and I have run up to difficulties with authorising the replacement Spotify API (any help with that is gratefully received!).

I’ve also always fancied myself as a lighting technician and the responsiveness of the Hue lights got me thinking that there might be a way to sync my lights to a specific track or a bunch of tracks.  Imagine a party where the lights “do their own thing” until a track comes on that is recognised, and then the lights sync up in exactly the way you have programmed them.

I wanted to make the program do as a minimum the following:

  • Have a “default” setting where the lights change in a generic but random way
  • When a track starts, to detect that the track has “light cues” associated with it and to start playing the light cues alongside the track
  • To be synced to the second, so that the lights always “keep up” with the track
  • To be able to “join in” and catch up with the track, even if it is paused or rewound (completely or partly)

The attached files are small, and are by no means polished, but they do the job and the program can run all night successfully changing between “I don’t know this song so I’ll just do a random light show” to “Oooh! I know this song, let me load up the light cues and join in!”.

There are two parts: and Excel spreadsheet where the lights are encoded, and a small python program that is run to manage the current playing track and loading of the associated light cues if they exist.

This program also relies on the node-sonos-http-api code by Jishi available here (https://github.com/jishi/node-sonos-http-api)  with installation instructions mentioned in my previous Hue/Sonos post.  This node program should be running (it always is on my Raspberry Pi as I use it to control all Sonos throughout the flat using HTTP commands).

The Excel spreadsheet:

The spreadsheet is a macro-enabled spreadsheet that allows you to create, load, edit and save light cue files (saved as *.lig files).  Simply open the spreadsheet and listen to your music.  When you come to a part of the music that deserves a light change, you go to that line and then choose a function and type in some numbers.

At the top of the spreadsheet, type in the name of the track you want to set up a light cue datafile for.  Enter the whole location of the file but without any extension.  For example, if the track is called Like a Cat, and you want it to be saved in your C:\Users\Sample\Documents folder, in cell C5 type in C:\Users\Sample\Documents\Like a Cat

A word of caution here: run the program and change the Sonos to the track you want to encode first.  The program will show the exact name of the file it is looking for.  In order to simplify the program, it strips out brackets and hyphens, as well as commas and full stops (periods).  You may therefore end up with a track name that has a few extra spaces in it, so look out for that.

In cells C9 to L9 enter the reference numbers of each light you want to use in this song.  You can use all available lights or just some.  You don’t have to select the same lights for each song, but remember if one known song comes on after the other, some lights may remain as you left them in the first song if you don’t include them in the second song’s list.

In cell C11 enter the group number of the Hue lights you want to control.  This is useful as some of the light cues you can use address the whole group rather than individual bulbs in sequence.  You can set groups using the Hue API.

Listen to a song and then work out in your head what would be a good lighting effect.  Maybe you’d like each bulb to flick between strong random colours every 2 seconds, or maybe you want a low orange glow on all lights until the chorus, and then raise up the lights to a vivid red, maybe making them flash at just the right moment.

For each song you can enter as many or as few lines of light cues as you like, even just one at the beginning of the track, to change the lights to match the mood of the music for the whole song, or maybe an epic display matched perfectly to each bar.

Functions available are:

ALLSET which changes in sequence each light you have specified to use

CHGALL which changes the whole group of lights instead of each individual light

FLASH which pulses the lights either once or twice (depending on how fast your host machine is)

INDIV which controls one individual bulb (enter this in the Lightref/delay column). If you want to change 2 bulbs together just put two INDIV lines together, one after the other, a second apart.

ALLBRI ignores a lot of the variables supplied and just changes the whole group of lights to a specific brightness

ALLOFF and ALLON switch the whole group of lights off or on, at a transition time you specify

CHGSEQ changes each light sequentially, just like ALLSET, but waits a certain number of seconds you specify (enter this in the Lightref/delay column)

How to write a light cue line:

First choose what you want to do.  Let’s say in the very first second of the track we want to bring up all the lights to a dark, moody red colour.  Enter the following line.

hms1

I want to force the lights to one specific colour, so I have entered the same number into MinHue and MaxHue so that I am sure that colour 0 (red) will be chosen.

Then we want to spring into vibrant colours which change every 10 seconds, from the 15th second of the track.

hms2

Notice this time I have set MinHue to 0 and MaxHue to 65000 – this gives a good range of colours, in fact the whole spectrum.  I set MaxSat and MinSat to 255 as I don’t want to mix the colours with any white.  The closer you get to 0 for Sat, the more white is mixed in with the colour.  I have set TransTime to 10 because I want them to change over the period of 1 second.  I could have put 5 or 1 in there if I wanted a faster or instant response.  There is some randomness between the brightness too, from 100 (mid-dim) to 255 (bright).

I then copy this line from column D to column L and then paste into 25 seconds, 30 seconds, 35 seconds and so on.

When I get to the end of the song I just finish.  Nothing else to do unless you want to add some other flourishes.  Let’s go back to 2 minutes and 24 seconds, as there is one enormous drum solo that starts there and I would like to put pulsing white lights for 10 seconds.

hms3

Now just click the Export button at the top.  Excel won’t reportanything (I told you it wasn’t finished) but the light cue file will be saved in the location and with the name you specified in cell C5.  Make sure it has shown up.

You can quickly build up quite a catalogue of “*.lig” light cue files.

When done, copy these files to the location where you’ll be running the python program (oh, you’ll need to create or download one called “default.lig” which is the file that the program will open if the track playing does not have its own file).

Inside the python program change 192.168.1.94:5005 to the address of the server that is running for node-sonos-http-api (the address where server.js is running) and then change the Sonos zone name from “Living%20Room” to the one that will be playing the music.  If you want more than one player to play music (at a party for example) make sure the player you specify here is the “main” player and additional speakers are grouped to it.

Run the python program (in python 3) and you’ll see it start to wait for the Sonos player to start playing something.  Play one of the songs you have created a light cue file for and make sure it opens.  If it does, you’ll enjoy the fruits of your labour! If not, first check what file the program was actually looking for (each title is printed out by the program when the Sonos player changes track).

I hope you enjoy this small program and light cue creation spreadsheet.  Please let me know how you’d improve it or if you use it!  Thanks as always for your comments, they keep me writing these posts.

Downloads

Take off the “.doc” extension before using – WordPress does not allow me to upload *.py, *.xlsx or my own *.lig files.

hms.py

Default.lig

Hue Music Encoder 2.xlsm

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.

Hue Go

My latest purchase is a Hue Go.  It’s a rechargeable (and therefore totally mobile) version of a Philips Hue bulb, encased in a bowl shaped frosted enclosure.

After a 1 and a half hour charge the light is good to go for 3 hours.  There’s a build in ‘bulge’ stand to allow for it to be pointed towards a surface, like the Iris or the Bloom.

What makes the light more usable for the whole family is that there’s a button on it to cycle through moods and colours, and to switch the light on or off.  The moods include such campness as Warm white, Cozy candle and Night adventure (which has a pink hue and a heart icon, I wonder what that mood is for…)

I like it, and think it’s going to make a great addition to the 20 or so Hue lights we already have.  For one thing, it can be moved in the dry to a balcony table – perfect for the approaching summer nights.

bowl2From a home automation point of view, there may be issues with having the light in ‘mobile’ mode, i.e. unplugged.  According to the literature, the light switches from ‘standby’ to ‘off’ after 2 hours of inactivity when in battery mode, so I’m guessing that means even if an ‘on’ command is sent, it won’t respond until either plugged in again or the button is pressed.  Obviously this is a fail-safe to ensure the battery does not drain completely.

£80 puts the Hue Go at the same price point as the Lightstrips, and I can see why.  It’s well made and even looks pretty when in standby mode.  I like the modern, ‘glossy glass’ look of the front panel and this continues even to the back where the understated function button resides.

The pros far outweigh the cons though, especially as after testing the Hue Go with the homemade disco controller I made, it is very responsive to commands even when in battery mode.

The brightness and saturation (although not seen well in these pictures) is as expected for a Hue product – read: amazing,

The literature seems to suggest that on battery mode, the brightness is reduced to extend battery life.  I can’t say I’ve noticed that, unless they mean that when displaying the pre-set moods that feature is enabled.

The charging cable (reminiscent of a cable for the Living Colours lamps) looks strong enough to be plugged and unplugged regularly.  The charging port on the unit itself is also recessed quite a distance which is good for protection purposes.

bowl3

Overall, a great product and another reason to get excited about Hue!

Homemade disco using Sonos and Hue

I’ve used Hue Disco and other apps to sync up my Philips Hue lights with my music, but what I really wanted was something that I could start during a party, and just leave to get on with it.  I wanted the lights to change reasonably often, but I wanted them to respond to the type of music being played.

This program is written in Python 3 and uses the Echonest database to get the energy and danceability, as well as the tempo of the currently plying track from the Sonos player (obtained by this great program: node-sonos-http-api.  The program then selects a brightness and saturation range and randomly changes all the hue lights you specify.  The lights change in a frequency relating to the tempo of the track playing.

The program must be started AFTER you’ve started playing a track on the Sonos, and then continuously runs until you pause the Sonos player, and then raises the lights to a medium white light, and then the program quits.

I’ve got this program running on my Raspberry Pi, and am really pleased with it, obviously more tinkering can be done, but I’ve not seen any similar apps that do this.  I have a Domoticz ‘switch’ that can start running this program, and then to end the program, you just pause playback.  But you could just run the program from the command line each time you want to have a disco!

Best used when you have a night of partying, with a large random playlist going.  Don’t forget that as long as the player you specify in the variables is part of the playing ‘group’, you can play music to different rooms and include those Hue bulbs into the list too!

You can download the code here: Hue-BR-Analyse

Here’s the code:

import urllib
from urllib import request 
from random import randint 
import base64,requests,json,time,datetime

"""
Hue Sonos Analyser by Harry Plant 2015

This program changes the hue, brightness and tempo of Philips Hue lights depending on the energy and danceability of the track,
as reported by Echonest.

Requirements:

*Philips Hue bridge and at least one Hue Light (http://www2.meethue.com/en-gb/)
*At least one Sonos player (http://www.sonos.com/)
*Python 3 (I have it installed on my Raspberry Pi)
*Echonest api key (obtainable at https://developer.echonest.com/ - click 'Get an API Key')
*node-sonos-http-api (https://github.com/jishi/node-sonos-http-api)

change the following variables to match your setup:

zone is the name of the sonos player you will be listening to
my_list is an array of the hue lights you want to control
sonosinfo is the address of the node-sonos-http-api server
hue_bridge is the address and key that you use to control the hue
echonest_apikey is the key you obtained from echonest

I have used this program with success (great parties) on multiple occasions but do not accept 
responsibility for any loss or damage caused by using this code.

"""

zone = 'Kitchen'
my_list = ['3', '4', '5', '7', '15', '17', '19', '20']
sonosinfo = 'http://192.168.1.100:5005/'
hue_bridge = 'http://192.168.1.101/api/newdeveloper/'
echonest_apikey = '02MKNPMXXXXXXXXXX'

"""
MAIN PROGRAM BELOW, YOU DON'T NEED TO CHANGE ANYTHING FROM HERE
"""

currenttrack = 'No track'
min_bri = 100
max_bri = 100
secs_waited = 0
secs_to_wait = 10
sat = 100
tt = 10
trackfound = 1
std_assumptions = 0

for r in range(1,999999):
 
 secs_waited = secs_waited + 1

 req = request.urlopen(sonosinfo + zone + '/state')
 encoding = req.headers.get_content_charset()
 obj = json.loads(req.read().decode(encoding))
 """
 print(json.dumps(obj,indent=4))
 """
 if obj['zoneState'] == 'PAUSED_PLAYBACK' or obj['zoneState'] == 'STOPPED':
 print('Player has stopped playing. Returning lights to white and exiting program.')
 my_list_len = len(my_list)
 for i in range(0,my_list_len):
 hue = 10000
 bri = 200
 sat = 50
 tt = 50
 payload = '{"on":true,"sat":' + str(sat) + ',"bri":' + str(bri) + ',"hue":' + str(hue) + ',"transitiontime":' +str(tt) + '}'
 """
 print(payload)
 """
 r = requests.put(hue_bridge + "lights/" + my_list[i] + "/state",data=payload)

 req = request.urlopen('http://192.168.1.94:8080/json.htm?type=command&param=switchlight&idx=252&switchcmd=Off')
 exit()

 track = obj['currentTrack']['title']
 artist = obj['currentTrack']['artist'] 
 elapsedtime = obj['elapsedTime']
 playing = obj['playerState']

 if track == currenttrack:
 """
 print('Waited ' + str(secs_waited) + ' out of ' + str(secs_to_wait))
 """
 if track != currenttrack:
 std_assumptions = 0
 print('This is a new track!')
 print('Now playing : ' + track + ' by '+ artist + ".")
 requeststring = 'http://developer.echonest.com/api/v4/song/search?api_key=' + echonest_apikey + '&format=json&artist=' + urllib.parse.quote(artist) + '&title=' + urllib.parse.quote(track)
 """
 print(requeststring)
 """
 req = request.urlopen(requeststring)
 encoding = req.headers.get_content_charset()
 obj = json.loads(req.read().decode(encoding))
 """
 print(obj)
 """
 if not obj['response']['songs']:
 std_assumptions = 1 
 print('Song not in database - using standard assumptions')
 
 if std_assumptions == 0:
 songid = obj['response']['songs'][0]['id']

 """
 print(songid)
 """

 requeststring = 'http://developer.echonest.com/api/v4/song/profile?api_key=' + echonest_apikey + '&id=' + songid + '&bucket=audio_summary'
 """
 print(requeststring)
 """
 req = request.urlopen(requeststring)
 encoding = req.headers.get_content_charset()
 obj = json.loads(req.read().decode(encoding))
 if not obj['response']['songs'][0]['audio_summary']:
 print('Although song was in database, there is no energy and danceability data. Using standard assumptions for this track.')
 std_assumptions = 1

 if std_assumptions == 0:

 print(obj)
 
 dancepercent = int((obj['response']['songs'][0]['audio_summary']['danceability'])*100)
 energypercent = int((obj['response']['songs'][0]['audio_summary']['energy'])*100)
 pulserate = obj['response']['songs'][0]['audio_summary']['tempo']
 print('Danceability is '+str(dancepercent) + '% and energy is ' + str(energypercent) + '% with a tempo of '+str(pulserate) +'bpm.')
 currenttrack = track

 if std_assumptions == 1:
 
 dancepercent = 50
 energypercent = 50
 pulserate = 100
 print('Danceability is '+str(dancepercent) + '% and energy is ' + str(energypercent) + '% with a tempo of '+str(pulserate) +'bpm.')
 currenttrack = track

 if pulserate &lt; 100:
 secs_to_wait = 20
 tt = 20
 
 if pulserate &gt; 99 and pulserate &lt; 120:
 secs_to_wait = 6
 tt = 10
 
 if pulserate &gt; 119 and pulserate &lt; 160:
 secs_to_wait = 4
 tt = 7

 if pulserate &gt; 159:
 secs_to_wait = 2
 tt = 5
 """
 
 secs_to_wait = int((pulserate/60)*2)
 """
 if energypercent &lt; 20:
 sat = 50
 
 if energypercent &gt; 19 and energypercent &lt; 40:
 sat = 100

 if energypercent &gt; 39 and energypercent &lt; 60:
 sat = 120

 if energypercent &gt; 59 and energypercent &lt; 80:
 sat = 170 

 if energypercent &gt; 59 and energypercent &lt; 80:
 sat = 200

 if energypercent &gt; 79:
 sat = 255

 if dancepercent &lt; 20:
 max_bri = 60
 min_bri = 40
 
 if dancepercent &gt; 19 and dancepercent &lt; 40:
 max_bri = 100
 min_bri = 80

 if dancepercent &gt; 39 and dancepercent &lt; 60:
 max_bri = 150
 min_bri = 80

 if dancepercent &gt; 59 and dancepercent &lt; 80:
 max_bri = 200
 min_bri = 50 

 if dancepercent &gt; 59 and dancepercent &lt; 80:
 max_bri = 255
 min_bri = 50

 if dancepercent &gt; 79:
 max_bri = 255
 min_bri = 10

 print('Changing hue lights now.')
 my_list_len = len(my_list)
 for i in range(0,my_list_len):
 hue = randint(0,65000)
 bri = randint(min_bri,max_bri)
 payload = '{"on":true,"sat":' + str(sat) + ',"bri":' + str(bri) + ',"hue":' + str(hue) + ',"transitiontime":' +str(tt) + '}'
 """
 print(payload)
 """
 r = requests.put(hue_bridge + "lights/" + my_list[i] + "/state",data=payload)
 secs_waited = 0
 
 if secs_waited &gt;= secs_to_wait:
 print('Changing hue lights now.')
 my_list_len = len(my_list)
 for i in range(0,my_list_len):
 hue = randint(0,65000)
 bri = randint(min_bri,max_bri)
 payload = '{"on":true,"sat":' + str(sat) + ',"bri":' + str(bri) + ',"hue":' + str(hue) + ',"transitiontime":' +str(tt) + '}'
 """
 print(payload)
 """
 r = requests.put(hue_bridge + "lights/" + my_list[i] + "/state",data=payload)
 secs_waited = 0

 time.sleep(1)
 



Are Hue serious?

I cannot overstate the impact that equipping the flat with Philips Hue lights has had.  These seemingly innocuous light bulbs behave much like any other.  You can switch them on and off at the wall like normal bulbs, but the magic happens when you command them to change colour, brightness and saturation via the Philips Hue app, or like me via a direct command to the Bridge via a http request.

The Bridge is a puck-shaped device that you plug into your router and this then communicates with all the bulbs within its radio-range.  For bulbs that are too far away from the Bridge, the message is communicated through all available bulbs.  This way a command can reach all the way through a large house (or comfortably through a small flat like ours).

Flap1

Here’s the Hue Bridge (the circular device with the blue lights).  You can see that I’ve found a cool place to tidy away all my home control devices: in the empty space previously occupied by a obsolete hot air heating system vent.  The Hue Bridge shares its home with a Hive controller, a Sonos Bridge and a LightwaveRF Link.  All devices are out of view until I need to look at any of them.

The Philips Hue App vs. direct control

The app itself is not great, purely because it takes a while to load up, and I don’t like the way that it behaves.  I think the app was not designed for someone like me, who wants to press one icon and get the lights exactly how I want them.

hue-bathroom1

A rather extreme example: how lighting can change the atmosphere within a split second (don’t worry, our bathroom isn’t often that pink!)

Direct control (http request) is the best way to control Hue as far as I am concerned.  I do away with the app altogether and use the control pads throughout the flat.  This incidentally was before Philips brought out a new device that can do this – the Hue Tap.

Basically, the pad is pressed to select a colour, this sends a radio signal which is picked up by the transciever attached to the Raspberry Pi.  Domoticz acknowledges that the button was pressed, and then sends an appropriate request or requests to the Philips Hue Bridge via the network.   I say requests because you can send as many commands in one go as you like, up to about 10 per second.

You can get a list of all the commands you can send to the Bridge, as well as how to set up the Bridge to accept these commands at the Philips Hue API site.

Speaking to the Pi

putty

I use Putty to connect to the Raspberry Pi, so that I don’t need to connect a screen and keyboard to the Pi.  I just fire up Putty from a computer on the same network and then use that computer’s screen and keyboard to control the Pi.  Read the installation instructions (and the legal information) before installing Putty.

Once you have launched Putty, enter the network address and port of the Pi into the boxes, and click connect.

puttylogon

You’ll then see a login screen.  Enter the login credentials as supplied by the place you downloaded the Raspberry Pi image from (I got my image from the Domoticz website – use the Raspberry Pi file.  More instructions available here).

puttyscreen

You’ll then be able to change the folder you are looking in to domoticz.

Type cd domoticz and press enter.

pi@domoticzpi ~/domoticz $

will be displayed.

That’s it!  You’re connected to your Pi and you can command it from any computer with Putty installed on your home network.

The bits and bobs what we have

Here’s a starter for 10.  An initial list of the items I’ll be talking about on this blog.  This is not exhaustive, even though I feel exhausted writing this down!

We’ve collected these various disparate systems over the past few years.  It’s my job to make them speak to each other.  Like some kind of flamboyant interpreter at an important European parliament discussion.

Sensors

3 x Oregon Scientific thermo/hygro sensors to monitor temperature and humidity throughout the flat, and outside on one of the balconies.  They send messages to the computer, roughly once a minute, giving up to date temperature and humidity data.  They also include in the message, a request for batteries to be changed.  That’s polite, isn’t it?

Available from: John Lewis

4 x LightwaveRF door sensors to determine if doors in the flat are open or closed – these send one signal when the contacts are moved apart – door open, and one signal when the contacts come back together – door closed. Open, closed.

Website: LightwaveRF

3 x LightwaveRF PIR sensors. These send out a signal when they detect movement, and then another signal when there is no longer any movement.  You can set how long the sensors wait before checking if there is no movement by selecting a time period using a switch on the back.  This can be from 5 seconds, to 10 minutes.  To literally never.

Website: LightwaveRF

Plugs

10+ LightwaveRF plug-in units.  These units do one of two things, depending on which ones you buy.  One type is ON/OFF which means that a signal is received and then ‘ping’, the device you’ve plugged in comes on.  Used for things like TVs or Microwaves.  The other type is DIMMER which means that not only does the device plugged in switches on and off when a command is received, but also that the device can dim from between 0% and 100% brightness.  Or it should go down to 0%, but doesn’t.  More on that in another post.  You really should not use dimmer switches to control the power level of a Microwave.

The plug-in units are really, really useful, and they were especially so when we rented, because they can be removed from a plug socket when you move, instead of frantically tugging out every electrical outlet in the last 5 minutes of your tenancy.

Website: LightwaveRF

1 x Belkin WeMo plug-in unit. I bought this from Maplin as an impulse buy, as it links with another recent purchase, my Ivee Sleek.  I’ll be doing interesting things with both of these items in the coming weeks.  Mainly when Ivee becomes more than a fancy alarm clock that chirps up randomly whilst you’re watching television.

Lighting

20140706_163537We have 17 Philips Hue bulbs and lightstrips in the flat.  These are what really shook up the home control thang, and made our lives better, more relaxing, and simpler.  Quite simply these are the best home control things I have bought.  Not only do they look good, they also behave 99% of the time, and they can be controlled from practically any computer program.  This is the holy trinity as far as home control goes.  Honestly, I can’t say too many good things about Philips Hue.  More gushing to come.

Where it is physically impossible to get Philips Hue bulbs, we have LEDs.  So the flat is very nearly 100% LED lit.  There are three exceptions in the kitchen where LEDs cannot be used at the moment.  Damn you, kitchen!

We also have a few LED downlighters that can be controlled by the LightwaveRF signals.  These are cute and can be used under shelves to create mood lighting.  The only downside is that they go through AAA batteries like our cat goes through litter.

Heating and Environmental Controls

We have an app-controlled heating system called Hive.  You can control the heating from wherever you can get online with your phone (which means everywhere).

Any flat can get problems with high humidity, so we have a dehumidifier.  It’s quite a cheap one, but I’ve made it very intelligent.  It only comes on when necessary, and only when we’re home.  I’ll blog about that some time.

We also have an air purifier which is also similarly automatically controlled.  The air purifier has a lovely colour changing effect and belches out lavender fragrance.  This is nothing to do with home control, but is very much to do with my other hobby, which is being incredibly and breathtakingly gay.

Controllers

To ensure we can ‘talk’ to the flat, we need to have some kind of way to speak to it.  I can go in and change the code in my control programs, but that isn’t very easy to do for many users, so a pretty looking button or a screen is a good way of doing this.

Many of these controllers are supposed to be ‘paired’ with a specific device to switch them on or off.  I shun this concept as amateurish.  I ‘pair’ the controller with the computer, so that the computer decides what to do when it receives a signal from the controller.  More on this later in the blog.

pad4 x LightwaveRF wall mood switches are used throughout the flat to control lights and moods in various rooms.  These are useful because (a) you can stick them anywhere – so you can place them where a light switch would normally be, and (b) because they are always there.  It’s one thing having a smartphone controlled flat, but what if you don’t have your smartphone with you and all you want to do is turn on a light!  Cue this.

The mood switches have 6 ‘pads’ to press.  Two large ones, marked 1 and 0, and four smaller pads, marked with symbols ‘-‘, ‘–‘, ‘—‘ and a standby icon.

The mood switches are good, and look great, but they have very generic markings on them.  I’ve overlaid a printed design on top of them so that users can tell what will happen when a button is pressed.  The switches also have a delightful blue LED which charmingly illuminates to confirm that a signal is being sent.

4 x LightwaveRF handset controllers.  These are hand-held controllers, comprising of 10 buttons and a four-way switch.  8 of the buttons send out unique signals which change depending on the position of the switch, therefore there are 8 x 4 = 32 unique signals.  The other two buttons send out the same signals regardless of the position of the 4-way switch.  Therefore there are 32 + 2 = 34 different signals that can be sent out from these controllers.  I am no Carol Vorderman but Excel tells me that I’m correct.

Sony Tablet S in charging dock.  This is a pretty standard android tablet which is always standing in its charging dock.  It makes controlling the flat easy, as long as you’re in the living room and you have fingers.  The above controllers are used elsewhere.

Ivee

Ivee was so exciting before I bought her.  She literally took months to enter my life, I was counting the days from when I ordered her from Maplin.  Ivee is supposed to be an always-listening voice-controller for your connected devices.  As it is, I can try and ask her “Hello Ivee.  Turn on the bathroom lights.” and she’ll respond with the phrase “The time in Handsome Eddy, New York, is 12:50am”.

I’m sure she’ll get smarter.

Smartphones.  This one is a no-brainer.  It’s also very impressive to show people.  “Hey, look at this.  I can switch on the fan in my living room from here in the office”.  And then they usually say something like “I’ve left something on the photocopier” and leave.  Quickly.

Audio

20150111_215333We have Sonos everywhere.  Literally everywhere.  As the flat is quite small, we have 3 PLAY:1 speakers, a CONNECT (for broadcast to the bathroom), and a PLAYBAR which is a stereo and a TV soundbar all rolled up in one very “I may look like a draught excluder but actually I cost twice as much as the TV I’m under” package.

The Sony tablet in the living room, and our smartphones can control the Sonos, as well as any of the handsets affixed throughout the flat.

The Brain

The brain of the whole crazy outfit is a teeeeeny tiny little computer called a Raspberry Pi.  This computer, the size of a pack of cards, is useful because it doesn’t use a lot of power (so you can leave it on all the time) and it’s reliable.  I use a program called Domoticz to run everything.  A heck of a lot more on this particular set up later.

The interesting thing about home control is that it can be as simple or as complex as you want to make it.  You can decide ‘I want a lamp in my living room to come on when it gets dark outside’ or ‘I want the flat to email me when the humidity gets stupidly high in there’, or ‘sound an alarm and email me when we’re supposedly out of the flat and a door is opened or a movement sensor is activated’.

With a bit of playing around, the world is your oyster.  Or your home is your servant.