Sunday, May 12, 2013

pyhue: A Python library for the Philips Hue personal lighting system

This week I have been developing a small Python module to work with the Philips hue system. This lighting system is formed by one or more LED lamps connected to a bridge, which is a network device that processes HTTP requests to change the state of the lamps.

For instance, let's suppose the IP address of your bridge is X.X.X.X and your username is test. If you want to set the hue of the lamp with ID 1 and its brightness to the maximum (255), you have to send a PUT request to hhtp://X.X.X.X/api/test/lights/1/state with the content {"hue":0, "bri":255}.

In Python, if you use an HTTPConnection object, it would be:


import json
try:
    from httplib import HTTPConnection  # Python 2.X
except ImportError:
    from http.client import HTTPConnection  # Python 3.X

content = json.dumps({"hue":0, "bri":255})
conn = HTTPConnection('X.X.X.X')
conn.request('PUT', '/api/test/lights/1/state', content)
response = conn.getresponse().read()
print(json.loads(response))

If the request is successfully sent, this prints the following response: [{"success":{"/lights/1/state/hue":0}}, {"success":{"/lights/1/state/bri":255}}] . This message confirms the state has been changed.

Wiht pyhue, I have tried to abstract this logic with an OOP approach: Instead of creating the HTTP requests manually, I have defined one class for each entity in the API, and I have overridden its __setattr__ methods to send the correct request apart from updating the corresponding attribute.


import pyhue

bridge = pyhue.Bridge('X.X.X.X', 'test')
light = bridge.get_light("1")
light.hue = 0
light.bri = 255

This is a basic example, but with this module you can also interact with groups and schedules. You can easily install pyhue with pip install pyhue and the source code is available on GitHub.

As a side note, I would like to mention that unittest has had an important role in this project. I have implemented a test suite that has allowed me to refactor easily without worrying about breaking anything. Thus, the amount of duplicated code is minimal and the length of the module is only around 150 lines, following also the guidelines of PEP8.


Disclaimer: Philips Hue is a product of Philips Lighting B.V. pyhue is an open source third party library and I am not associated with Philips in any way.

No comments:

Post a Comment