Today, we’ll see how to control your lights at home in code

If you don’t know, Philips Hue is a smart lighting collection from Philips

An app on your smartphone allows you to switch them on and off, change intensity or colors

But as good DIYers, we’ll replace this app by coding our scenario on our Raspberry Pi 🙂

How to control home lights with Raspberry Pi?

To control lights at home, smart lights like Philips Hue are needed.

On Raspberry Pi, it’s possible to use the Python programming language to connect to the API, and manage the lights at home.

This is what we’ll do today

I’ll start by introducing the product, then the Raspberry Pi preparation, and finally we’ll see some code you can create to control your lights, from basic tests to more complex scenarios

Philips Hue

Philips

Philips is a well-known Dutch company.

It is a leader in many areas, including home appliance, technology and healthcare products

It’s a company driven by innovation, for example, it was the first to sell audio cassettes, CD or Blu-ray

They also are pioneers in a lot of others products, I’m thinking about the Ambilight technology on TV for example

But the main product that interest us today are the smart lights they created in the Philips Hue collection

Philips Hue collection

The Philips Hue collection includes all the smart lights from Philips

It’s a concept including bulbs, a bridge and an app to manage the lights

The bridge is the router between lights and your smartphone app

It needs access to your network (RJ45), and if possible to an Internet connection

The configuration is easy if you use a DHCP server on your network

is the router between lights and your smartphone app It needs access to your network (RJ45), and if possible to an Internet connection The configuration is easy if you use a DHCP server on your network Lights connect the bridge automatically in wireless

As soon as you switch them on, they are available on the app. No configuration

connect the bridge automatically in wireless As soon as you switch them on, they are available on the app. No configuration And the Hue app is available on your smartphone to manage all of this

Switch lights on and off, change colors, create routines

And what they don’t sell in the commercial ads is the API

There is a great API on the bridge, you can use to make what you want

And that’s what I’ll show you in this post

Models

If you don’t have a Philips Hue package at home yet, or maybe colored lights, you must know that there are severals models and packs available in the market

From the basic on/off white light to bulbs you can change their colors

Here are some recommended packages:

The starter kit, with 2 bulbs and the bridge. Perfect for a try (check it on Amazon)

The LED light strip (white and colors). Good for Christmas or a background ambiance (available here on Amazon).

And finally, the starter kit with color capacity (check the price on Amazon.com)

All of them are available with Alexa, and in some packs you can get an Echo dot

For starters kits you have the choice on how many bulbs you want

I have the two firsts at home since I’m happy with this for maybe five years now

Preparation

Before coding, you’ll need some preparation steps

Let’s check if everything is ready

Raspberry installation

The first thing to do is to prepare your Raspberry Pi:

Turn it on and install Raspbian if needed

You can choose any version, I’ll make this tutorial with the Lite version

If you need help on this point, check my article on How to install Raspbian on a Raspberry Pi

You can choose any version, I’ll make this tutorial with the Lite version If you need help on this point, check my article on How to install Raspbian on a Raspberry Pi Plug it to the network (or configure the WiFi), enable SSH

Update your system sudo apt update sudo apt upgrade

Choose an editor, install it if needed

On the Desktop version, you already have Thonny and the Python shell installed

On the Lite version, nano or vim should be enough

You can also create scripts on your computer and transfer them after on the Raspberry Pi (with WinSCP for example)

On the Desktop version, you already have Thonny and the Python shell installed On the Lite version, nano or vim should be enough You can also create scripts on your computer and transfer them after on the Raspberry Pi (with WinSCP for example) Install PIP to allow you to download libraries later sudo apt install python-pip

That’s all you need for the moment

Hue bridge

Then you need to find the Hue bridge IP address

If you have access to your Internet router or DHCP server, you may find it inside

If not, the easiest way is to scan the network

On Windows you can use Advanced IP Scanner to do this

But as the Raspberry Pi is ready, we can use it to find the bridge:

Install nmap with apt: sudo apt install nmap

Run this command: nmap -sP 192.168.1.0/24 Adjust the network to your own environment

You’ll get a list of all devices on the network

Find the Hue bridge inside



Find the Hue bridge inside That’s it, you found the bridge IP address (192.168.1.10 in my case)

Note this IP address, we’ll use it later

Configure lights

Make sure all your lights are already installed and configured in your smartphone app

Give them a name to find them easily

We’ll use this later

Install library

A library is a collection of functions to make something easier while coding

Instead of creating all the code ourself, we’ll use an existing library on GitHub: phue

As you probably guessed already, we’ll code in Python and phue is a Python library to help to use the Hue API in Python

If you prefer another language, this should be similar

I’ll give you libraries links for other languages at the end

So the last preparation step is to install phue on the Raspberry Pi

Do it with this command:

sudo pip install phue

That’s it, we’re ready to move to the coding stuff

API discovery

On your Hue bridge, there is an API available

The base URL is http://<IP>/api/v1

I’ll show you basic calls you can make, how it works, and after that we’ll create the first scripts

API introduction

If you are new in coding, an API stands for Application Programming Interface

The main goal is to allow devices or softwares to talk together, with the same language

In our case, the Raspberry Pi will talk to the Hue bridge, with Python making HTTP requests to get or change the Hue system configuration

So the Hue API give us HTTP functions to change things for the lights (like switch a light off for example)

As often, this API is protected with a user name we need to create before making any calls

(You may have seen the “unauthorized user” error if you tried the API base URL)

API tester

To test the API without coding, Philips gives us a tool to create requests in a form

This form is available at http://<IP>/debug/clip.html

In this form you’ll find three parts:

URL: The URL you want to call

You’ll see later that each function has a different URL

You’ll see later that each function has a different URL Method: GET PUT POST or DELETE

These are different actions you can make with your request

For example, GET is to see the configuration while PUT is to change something

These are different actions you can make with your request For example, GET is to see the configuration while PUT is to change something Message Body: For specific functions, you must add more details to explain what you want to change in the Hue configuration

Command Response: When you send requests, you’ll see the bridge’s answer in this field

This will help you debug your requests

Now that you understand what it is, let’s start by creating your user name

Create user

In most requests, we need an authentication to allow access to the Hue bridge configuration

To create your authentication token, fill the form like this:

URL: /api

Message Body {"devicetype":"TestApp#RaspberryPi"} Put what you want for the device type (app name or device as you want)

Then press the bridge button

Then press the bridge button In the following 30s, hit the POST button to run the query

This should look like this in the form:

In the “Command response” field, you can see the username generated by the Hue bridge

Note it, we’ll use it in all the next calls

List lights

Before changing the configuration in a specific room, we need to get the list of all lights installed

Get all lights

To get a list with all lights available, fill the form with this:

URL: /api/<username>/lights

Replace <username> by the one you got in the previous step (long random string)

Replace <username> by the one you got in the previous step (long random string) Then press “GET” to get the answer

The answer is in JSON format, not easy to read for a human being

You should see one paragraph by light

Each paragraph starts with a number (1, 2, 3, …) and contains all informations about the corresponding light

Try to find which number corresponds to which light

For example: 1=>Bedroom, 2=> LED strip, etc …

Later we’ll use only the ID, so you need to grab this information

Get one light

You can also get information for only one light

Just add the light ID at the end of the URL, like this:

URL: /api/<username>/lights/1

Method GET

This way, you make sure that the light 1 is the one you think

Switch a light off and on

Switch a light off

To switch a light off, use these parameters in the form:

URL: /api/<username>/lights/2/state

Message Body {"on":false}

Then click PUT

You should see the light switching off without using the smartphone app

Switch a light on

Then to put it back on, use exactly the same parameter

And change false to true in the message body

Sandbox finished, let’s move to the code part

First scripts

In this part I’ll show you some basic scripts, to learn how to use the API through the phue library

Switch the light on and off

Switch the light off

I give you the script directly and explain after:

Open your Python editor (Thonny or nano)

nano switch.py

Paste this code inside #!/usr/bin/python from phue import Bridge import logging logging.basicConfig() b = Bridge('192.168.1.10') # If the app is not registered and the button is not pressed, press the button and call connect() (this only needs to be run a single$ #b.connect() #Change the light state b.set_light(1, 'on', False) Replace 192.168.1.10 by your bridge IP address you noted previously

In the set_light function replace the first parameter by your light ID

Save and run it

In Thonny, click “Run” in the top menu

Or in a terminal, use: python switch.py

The first time you’ll get an error, because the script needs to create his own username (like we did in the API tester)

For this, you need to :

Comment out the b.connect() line

Press the bridge button

Run the script

Comment the line

Run the script again

The corresponding light should switch off

You only need to to this the first time, for all the following scripts, the user name already exists and the b.connect() line is not needed

Switch the light on

To not stay in the dark longer, we will turn on the light again 🙂

Basically, you only have to change one thing, replace false by true in the set_lights function

Here is the script you can use:

#!/usr/bin/python from phue import Bridge import logging logging.basicConfig() b = Bridge('192.168.1.10') b.set_light(1, 'on', True)

Don’t forget to replace the bridge IP address

Change the light color

You need a light with color capabilities to follow this part

If not, jump to the next one

Philips Hue uses two values: x and y, to define the color

You may have seen these values in the API tester

Basically, x and y are numbers between 0 and 1, and changing their values will change the light color

I’m not an expert but you’ll find information here on the official website to convert RGB colors to XY colors

For our test, we’ll just take random values and see what happen

Here is the code you can use to change the light color:

#!/usr/bin/python from phue import Bridge import logging import random logging.basicConfig() b = Bridge('192.168.1.10') b.set_light(1, 'xy', [random.random(),random.random()])

It’s the same code than before, but instead of changing the “on” setting, we play with the “xy” values

The random function returns a number between 0 and 1, perfect in this case

You use the same “set_light” function to change other parameters you’ve seen in the API tester, like the brightness or the saturation

But now that you understand the basics, we’ll move to more complex scenarios

Scenarios

In this section, I’ll give you an idea of what you can build with this API, Python and your Raspberry

There is no limit to what you can do, just find an idea and try to code it

Light schedule

We can build a time schedule for the light

For example, to switch them on just before you come back home or wake up

In the smartphone app this is available in the “Routines” tab

But we’ll build it in Python

See current routines

The base API URL for routines is: /api/<username>/schedules

You can call this URL with the GET method to see your existing routines in the API tester

You’ll get a JSON with all the routines, and for each one the configuration you made

You can also see them in a more intuitive way on your phone

It’s maybe the easiest way to check if the routines created with the script are correct or not

Create a routine

To create a routine, you need to POST data to the same URL

Here is one example:

#!/usr/bin/python from phue import Bridge import logging logging.basicConfig() b = Bridge('192.168.1.10') data = {'on': True, 'transitiontime': 600} b.create_schedule('Wake up', '2019-05-01T07:00:00', 1, data, 'Wake Me Up' )

In this script, we ask the API to create a routine called “Wake Up”

This routine will switch on the light with ID 1 at the specified date

You should now see this routine on your smartphone (Routines > From other applications)

Or you can check again with the API tester

There is no point in doing this if you have the app on your smartphone

But you can include this piece of code in a larger program

If you have a weekly planning with different wake up times, changing every week, it will be hard to do this with your phone

But in your Python code you can import a CSV file with the wake up time for each day, or even connect to a web page to update the wake up time for tomorrow

You make the code one time and don’t have to do anything after that

Just an idea … let’s move to the next one 🙂

Playing with colors

We saw before how to set the light color if your bulb can manage this

With the power of Python you can create animation unavailable in the smartphone app

For example, we could change the color automatically and gradually every minute

I will start with something easy but not the prettiest

And then we’ll see a more complex code to change the color step by step

First try

In a previous paragraph, I wrote that the color of the Hue bulbs is defined by two values : x and y

In order to change the color gradually, the first try could be to increase this value bit by bit

For example, starting at 0/0 and increasing one value by 0.01 every minute

Let’s make a try:

#!/usr/bin/python from phue import Bridge from time import sleep import logging logging.basicConfig() b = Bridge('192.168.1.10') x=0 y=0 while True: x = x+0.01 if x>1 : x=0 print(x) b.set_light(3, 'xy', [x,y]) sleep(1)

I import sleep from the time library to wait one second between each change (you can set another wait time, but for the try one second is ok)

from the time library to wait one second between each change (you can set another wait time, but for the try one second is ok) Then I define my two values : x and y, initialized at 0

To make the light change color forever, I need to create an infinite loop ( while True )

) I increment the x value from 0.01 each second and make sure that it stays between 0 and 1

I display the value in the output to monitor if everything goes well

Finally, I set the light to the current x and y values (set_light), and wait one second (sleep)

Run the script and see what happens

You should see your bulb or strip start with a blue light, then passing from purple to pink, and finally going red

Try to change the y value to see which colors you get, or even change the two values at the same time

The result is cool but not perfect.

We don’t go through all possible colors and at the end of the loop we are going from red to blue without transition

Can we create a better script? Yes absolutely

First improvement

To avoid switching from red to blue without transition, you need to have your value going from 0 to 1, and then from 1 to 0

To do this, for each iteration, you need to know if the direction is an increment or decrement

And change the direction when you reach the limits (0 or 1)

Here is how I made this code:

#!/usr/bin/python from phue import Bridge from time import sleep import logging logging.basicConfig() b = Bridge('192.168.1.10') x=0 y=0 direction="inc" while True: if direction=="inc": x = x+0.01 if x>=1 : direction="dec" else: x = x-0.01 if x<=0: x=0 direction="inc" print(x) b.set_light(3, 'xy', [x,y]) sleep(1)

Now, if you run the script, the color will go from blue to red as before, and then from red to blue gradually

It’s better but we still don’t have all the colors

To improve this, you need to understand what are these x and y values, and how they work

Can you do better?

Here is the representation of x and y values with the corresponding light color (source: Wikipedia)

As you can see, it’ll not be easy to move through all possible colors

My only idea was to use an array with some points defined manually in your favorites color

And then to set these colors step by step

I had another idea: convert hexadecimal colors code (#123456) to the corresponding XYZ value

And there is a Python library to do this

To install it, use this command:

sudo pip install rgbxy

And then you can use functions like converter.hex_to_xy(‘12345‘) to get the xy value from the hex value

You’ll find all the functions here

But I don’t find how to cycle through all the colors gradually

So it doesn’t help me

If you have a better way to do this, share your ideas in the comments below

Use an external API

The last scenario I want to introduce, is to use an external API

For example, you can get sunrises and sunsets times from an API, and plan to stop the light when the day comes up

If you want an anecdote, I remember I created a script to set a specific color depending on the numbers of players on my Minecraft server in real time

For example, white if empty, green up to 10, orange up to 20 and red over 30 players

It’s an idea, but you can adapt it to your specific point of interests

It’s funny and easy to make

Other languages

If you prefer to code with other languages, I want to give you the main libraries I found for the main languages

PHP : https://github.com/sqmk/Phue

I like to use PHP, especially to work with others API

: https://github.com/sqmk/Phue I like to use PHP, especially to work with others API NodeJS : https://github.com/peter-murray/node-hue-api

: https://github.com/peter-murray/node-hue-api JavaScript: https://github.com/blargoner/jshue

On a Raspberry Pi, Python or PHP should be enough for a standalone script

But it depends where you want to include it, or if you use others API

Conclusion

That’s it! You know how to control your lights from a Raspberry Pi, thanks to the Philips Hue system

It’s difficult to start, but when you understand the basics, you can build what you want in a few minutes

If you need more information, check the Philips Hue Developer website to learn other tips

Let me know what you build with your Raspberry Pi and Philips Hue, you can share it with us in the comments

And also if you have problems with it, we can try to help you