Philips Hue with python
--
I chose Philips Hue lights over some other connected lights because it has a great API to control your lights. There is some package that made it easier to use with python.
Installing
Install the huesdk package
pip install huesdk
Connexion
To use the Philips Hue API you need two things. The local ip address of your Hue Bridge and a username. The username is an authentication key that is generated by the bridge.
Bridge IP
Go to https://discovery.meethue.com/, to find the IP of your bridge. We will see something like this :
[{"id":"xxx","internalipaddress":"192.168.1.10","port":443}]
App username
Press the button on your bridge and use the connect()
method to generate the username.
from huesdk import Hue
username = Hue.connect(bridge_ip=YOUR_BRIDGE_IP)
print(username)
Connect
Now you can instantiate a Hue
object
hue = Hue(bridge_ip=YOUR_BRIDGE_IP, username=YOUR_USERNAME)
Lights
The package work in an object-oriented way, with Lights, Group and Schedule objects. Let’s start with the lights.
First, you can retrieve your lights
# Get all the lights connected to the bridge
lights = hue.get_lights()# get a single light with id
light = hue.get_light(id_=1)
# get light with name
light = hue.get_light(name="Room 1")
Lights have various properties
light.id_
light.name
light.is_on
light.bri # Brightness from 1 to 254
light.hue # the color with a value between 0 and 65535
light.sat # Saturation from 1 to 254
You can change the state of the light with these methods:
# turn on
light.on()
# turn off
light.off()
# Change color
# with hue, red=65535, green=21845 and blue=43690
light.set_color(hue=43690)
# with hexadecimal
light.set_color(hexa="#065535")
# Change brightness
light.set_brightness(254)
# Change light's name
light.set_name("Hue color lamp 2")
# Change saturation
light.set_saturation(254)
For each change, you can set a transition time. This is given as a multiple of 100ms. So transition=10
will make the transition last 1 second. The default value is 4 (400ms).
# the light will slowly turn off in 5secs
light.off(transition=50)# the color's light will transition from the current color to red in 10seconds
light.set_color(hexa="#ff0000", transition=100)
Groups
You can do the same with your group. Which will apply the changes to all the lights within the same group.
# get all groups
groups = hue.get_groups()# get group with id
group = hue.get_group(id_=1)
# get group with name
group = hue.get_group(name="kitchen")group.on()
group.off(transition=40)
group.set_brightness(value)
group.set_name("Hue color lamp 2")
group.set_saturation(value)
group.set_color(hexa="#065535", transition=100)
You can now control your lights in all your python projects. Like, make color blink in your jupiter notebook when the training of your model is done. Connect it to some API when you receive a Slack message, change the color depending on the music …