philips hue api raspberry pi python

Raspberry Pi: How to control lights at home? (Philips Hue)

Today, we’ll see how to control your lights at home in code. If you don’t know, Philips Hue is a smart light collection from Philips. An app on your smartphone allows you to switch the lights on and off, and change intensity or colors.
But as good DIYers, we’ll replace this app by coding our scenario on our Raspberry Pi :).

To control lights at home, smart lights like Philips Hue are required.
With a Raspberry Pi, the Python programming language allows you to connect to the lights API, and manage them with a script.

This is what we’ll do today!
I’ll start by introducing the product, then the Raspberry Pi preparation, and finally we’ll learn some code you can create to control your lights, from basic tests to more complex scenarios.

If you’re looking to quickly progress on Raspberry Pi, you can check out my e-book here. It’s a 30-day challenge where you learn one new thing every day until you become a Raspberry Pi expert. The first third of the book teaches you the basics, but the following chapters include projects you can try on your own.

Philips Hue

Philips

Philips is a well-known Dutch company.
It is a leader in many areas, including home appliances, technology, and healthcare products.

It’s a company driven by innovation. It was the first to sell audio cassettes, CD and Blu-ray.
They also are pioneers in a lot of other products, such as the Ambilight technology on TV (that you can simulate by using Hyperion on Raspberry Pi).
But the main products 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.

Philips hue collection
  • 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.
  • Lights connect the bridge automatically in wireless.
    As soon as you switch them on, they are available on the app. No configuration needed.
  • And the Hue app is available on your smartphone to manage all of this.
    You can switch lights on and off, change colors, and create routines.

And what they don’t sell in the commercial ads is the API.
There is a great API on the bridge that 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 several models and packs available in the market.
From the basic on/off white light to bulbs where you can change the color.

Here are some recommended packages:

All of the packages are available with Alexa, and in some packs, you can get an Echo dot.
For starters kits, you have the choice of how many bulbs you want.
I have had the two first packages at home for maybe five years now. I am happy with the product!

Preparation

Before coding, you’ll need to prepare a couple of things.
Let’s check if everything is ready first.

Raspberry installation

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

  • Turn on your Raspberry Pi and install Raspbian if needed.
    You can choose any version, I’ll do the 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 into the network (or configure the Wi-Fi), 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 will 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 for this step.
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 ip
  • 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 installed and configured on your smartphone app.
Give each a name to allow you to easily find them.
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 ourselves, 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 library links for other languages at the end of the article.

Grab my Python cheat sheet!
If like me, you always mix the languages syntax, download my cheat sheet for Python here!
Download now

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 coding.

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 gives us HTTP functions to change things for the lights (like switch a light off for example).

This API is typically 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/
  • 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.
  • 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 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.
  • In the following 30s, hit the POST button to run the query.

This should look like this in the form:

how to create the Hue username

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> with the one you got in the previous step (long random string).
  • Then press “GET” to get the answer.

The answer is in JSON format, which isn’t easy to read for a human (more about this here).
You should see one paragraph by light.
Each paragraph starts with a number (1, 2, 3, …) and contains all information 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')

    #Uncomment this line to register the app (see below)
    #b.connect()

    #Change the light state
    b.set_light(1, 'on', False)


    Replace 192.168.1.10 with your bridge IP address you previously noted.
    In the set_light function replace the first parameter with 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 its 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 do 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.

Grab my Python cheat sheet!
If like me, you always mix the languages syntax, download my cheat sheet for Python here!
Download now

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 you do not have this, jump to the next section.

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.
You can 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 happens.

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 as 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 schedule with different wake-up times that changes every week, it will be hard to create this schedule 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, you can increase this value bit-by-bit.
For example, starting at 0/0 and increasing one value by 0.01 every minute.

Let’s 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).
  • 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 switch from red to blue without transitioning.
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 won’t be easy to move through all possible colors.
My only idea was to use an array with some points defined manually in your favorite 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 can’t find how to cycle through all the colors gradually.
So it doesn’t help me.

🖋 Love Raspberry Pi & writing?
Combine your passions and get paid. Write for RaspberryTips!

Use an external API

The last scenario I want to introduce is using an external API.
For example, you can get sunrise and sunset times from an API, and plan to turn off the lights when the day comes up.

If you want an anecdote, I remember I created a script to set a specific color depending on the number 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 that you can adapt to your specific point of interest.

It’s funny and easy to make!

Download Your Essential Linux Commands Guide!
It's a free PDF guide containing every Raspberry Pi Linux command you should know!
Download now

Other languages

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

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 another API.

And if you are not ready yet to jump into the programming complexity, installing Home Assistant on your Raspberry Pi might be a first step to try to automate everything in your home.

Download Your Essential Linux Commands Guide!
It's a free PDF guide containing every Raspberry Pi Linux command you should know!
Download now

🛠 This tutorial doesn't work anymore? Report the issue here, so that I can update it!

If you are looking for exclusive tutorials, I post a new course each month, available for premium members only. Join the community to get access to all of them right now!

Conclusion

That’s it! You now 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 couple of 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.

Similar Posts

17 Comments

  1. Hello, this looks like a terrific article. Unfortunately without a publication date attached to it, it’s nearly useless to me. Without having some idea how current the information is, I’m not willing to go through the entire tutorial. It would be great if you could put a publication date at the beginning of the posting. Thanks, and keep up the good work!

    1. Hi Steve,
      This post is about one year old
      It should still work, there is almost nothing depending on the system in this tutorial

  2. Hi Patrick,
    I’m not a programmer but for me this looks good 🙂 .

    I’m trying now to build a website where I can control my lights from. somethig Very easy – a butten on a apache website which when I press the light goes on and when I press it again the light goes off. Can I do it with this script in python?
    Cheers
    Pawel

    1. I don’t have much experience in Python, but it should be possible

      In my case, I have done this in PHP in the past
      But I don’t have the code anymore
      You can find many library on GitHub if you want to try in PHP

      1. Too bad that You don’t have the code anymore. I will try to find Your PHP code and give it a shot. If I will not succeed by myself can I contact You directly? On GitHub is no forum where I can ask 🙁

  3. not working for me, when i first go in debug mode i can see the url changed to :/api/1234

    when i try both /app and /api/1234 i get error 404

  4. im getting this error

    from phue import Bridge
    ModuleNotFoundError: No module named ‘phue’

    1. Hello,

      Did you install the library?
      sudo pip install phue

      And thanks for /app, I will change this

      1. Thonny uses Python 3, you installed it for Python 2. Try using pip3 instead of pip.

  5. When trying to get the list of lights i use the URL:
    /api/7iU1zmt9-mHWtwZ3rW6ZIgz1nRAlEDFvonCRxcmx/lights

    And it returns “Your file not found”

    Any suggestions on how to fix this?

    Thank you in advance for your help.

  6. When trying to get the list of lights i use the URL:
    /api/7iU1zmt9-mHWtwZ3rW6ZIgz1nRAlEDFvonCRxcmx/lights

    And it returns “Your file not found”

    Any suggestions on how to fix this?

    Thank you in advance for your help

    1. Figured it out from another article it needed to have the bridge IP before, so:
      /api/7<username/lights

  7. Hi,

    When i try to use the “put” command to change the state of the bulb to “false” i receive the following message:

    [
    {
    “error”: {
    “type”: 4,
    “address”: “/lights”,
    “description”: “method, PUT, not available for resource, /lights”
    }
    }
    ]

    Do you know how i can resolve this?

    Thanks in advance for your help.

  8. Hi guys,
    I am setting up ambi light with WS2812 LED strip. I was wondering if i can use my philips hue lights with the WS2812 together for more effect.
    Thank you

Comments are closed.