Code Monkey home page Code Monkey logo

phue's Introduction

phue: A Python library for Philips Hue

Full featured Python library to control the Philips Hue lighting system.

Features

  • Compliant with the Philips Hue API 1.0
  • Support for Lights
  • Support for Groups
  • Support for Schedules
  • Support for Scenes
  • Support for Sensors
  • Compatible with Python 2.6.x and upwards
  • Compatible with Python 3
  • No dependencies
  • Simple structure, single phue.py file
  • Work in a procedural way or object oriented way

Installation

Using distutils

sudo easy_install phue

or

pip install phue

Manually

phue consists of a single file (phue.py) that you can put in your python search path or in site-packages (or dist-packages depending on the platform) You can also simply run it by putting it in the same directory as you main script file or start a python interpreter in the same directory. phue works with Python 2.6.x, 2.7.x and 3.x

Examples

Basic usage

Using the set_light and get_light methods you can control pretty much all the parameters :

#!/usr/bin/python

from phue import Bridge

b = Bridge('ip_of_your_bridge')

# 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 time)
b.connect()

# Get the bridge state (This returns the full dictionary that you can explore)
b.get_api()

# Prints if light 1 is on or not
b.get_light(1, 'on')

# Set brightness of lamp 1 to max
b.set_light(1, 'bri', 254)

# Set brightness of lamp 2 to 50%
b.set_light(2, 'bri', 127)

# Turn lamp 2 on
b.set_light(2,'on', True)

# You can also control multiple lamps by sending a list as lamp_id
b.set_light( [1,2], 'on', True)

# Get the name of a lamp
b.get_light(1, 'name')

# You can also use light names instead of the id
b.get_light('Kitchen')
b.set_light('Kitchen', 'bri', 254)

# Also works with lists
b.set_light(['Bathroom', 'Garage'], 'on', False)

# The set_light method can also take a dictionary as the second argument to do more fancy stuff
# This will turn light 1 on with a transition time of 30 seconds
command =  {'transitiontime' : 300, 'on' : True, 'bri' : 254}
b.set_light(1, command)

Light Objects

If you want to work in a more object-oriented way, there are several ways you can get Light objects.

Get a flat list of light objects

lights = b.lights

# Print light names
for l in lights:
    print(l.name)

# Set brightness of each light to 127
for l in lights:
    l.brightness = 127

Get Light objects as dictionaries

# Get a dictionary with the light id as the key
lights = b.get_light_objects('id')

# Get the name of light 1, set the brightness to 127
lights[1].name
lights[1].brightness = 127

# Get a dictionary with the light name as the key
light_names = b.get_light_objects('name')

# Set the brightness of the bulb named "Kitchen"
light_names["Kitchen"].brightness = 254

# Set lights using name as key
for light in ['Kitchen', 'Bedroom', 'Garage']
    light_names[light].on = True
    light_names[light].hue = 15000
    light_names[light].saturation = 120

# Get a flat list of the light objects (same as calling b.lights)
lights_list = b.get_light_objects('list')

for light in lights_list:
   light.on = True
   light.brightness = 127

Setting Transition Times

In the Hue API, transition times are specified in deciseconds (tenths of a second). This is not tracked as a device setting, but rather needs to be applied on each individual transition command you want to control the time of.

This can be done by specifying a transitiontime keyword when calling set_light on the bridge:

# Set brightness of lamp 1 to max, rapidly
b.set_light(1, 'bri', 254, transitiontime=1)

As a convenience, the Light class implements a wrapper that remembers a specified transition time for that light, and applies it automatically to every transition:

light = light_names['Kitchen']
light.transitiontime = 2
# this next transition will happen rapidly
light.brightness = 20    

Note that there is a known bug where turning a light off with the transitiontime specified can cause the brightness level to behave erratically when the light is turned back on. See this discussion This package attempts to work around this issue by automatically resetting the brightness when necessary, but this may not work in all cases.

Transition times from 0-300 deciseconds (i.e. 0 - 30 seconds) have been tested to work.

Groups

You can also work with the groups functionality of the Bridge. If groups aren't working, try re-setting the bridge by unpluging it and plugging it back again.

# List groups
b.get_group()

# List group 1
b.get_group(1)

# Get name of group 1
b.get_group(1, 'name')

# Get lights in group 1
b.get_group(1,'lights')

# Create a group with lights 1 and 3
b.create_group('Kitchen', [1,3])

# Rename group with id 1
b.set_group(1, 'name', 'New Group Name')

# Change lights within group 1
b.set_group(1, 'lights', [3,4])

# Turn group 1 off
b.set_group(1, 'on', False)

# Delete group 2
b.delete_group(1)

Schedules

You can view, create and delete schedules using the following methods. Note that updates to the Hue API now use local time instead of UTC. If you have issues with schedules not triggering correctly, double check that the time zone is set correctly on your Hue Bridge and that your time in your code is not in UTC by default.

# Get the list of different schedules
b.get_schedule()

# Get the data of a particular schedules
b.get_schedule(1)

# Create a schedule for a light, arguments are name, time, light_id, data (as a dictionary) and optional description
data = {'on': False, 'transitiontime': 600}
b.create_schedule('My schedule', '2012-11-12T22:34:00', 1, data, 'Bedtime' )

# Create a schedule for a group, same as above but with a group_id instead of light_id
data = {'on': False, 'transitiontime': 600}
b.create_group_schedule('My schedule', '2012-11-12T22:34:00', 0, data, 'Bedtime' )

# Delete a schedule
b.delete_schedule(1)

Using phue with Max/MSP via Jython

You can use the phue library within Max/MSP by using Nick Rothwell's Jython objects. He recently updated the version to support Jython 2.7 which is required for phue to work.

Download it here: https://github.com/cassiel/net.loadbang.jython

Using phue on iOS via Pythonista

You can use phue on your iOS device via the Pythonista app. This is a great way to build quick prototypes on iOS as you don't need to compile anything, you can code directly from the device itself.

See this little example:

http://www.youtube.com/embed/6K-fxWG6JSs

Acknowledgments

Huge thanks to http://rsmck.co.uk/hue for hacking the protocol !

License

MIT - http://opensource.org/licenses/MIT

"Hue Personal Wireless Lighting" is a trademark owned by Koninklijke Philips Electronics N.V., see www.meethue.com for more information. I am in no way affiliated with the Philips organization.

phue's People

Contributors

aletheap avatar balloob avatar bennert avatar blacklight avatar bradykent avatar carlinmack avatar carlosperate avatar cazfri avatar demosdemon avatar dsifford avatar eldstal avatar elmuerte avatar jamescun avatar jlintz avatar jo12bar avatar k0nze avatar mammuth avatar mperrin avatar natcl avatar pauljones0 avatar psychokiller1888 avatar rec avatar renini avatar rgardler-msft avatar richjeanes avatar rolfkoenders avatar sdague avatar simontuckwell avatar sqwabman avatar vapidlinus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phue's Issues

Silent fail on connect() if IP changed or no network

Things were working fine untill today when suddenly my app would crash when setting the lights.

Running phue.py gave this:

$ python phue.py --host 192.168.1.3
INFO:phue:Attempting to connect to the bridge...
INFO:phue:Using ip: 192.168.1.3
INFO:phue:Using username from config: [censored]

Seems ok, but those messages are misleading... If I check the source code it's obvious why:

    def connect(self):
        """ Connect to the Hue bridge """
        logger.info('Attempting to connect to the bridge...')
        # If the ip and username were provided at class init
        if self.ip is not None and self.username is not None:
            logger.info('Using ip: ' + self.ip)
            logger.info('Using username: ' + self.username)
            return

So in my app b = Bridge('192.168.1.3') would run fine, but b.get_light_objects('id') would fail with exception: [Errno 61] Connection refused.

I logged into meethue.com and noticed my bridge was now on 192.168.1.2. Changing to that I got PhueRegistrationException which is good. But I'd expect to get that or some other exception when running Bridge(ip). Otherwise it's hard for me to do proper error handling for my users.

I haven't tried the undocumented methods of registering, like Bridge::register_app() or Bridge::get_ip_address() but it doesn't seem like they would help as once the IP and username are set phue will always assume a connection.

Can't connect to the bridge

I installed phue via pip on a raspberry pie model b and tried the following script:

#!/usr/bin/python
from phue import Bridge
b = Bridge('192.168.178.56')
# 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 time)
b.connect()
b.get_api()

But I get always the following log message:
Traceback (most recent call last): File "test.py", line 5, in <module> b = Bridge('192.168.178.56') File "/usr/local/lib/python2.7/dist-packages/phue.py", line 629, in __init__ self.connect() File "/usr/local/lib/python2.7/dist-packages/phue.py", line 753, in connect self.register_app() File "/usr/local/lib/python2.7/dist-packages/phue.py", line 707, in register_app response = self.request('POST', '/api', data) File "/usr/local/lib/python2.7/dist-packages/phue.py", line 653, in request connection.request(mode, address, data) File "/usr/lib/python2.7/httplib.py", line 1039, in request self._send_request(method, url, body, headers) File "/usr/lib/python2.7/httplib.py", line 1073, in _send_request self.endheaders(body) File "/usr/lib/python2.7/httplib.py", line 1035, in endheaders self._send_output(message_body) File "/usr/lib/python2.7/httplib.py", line 879, in _send_output self.send(msg) File "/usr/lib/python2.7/httplib.py", line 841, in send self.connect() File "/usr/lib/python2.7/httplib.py", line 822, in connect self.timeout, self.source_address) File "/usr/lib/python2.7/socket.py", line 571, in create_connection raise err socket.error: [Errno 111] Connection refused

Any ideas?

Thanks
Daniel

Error in get_light_objects

Whenever I try to run the get_light_objects method I get the following error:

Traceback (most recent call last):
  File "random_colors.py", line 14, in <module>
    lights = b.get_light_objects()
  File "/Users/abcd/abcd/Hue/Python/examples/phue.py", line 562, in get_light_objects
    self.lights_by_id[int(light)] = Light(self, int(light))
TypeError: int() argument must be a string or a number, not 'dict'

The error started appearing for me about 2 or 3 weeks ago. I noticed it after a base station update (maybe the problem?) but I dont think there was an API change. I dont think its my code either since I get this error while running the examples as well (the error above came from the "random_colors.py" example).

Any idea why this started happening?

fix license in setup.py ?

Project seems to be licensed under MIT, but setup.py states WTFPL.

I assume this should also be MIT?

Command line tool

It could be nice to have a command line tool based on this api. Also I want a pony.

Error after migrating from original hub to new version which supports Apple Homekit

I just replaced my original round hub with a new square hub that supports Appel HomeKit. The migration process was easy and smooth. The new hub was assigned the same IP address as the old one. I was instructed to reset the old one to factory condition. I did that and disconnected it. I can control my lights with my iPad, etc. but I get an error when my programs try to access the lights.

I get this error message when I run my program to display information about all the lights:

No handlers could be found for logger "phue"

Traceback (most recent call last):
File "C:\MyPython\showlights.py", line 49, in
lights = b.get_light_objects() # try to access light info
File "C:\MyPython\phue.py", line 592, in get_light_objects
lights = self.request('GET', '/api/' + self.username + '/lights/')
File "C:\MyPython\phue.py", line 481, in request
raise PhueRequestTimeout(None, error)
PhueRequestTimeout

I'm attaching a copy of the failing program. Any ideas?

Thanks.
Tom

!/usr/bin/python

phue can be downloaded from: https://github.com/studioimaginaire/phue

from phue import *

def displayLightInfo():

    print '  NUM     NAME           ON  BRIGHT  MODE         XY          HUE    SAT     MFG      TYPE' 
    for light in lights:
            num = light.light_id
            name = light.name
            onoff= light.on
            bright=light.brightness
            try:
                    hue = light.hue
            except KeyError:
                    hue = 0
            try:
                    sat = light.saturation
            except KeyError:
                    sat = 0
            try:
                    xy = light.xy
            except KeyError:
                    xy = '-       '          
            try:
                    mode = light.colormode
            except KeyError:
                    mode = '-'

            description = b.get_light(num)
            mfg = description['manufacturername'].strip()
            ltyp= description['type'].strip()

            print '%5d     %-15s %d    %3d %5s   %16s  %5d %5d %8s %15s' % (
                    num,name,onoff,bright,mode,xy,hue,sat,mfg,ltyp)

    return()

b = Bridge('192.168.1.122') # Enter bridge IP here.

If running for the first time, press button on bridge and run with b.connect() uncommented

b.connect()

lights = b.get_light_objects() # try to access light info

displayLightInfo() # display info on all lights

get_ip_address must use HTTPSConnection

I wanted to build some python code using the phue library that did not require the user to hard-code their bridge IP address. I initially wrote my own code to get the IP address from the json returned by https://www.meethue.com/api/nupnp. After getting that working I noticed you already had a method in your library to do this. However - it doesn't work.

You need to change line 480 to use HTTPSConnection. e.g.

connection = httplib.HTTPSConnection('www.meethue.com')

Hope that helps.

Thanks so much for the library

Are scenes supported ?

Scenes are pretty well documented in the API. Am I missing something or are scenes not supported ?

Why am i getting this error message?

Hi guys!

Thank you very much for this amazing library. It has helped me use my philips hue trough a raspberry pi even though i didn't have experience using either.

One problem i have is after running my hue program for about a minute is the following error. I have no clue why this comes. In my program i change the hue and the brightness trough 'brivar' and 'huevar'.

In this error message it's because of brivar. in other error messages i get it's about the huevar.

"
Traceback (most recent call last):
File "v3.py", line 130, in
b.set_light(2,'bri', brivar)
File "/usr/local/lib/python2.7/dist-packages/phue.py", line 611, in set_light
converted_light) + '/state', json.dumps(data)))
File "/usr/local/lib/python2.7/dist-packages/phue.py", line 430, in request
result = connection.getresponse()
File "/usr/lib/python2.7/httplib.py", line 1034, in getresponse
response.begin()
File "/usr/lib/python2.7/httplib.py", line 407, in begin
version, status, reason = self._read_status()
File "/usr/lib/python2.7/httplib.py", line 371, in _read_status
raise BadStatusLine(line)
httplib.BadStatusLine: ''
"

The philips developer website tells me you can send about 10 commands to lights per second so i can't imagine that it is because i overload the lamps.

Kind regards,
Jonas

cannot parallelize light activation

When I do

bridge.set_light([1,2,3,4], { 'hue': 33862, 'sat': 50, 'bri': 254, 'on': True })

What actually happens, is that every light slowly turns on in sequence, instead of all four lights turning on.

I tried to get around this by using Pool like so:

from multiprocessing import Pool
LIGHTS = 4
def change_state(light):
    b.set_light(light, { 'hue': 33862, 'sat': 50, 'bri': 254, 'on': True })

if on_state != current_state:
    pool = Pool(LIGHTS)
    pool.map(change_state, range(1, LIGHTS+1))

What happens when I do this is even worse, first one of the lights slowly turns on, then the other three turn on in parallel, and this takes even longer than the first example.

bri/hue/sat settings seem partially implemented.

In my tests with a single Philips Hue bulb, I'm finding it possible to set brightness and hue, but not saturation. Moreover, the spelling of bri/brightness varies, and hue cannot be set via the set_light method.

# for bridge  
b.set_light(1,'bri',250)          # works
b.set_light(1,'brightness',250)   # no handler found
b.set_light(1,'hue',40000)        # no handler found
b.set_light(1,'sat',250)          # no handler found
b.set_light(1,'saturation',250)   # no handler found

# for individual light
l.bri = 250               # no effect
l.brightness = 250        # works
l.hue = 40000             # works
l.sat = 250               # no effect  (in my tests colormode is "hs")
l.saturation = 250        # no handler found

Instructions for installing in Pythonista

There are currently no instructions on how to get the library onto your iPad where it can be used by Pythonista. This is a non-trivial task since Pythonista doesn't seem to support pip or easy_install.

Update API version compliance

Any chance to see phue updated with support for the latest API version?
Appears to be 1.15 according to http://www.developers.meethue.com/documentation/changelog

I noticed the API version was an issue as the 'time' argument on the Schedule interface is deprecated in favor of 'localtime' (a change that seems to be missing from their changelog... So maybe it isn't all inclusive... How useful.) as of API 1.2.1 (in addition to 'status' and 'autodelete' being added in 1.2.1 and 1.3, respectively). However this means that I cannot create schedules at all using phue, just getting an error when I try.

I am happy to contribute, though I can't make any promises on quality or timeframe. ๐Ÿ‘

Broken with commit a8863fb9a3cdbc93a0aaf6645912a050609fba98

on line 531, the installation of phue.py on a blank system and first connection to the bridge won't work because the .python_hue file can't be opened for read (the file doesn't exist.)

I guess a workaround is to create a .python_hue file with valid JSON data so that it can be opened and loaded, but perhaps a better check would be to load the file only if it exists?

Great work otherwise!

I'm having difficulties when the ip address of the Hue hub changes

I'm using both Windows 7 and a Raspberry Pi to control lights. I do testing and coding in Python mostly on Windows but the RPi does most of the controlling since I leave it on all the time. Everything works fine until I have a power outage (or, equivalently, disconnect and reconnect power to my router). I have a number of devices on my home network: 3 computers, a couple of printers, TiVo, etc. The Hue hub always seems to get a different ip address when this happens. This means that my programs no longer can connect to the hub. I can figure out what the new ip address is when this happens and change the programs but that's not enough. I find that I have to go through the press-the-button-on-the-hub process again for each system. Is there some way to avoid that?

I notice that I don't have to do anything like that on my iPad -- it doesn't seem to be bothered by the ip change. This problem doesn't happen often and the RPi sends me email to let me know about the problem. My difficulty is that I'm not always at home and there is no way to push the button remotely. Any ideas or suggestions would be welcome.

Non-ASCII character line 7

Traceback (most recent call last):
File "./bla.py", line 3, in
from phue import Bridge
File "/share/MD0_DATA/phue/phue.py", line 7
SyntaxError: Non-ASCII character '\xc3' in file /share/MD0_DATA/phue/phue.py on line 7, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

adding coding to phue.py fixes this:

!/usr/bin/python

-- coding: iso-8859-15 --

No handlers could be found for logger "phue"

I just installed my bridge and it's working properly using the app. It also worked a few times using the hue basic example but now I'm getting this warning: No handlers could be found for logger "phue"
The lamps do get set on but not on the right brightness, it's quite low.

AllLights not working

import phue


b = phue.Bridge("<ip>")
b.connect()

This will not work any more

This was working but Then stopped.
phue.AllLights.on = True

but this is Working

This will work for all lights.
b.set_group(0, "on", False)

Problem with Living White Plug - has no colormode

I have several Living White plugs in my system. They have no colormode attached to it, making phue fail when you try to get lights:

Traceback (most recent call last):
File "./dumpscene.py", line 34, in
dump_light(light)
File "./dumpscene.py", line 16, in dump_light
if light.colormode:
File "/opt/hue/phue.py", line 138, in colormode
self._colormode = self._get('colormode')
File "/opt/hue/phue.py", line 75, in _get
return self.bridge.get_light(self.light_id, _args, *_kwargs)
File "/opt/hue/phue.py", line 534, in get_light
return state['state'][parameter]
KeyError: 'colormode'

So self._get('colormode') should be able to return None, I guess?

Here the dump from a Living White plug straight from clip debugger on my bridge:

{
"state": {
"on": true,
"bri": 254,
"alert": "none",
"effect": "none",
"reachable": true
},
"type": "Dimmable plug-in unit",
"name": "BedroomMusic",
"modelid": "LWL001",
"swversion": "1.0.1.4591",
"pointsymbol": {
"1": "none",
"2": "none",
"3": "none",
"4": "none",
"5": "none",
"6": "none",
"7": "none",
"8": "none"
}
}

As you can see, state has no color information at all. AFAICS without being a developer, this makes phues fail where it should fall back graciously somehow.

Maybe add a colormode "none" or "switch" or "dimmer"?

Jan

Can not import Bridge

I am trying to set this up and please forgive me as I am new to this but after I installed phue I tried to do a test and I keep getting this error

Traceback (most recent call last):
File "phue.py", line 2, in
from phue import Bridge
File "/home/mike/hue/phue.py", line 2, in
from phue import Bridge
ImportError: cannot import name Bridge

can anyone shed some light as to what might be causing this error?

Multiple Hubs

I have two hubs and using this in HA, it finds all the bulbs once the hubs are registered. However on subsequebt start, one of the hubs is 'lost' and needs re-registering. I see there is just one entry in the phue.conf file so that is the problem. Either the file needs to accomodate additional registration entries or more than one file. As the number of hubs is likely to be low could the registration process store all the user ids in the one file and try all the keys to establish a match or match the key to the IP address?

Does not respond properly when first setting up on a Windows system

The procedure for Windows systems is not quite right, I think -- I won't pretend to know what I'm doing, but I can tell you what I did that made it work for me.

When I started a test program of mine ("CrimsonTide.py", does a "red alert on a submarine" effect), it failed in an unexpected way, reporting a type-conversion error (error message at bottom). I was expecting an error to the effect of "this program is not registered with the bridge" or some other authentication error.

I tracked it backwards to a failure during the init call on lines 360 and 361.

    if os.access(os.getenv(USER_HOME),os.W_OK):
        self.config_file_path = os.path.join(os.getenv(USER_HOME),'.python_hue')

It seems that if USER_HOME is not defined as an environment variable, getenv() returns None, which is not being implicitly converted to a string. I added str() calls around os.getenv(), and that got it working. As I mentioned, I don't really know what I'm doing, so that may be a bad way to fix it.

Thank you for putting this together, I'm having fun playing with my lamps!


INFO:phue:Logging level set to info
INFO:phue:Attempting to connect to the bridge...
INFO:phue:Error opening config file, will attempt bridge registration
INFO:phue:Please press button on bridge to register application and call connect
() method
Traceback (most recent call last):
File "CrimsonTide.py", line 59, in
main()
File "CrimsonTide.py", line 20, in main
lights = b.get_light_objects('name')
File "C:\Users\Michael Basial\Documents\My Dropbox\Philips_Hue\phue-master\phu
e.py", line 483, in get_light_objects
lights = self.request('GET', '/api/' + self.username + '/lights/')
TypeError: Can't convert 'NoneType' object to str implicitly

DeviceID when searching for lights

So the lights call refused to find my device (Philips hue go) until I manually specified the device id (a.k.a the serial id).

I had to do this using curl:

curl http://XXX.XXX.244.114/api/c320XXXXXXX82f32ead6bb19e913a7/lights --data '{"deviceid": ["DBXXXX"] }'

as documented in the api docs. It might be nice to support deviceid within the phue.

Please upload 0.9 on PyPI

Would you mind uploading the latest code (0.9 or so) on PyPI? Then any pip install commands used in whatever installation docs could reference a stable release rather than a work in progress.

Otherwise thanks for a cool package! Since it's essentially one module only, I can use it from Pythonista (http://omz-software.com/pythonista/) which has requests and other batteries built-in!

Data Returned is Inconsistent

For example, when I do bridge.get_group('Office'), I get a dictionary of text returned. But the client lib should, for example (and since currently I'm only working with lights), return {lights:[ {{ list of Light objects }} .. ] ... }

Additionally, the Light IDs returned via b.get_group() are unicode strings... not ints.

Inconsistent behaviour

I'm trying to use phue from a Raspberry Pi but can't get my script to work as designed. I've stripped my program to execute just a few lines [after providing credentials, etc.] to illustrate the problem:

print hue.set_light(2, {'on': True, 'bri': 20, 'transitiontime': 50})  # transitiontime is ignored
time.sleep(1)
print hue.set_light(2, {'bri': 200, 'transitiontime': 100})  # completely ignored
time.sleep(1)
print hue.set_light(2, {'on': False, 'transitiontime': 200})  # completely executed

The effect on the lamp is described in the comments. Output on the screen is as follows:

[[{u'success': {u'/lights/2/state/transitiontime': 50}}, {u'success': {u'/lights/2/state/on': True}}, {u'success': {u'/lights/2/state/bri': 20}}]]
[[{u'success': {u'/lights/2/state/transitiontime': 100}}, {u'success': {u'/lights/2/state/bri': 200}}]]
[[{u'success': {u'/lights/2/state/transitiontime': 200}}, {u'success': {u'/lights/2/state/on': False}}]]

A significant part of the code is ignored or at least has no visible effect on the lamp. To be absolutely certain that the bridge doesn't get too many commands in a short time, I've used a 1 second delay between issuing commands.

I've tried many different combinations of commands to single out the problem of which the code shown is the simplest. Is it my flawed understanding of phue or something else? Any help will be appreciated.

logging is slightly inefficient...

A very minor complaint but thought you might want to know.

The way you are logging, you prepare the output string every time, and then try to log it. But if debug logging isn't turned on, the work of preparing the string is wasted.

Python's logging system handles that (and pylint would have reported this to you...!)

For example, look here at https://github.com/studioimaginaire/phue/blob/master/phue.py#L100: you have

logger.debug("Setting with transitiontime = {0} ds = {1} s".format(
             self.transitiontime, float(self.transitiontime) / 10))

but a tiny bit better is:

logger.debug("Setting with transitiontime = %s ds = %s s", 
             self.transitiontime, float(self.transitiontime) / 10)

because if debugging isn't turned on, it doesn't actually do the formatting...

Add a timeout to requests made to the bridge

I've had a few times that the bridge would not respond to a request from Phue and it ended up hanging my script. I think it has to do with the bridge receiving too many requests at once.

Currently the HTTPConnection is initialized within Phue without the timeout parameter. This makes Python use the global default value which is None: a request can stay open forever waiting for an answer (there is an open Python bug from 2010 to change this behavior).

I propose the HTTPConnection to be initialized with a timeout parameter. We can make it a very generous timeout (ie 10 seconds) so that it won't interfere with normal operation.

If approved I'll submit a pull request with this change.

b.get_api() not displaying anything?

I'm sorry if this is just me being thick, but I'm totally new to Python (and programming/scripting in general).

I have the library working and am able to turn my lights on/off etc, but the b.get_api() and b.get_light(1, 'on') commands don't print anything...

Is this supposed to be printed in the terminal or should I have written something more to get them to show? I'm not sure. I'm using Debian and OSX.

Thanks so much for the awesome software, it's really inspired me to learn some python and do some scripting!

Timeout for bridge connection

Hi,
First of all congratulations for your project !

I use a raspberry pi with a script running in loop that detects if the lights have been turned on (setting pattern matching the one on start) and then adjust its setting to make the light more bearable.
The script has been running smoothly for one month and then crashed PhueRequestTimeout

Is there any way to define the timeout as a parameter ?

Le bonjour a la belle Province.

get_light_objects('name').keys() returns unicode but get_light() and set_light() cannot take unicode

I ran into this using something like:

which lights to turn on - leave empty to turn on lights on

mylights = [ "window", "ceiling1", "ceiling2", "ceiling3" ]

mylights = []

    if not mylights:
            mylights = b.get_light_objects('name').keys()
    for lightname in mylights:
            try:
                    if not b.get_light(str(lightname))["state"]["on"]:

this will throw the error:
Traceback (most recent call last):
File "./hue-dhcp", line 120, in
lightson(mylights)
File "./hue-dhcp", line 100, in lightson
if not b.get_light(lightname)["state"]["on"]:
File "/usr/lib/python2.7/site-packages/phue.py", line 625, in get_light
light_id = self.get_light_id_by_name(light_id)
File "/usr/lib/python2.7/site-packages/phue.py", line 569, in get_light_id_by_name
if unicode(name, encoding='utf-8') == lights[light_id]['name']:
TypeError: decoding Unicode is not supported

So I have to use str(lightname) which is kinda ugly.

PyPi tarball is missing LICENSE file

It would be good to include the LICENSE file in the tarball on PyPi.
This way upstream packagers like Yocto can automatically verify it during package creation.

Also the source file states:

Published under the MIT license - See LICENSE file for more details.

But LICENSE is not included

set_group error

Currently set_group has two ifs in a row which negates the ability to pass a dictionary in. I suspect that line 446 is meant to be an elif.

def set_group(self, group_id, parameter, value = None):
    if type(parameter) == dict:
        data = parameter
    if parameter == 'lights' and type(value) == list:
        data = {parameter : [str(x) for x in value] }
    else:
        data = {parameter : value}

Unworkable license

Any chance you could put a real open source license on this. The nearest thing to the one you have selected is probably the MIT, but any permissive license would do.

Unicode NoneType Problem with Initialization Function

An error occurs when trying to execute a python script via an external execution call. For instance, if the php exec function is used to call a python script containing a phue call, even if the apache2 user is the SAME user that has already initialized with the hue hub (tapping the button within 30 seconds), the following error appears:

TypeError: coercing to Unicode: need string or buffer, NoneType found
Traceback (most recent call last):
  File "/home/pi/lights.py", line 26, in <module>
    b = Bridge('192.168.0.110')
  File "/usr/local/lib/python2.7/dist-packages/phue.py", line 389, in __init__

The code in question is trying to ascertain the appropriate configuration file path. It would appear, that in this scenario, os.getenv(USER_HOME) does not work as anticipated as a result of the "user" being the webserver user:

if os.access(os.getenv(USER_HOME), os.W_OK):
    self.config_file_path = os.path.join(os.getenv(USER_HOME), '.python_hue')
else:
    self.config_file_path = os.path.join(os.getcwd(), '.python_hue')

The above code can be commented out and replaced with a hard-coded pointer to the config file. This works for me, for now, but is obviously a non-ideal solution:

self.config_file_path = '/home/pi/.python_hue'

does not deal well if lights don't start with #1

It seems like, in some places, the library assumes that lights will be sequentially ordered starting with one. I have a bridge that a friend gave me and bought a new bulb which it's calling '4'. It's the bulb I've got in the following cases.

> lights = b.lights
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/lib/python2.7/site-packages/phue.py", line 611, in lights
    return self.get_light_objects()
  File "/lib/python2.7/site-packages/phue.py", line 588, in get_light_objects
    return [self.lights_by_id[x] for x in range(1, len(self.lights_by_id) + 1)]
KeyError: 1

edit: removed last half of report because it was an int/float issue on my end

No tests in code

I've started hacking on this for some features I'd really like in home-assistant. The fact that the code doesn't have any tests makes it quite easy to break by accident on new patches.

I'd be happy to start building up some tests and connect this to the travis infrastructure if there is upstream interest. Please let me know, and I'll start in on that work.

Thanks again for this great base library. Hoping to help make it even better.

Observe light bulb changes

I'd like to observe light bulb changes.

Instead of querying every X seconds and asking for the state of the light bulbs it would be cool if I could somehow register myself to light changes and observe changes.

So far I haven't found this in the README nor do I know whether the bridge itself supports something like this.

Removing light {1} breaks b.lights

I had a broken light, which was light number 1, after replacing this light with a new light, my python script based on phue no longer works, the new light has number 5.

lights = b.lights # Print light names
for l in lights: print(l.name)

results in
File "/usr/local/lib/python2.7/dist-packages/phue.py", line 588, in get_light_objects
return [self.lights_by_id[x] for x in range(1, len(self.lights_by_id) + 1)]
KeyError: 1

when changing line 588, to
return [self.lights_by_id[x] for x in range(2, len(self.lights_by_id) + 1)]

the script works again but obviously doesn't list the last light (5) in my case because it starts with 2.
so you cannot assume lights always start at 1, apparently the bridge doesn't renumber them in order.

i will try to patch this with a pull req, but python is not my strongest language.

Consider using six for your 2->3 needs.

Last issue for today, I promise! And it's another tiny one...

I applaud you on making your program available for both Python 2 and 3.

There's a tiny package called six that has all this already worked out for you: https://pypi.python.org/pypi/six

And it's pretty standard these days. I just drop it into my directory when I start working...

If you liked I could send you a pull request for this, it'd take 15 minutes to do...

transitiontime doesn't affect brightness changes, only color changes

When I change the color of a light, it changes at the speed of the transitiontime. However, when I change the brightness, it changes at the default transitiontime (quickly).

Is this a bug, or is it just me? It even happens with the supplied example files.

edit: thanks for phue, by the way. loving using it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.