Control Philips Hue Lights with API#

The Python script uses the Philips Hue API to interact with a Philips Hue bridge, which manages the smart lights. It presents a menu offering options to turn lights on, turn lights off, or exit the program.

When selecting to turn lights on, the script retrieves a list of lights that are currently off. It then prompts the user to choose one or multiple lights from this list by entering their respective numbers, separated by commas.

Similarly, when choosing to turn lights off, the script fetches a list of lights that are currently on. It allows the user to select one or multiple lights to turn off by entering their corresponding numbers, also separated by commas.

The script communicates with the Philips Hue bridge via the internet using the API, sending commands to change the state of the selected lights (either turning them on or off) based on the user’s choices.

After sending these commands, the script provides feedback, confirming which lights have been turned on or off, completing the interaction and control of the Philips Hue lights.


Getting started#

IMPORTANT: You need access to the Philips Hue Brigde in order to get an API key:

To get an API key for Philips Hue, you’ll need to follow these steps:#

Prerequisites:

  • Ensure your Philips Hue bridge is connected to your network and powered on.
  • Connect your computer or device to the same network as the Hue bridge.

Steps to Obtain API Key:#

Access the Philips Hue Bridge Portal:

  • Open a web browser and go to the following URL: https://discovery.meethue.com/.
  • This page will show the local IP addresses of your Philips Hue bridges on your network.

Find Your Bridge’s IP Address:

  • Note down the IP address of your Philips Hue bridge from the information displayed on the page.

Access the API Portal:

  • Open a web browser and enter the IP address of your Hue bridge in the address bar.
  • For example, if your bridge IP is 192.168.0.100, enter http://192.168.0.100/.

Press the Link Button on Your Bridge:

  • To generate the API key, you’ll need to press the physical link button on your Hue bridge.

Create a New User (API Key):

  • After pressing the link button, go back to the web browser and on the API portal page.
  • Click on the ‘Create User’ or ‘Generate API Key’ option.
  • Follow the instructions which usually involve providing a username for your API access.
  • The API key (also known as a username) will be generated. It should look like a string of random characters.

Note Down Your API Key:

  • Once generated, make sure to copy and securely store this API key.
  • This key will be used in your applications or scripts to communicate with your Hue bridge through the API.

Important Notes:

  • Keep your API key confidential and don’t share it with others.
  • If at any point you suspect your key has been compromised, you can create a new one by repeating the process.
  • Access to the API may vary depending on your Hue bridge’s firmware version, so ensure your bridge is updated for full functionality.

Following these steps will enable you to obtain an API key for your Philips Hue bridge, allowing you to interact with your lights programmatically through the Philips Hue API.

1. Use a python enviroment like miniconda:#

conda create --name PhilipsHue python=3.10

2. Activate enviroment:#

conda activate PhilipsHue

3. Create requirments file:#

touch requirements.txt
echo "requests" > requirements.txt

4. Install requirments:#

pip install -r requirements.txt

5. Create the python script:#

nvim controller.py

Remember to enter bridge IP and your API key, when you add the script below to the file controller.py:

import requests

# Philips Hue bridge IP address and API key
HUE_BRIDGE_IP = "YOUR_HUE_BRIDGE_IP_ADDRESS"
API_KEY = "YOUR_HUE_API_KEY"

# Base URL for API requests
BASE_URL = f"http://{HUE_BRIDGE_IP}/api/{API_KEY}"

def get_lights(state):
    lights_url = f"{BASE_URL}/lights"
    response = requests.get(lights_url)
    lights = response.json()

    lights_info = [
        (light_id, details['name'])
        for light_id, details in lights.items()
        if details['state']['on'] == state
    ]
    return lights_info

def turn_on_off_lights(state):
    if state == 'on':
        lights = get_lights(False)
    else:
        lights = get_lights(True)

    if not lights:
        print(f"No lights are {'off' if state == 'on' else 'on'}")
        return

    print(f"Select {'off' if state == 'on' else 'on'} lights to turn {'on' if state == 'on' else 'off'}:")
    for idx, (light_id, light_name) in enumerate(lights, 1):
        print(f"{idx}. {light_name}")

    selection = input("Enter the number(s) of the light(s) to control (separated by comma), or 'q' to quit: ")
    if selection.lower() == 'q':
        return

    selected_numbers = [int(x.strip()) for x in selection.split(',') if x.strip().isdigit()]

    for selected_number in selected_numbers:
        if 0 < selected_number <= len(lights):
            selected_light_id, _ = lights[selected_number - 1]
            light_url = f"{BASE_URL}/lights/{selected_light_id}/state"
            requests.put(light_url, json={"on": state == 'on'})
            print(f"Light '{lights[selected_number - 1][1]}' turned {'on' if state == 'on' else 'off'}")
        else:
            print(f"Invalid selection: {selected_number}")

def main():
    while True:
        print("\nSelect an action:")
        print("1. Turn on lights")
        print("2. Turn off lights")
        print("3. Quit")

        choice = input("Enter your choice: ")
        if choice == '1':
            turn_on_off_lights('on')
        elif choice == '2':
            turn_on_off_lights('off')
        elif choice == '3':
            break
        else:
            print("Invalid choice. Please enter a valid option.")

if __name__ == "__main__":
    main()

6. Run the script:#

python3 controller.py