Esempio n. 1
0
    def _get_client(self):
        hue = Hue()
        hue.station_ip = self.config['station_ip']
        hue.client_identifier = self.config['client_identifier']
        hue.get_state()

        return hue
Esempio n. 2
0
def create_schedule():
    h = Hue()
    body = dict(on=False)
    command = dict(address='/api/<your user name here>/lights/3/state',
            method='PUT',
            body=body)
    h.create_schedule('Tests', 'this is test', command)
Esempio n. 3
0
def create_schedule():
    h = Hue()
    body = dict(on=False)
    command = dict(address='/api/<your user name here>/lights/3/state',
                   method='PUT',
                   body=body)
    h.create_schedule('Tests', 'this is test', command)
Esempio n. 4
0
def main():

    module = AnsibleModule(
        argument_spec = dict(
            bridge=dict(required=True, type='str'),
            name=dict(required=True, type='str'),
            on=dict(default=True, type='bool'),
            brightness=dict(type='int'),
            hue=dict(type='int'),
            saturation=dict(type='int'),
            xy=dict(type='list'),
            color_temp=dict(type='int'),
            rgb=dict(type='str'),
            alert=dict(type='str', choices=['none', 'select', 'lselect']),
            effect=dict(type='str', choices=['none', 'colorloop']),
            transition_time=dict(type='int'),
        ),
        mutually_exclusive=(('hue', 'xy', 'color_temp', 'rgb'), ('saturation', 'xy', 'color_temp', 'rgb')),
        supports_check_mode=True
    )

    if not HUE_AVAILABLE:
        module.fail_json(msg="The python-hue library is not installed")

    # Connect to the Hue hub
    try:
        h = Hue()
        h.station_ip = module.params['bridge']
        h.get_state()
    except Exception, e:
        module.fail_json(msg="Failed to connect to the Hue hub. Make sure you've registered using the hue_register module first. Error was: %s" % str(e))
Esempio n. 5
0
def runMain():
    # First, we import our devices from our configuration file. These will be split into two different groups, those
    # controlled by Philips Hue and those controlled by Insteon.
    configuration = Configuration()
    config = configuration.loadConfig()

    hueDevices = {}
    insteonDevices = {}

    for device in config['devices']['hue']:
        hueDevices[device] = config['devices']['hue'][device]
    for device in config['devices']['insteon']:
        insteonDevices[device] = config['devices']['insteon'][device]
    insteon = Insteon()
    hue = Hue()

    roomba = Roomba()

    # Now we set up the voice recognition using Pocketsphinx from CMU Sphinx.
    pocketSphinxListener = PocketSphinxListener()

    # We want to run forever, or until the user presses control-c, whichever comes first.
    while True:
        try:
            command = pocketSphinxListener.getCommand().lower()
            command = command.replace('the', '')

            if command.startswith('turn'):
                onOrOff = command.split()[1]
                deviceName = ''.join(command.split()[2:])
                if deviceName in hueDevices:
                    deviceId = hueDevices[deviceName]['deviceID']
                    hue.turn(deviceId=deviceId, onOrOff=onOrOff)
                if deviceName in insteonDevices:
                    deviceId = insteonDevices[deviceName]['deviceID']
                    insteon.turn(deviceId=deviceId, onOrOff=onOrOff)
                if deviceName == 'roomba':
                    roomba.turn(onOrOff)
            elif command.startswith('roomba'):
                action = ' '.join(command.split()[1:])
                if action == 'clean':
                    roomba.clean()
                if action == 'go home':
                    roomba.goHome()

        # This will allow us to be good cooperators and sleep for a second.
        # This will give the other greenlets which we have created for talking 
        # to the Hue and Insteon hubs a chance to run.
            gevent.sleep(1)

        except (KeyboardInterrupt, SystemExit):
            print 'People sometimes make mistakes, Goodbye.'
            sys.exit()
        except Exception as e:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            traceback.print_exception(exc_type, exc_value, exc_traceback,
                                      limit=2,
                                      file=sys.stdout)
            sys.exit()
Esempio n. 6
0
def setupHue():
    hue = Hue(HUE_IP)
    # Get Hue username
    hue.loadUsername()
    if (hue.username == ""):
        print("Waiting for Hue authorization...")
        hue.authorize()
        print("---> Hue Authorization complete!")
    # Get Hue lights
    hue.getLights()
    # Set all lights to red
    hue.setAllLights(65000)
    return hue
Esempio n. 7
0
def apply_changes():
    data = request.form
    colors = {}
    myhue = Hue()
    for key, val in data.items():
        if key != 'csrf_token':
            light_id = key[1]
            color = key[0]
            if light_id not in colors:
                colors[light_id] = {}
            colors[light_id][color] = val
    myhue.update_via_rgb(colors)
    return json.dumps({'success': True})
Esempio n. 8
0
def wakemeup():
    h = Hue()
    h.station_ip = '192.168.42.89'
    h.get_state()

    minutes = 15
    transition = minutes * 60 * 10

    h.lights['l1'].off()
    h.lights['l1'].set_state({
        "on": True,
        "bri": 255,
        "transitiontime": transition
    })
Esempio n. 9
0
def wakemeup():
    h = Hue()
    h.station_ip = '192.168.42.89'
    h.get_state()

    minutes = 15
    transition = minutes * 60 * 10

    h.lights['l1'].off()
    h.lights['l1'].set_state({
        "on": True,
        "bri": 255,
        "transitiontime": transition
    })
Esempio n. 10
0
def hue_control():
    myhue = Hue()
    colors = {}
    form = FlaskForm()
    on = False
    count = len(myhue.lights)

    for light in myhue.lights:
        x = myhue.lights[light]['state']['xy'][0]
        y = myhue.lights[light]['state']['xy'][1]
        brightness = myhue.lights[light]['state']['bri'] / 254

        if x > 0 and y > 0:
            r, g, b = xy_to_rgb(x, y, brightness)
        else:
            r, g, b = 0, 0, 0

        colors[light] = {'r': r, 'g': g, 'b': b}
        if myhue.lights[light]['state']['on']:
            on = True

    return render_template('hue_control.html',
                           title='Hue Control',
                           lights=myhue.lights,
                           colors=colors,
                           form=form,
                           on=on,
                           count=count)
Esempio n. 11
0
    def __init__(self):

        self.brightness = Brightness()

        self.gamma = Gamma()

        self.gain = Gain()

        self.exposure = Exposure()

        self.exposureauto = ExposureAuto()

        self.saturation = Saturation()

        self.hue = Hue()

        self.whitebalancered = WhiteBalanceRed()

        self.whitebalanceblue = WhiteBalanceBlue()

        self.Parameters = {
            'Brightness': self.brightness.Brightness,
            'Gamma': self.gamma.Gamma,
            'Gain': self.gain.Gain,
            'Exposure': self.exposure.Exposure,
            'ExposureAuto': self.exposureauto.ExposureAuto,
            'Saturation': self.saturation.Saturation,
            'Hue': self.hue.Hue,
            'WhiteBalanceRed': self.whitebalancered.WhiteBalanceRed,
            'WhiteBalanceBlue': self.whitebalanceblue.WhiteBalanceBlue
        }
Esempio n. 12
0
def test_get_config_non_whitelist(testhue):
    unwhitelisted_name = 'woogyboogy_nowhitelist'
    assert unwhitelisted_name not in testhue.get_config()['whitelist']
    myhue = Hue.discover_one(unwhitelisted_name)
    conf = myhue.get_config()
    # We only get a minimal config when not whitelisted
    assert conf.keys() == ['swversion', 'name']
Esempio n. 13
0
def main():

    module = AnsibleModule(
        argument_spec = dict(
            bridge=dict(required=True, type='str'),
        ),
        supports_check_mode=False,
    )

    if not HUE_AVAILABLE:
        module.fail_json(msg="The python-hue library is not installed")

    # Connect and authenticate to the Hue hub
    try:
        h = Hue()
        h.station_ip = module.params['bridge']
        h.authenticate()
    except Exception, e:
        module.fail_json(msg="Failed to authenticate to the Hue hub. Make sure you've pushed the button on the hub recently. Error was: %s" % str(e))
Esempio n. 14
0
def on_and_off():
    h = Hue()
    if not h.lights:
        return
    l = h.lights[0]
    print 'Turn off the lights...'
    l.off()
    sleep(2)
    print 'Sleep 2 seconds...'
    l.on()
    print 'Lights on!'
Esempio n. 15
0
def get_hue(device_type='pyhue', ip=''):
    try:
        from hue import Hue
        from config import HueConf
        ip = ip or get_internalipaddress()
        conf = HueConf(station_ip=ip,
                device_type=device_type)
        return Hue(station_ip=conf.station_ip,
                device_type=conf.device_type)
    except:
        print error
Esempio n. 16
0
def main():

    module = AnsibleModule(
        argument_spec=dict(bridge=dict(required=True, type='str'), ),
        supports_check_mode=False,
    )

    if not HUE_AVAILABLE:
        module.fail_json(msg="The python-hue library is not installed")

    # Connect and authenticate to the Hue hub
    try:
        h = Hue()
        h.station_ip = module.params['bridge']
        h.authenticate()
    except Exception, e:
        module.fail_json(
            msg=
            "Failed to authenticate to the Hue hub. Make sure you've pushed the button on the hub recently. Error was: %s"
            % str(e))
Esempio n. 17
0
def test_create_user(testhue):
    testhue.activate_link_button()
    myhue = Hue.discover_one('PythonHueClientTest', 'PythonHueClientTests')
    myhue.create_user()
    conf = myhue.get_config()
    # we got the full config values
    assert 'whitelist' in conf
    myhue.delete_user()
    with pytest.raises(Exception):
        # Our user is invalid, so we can't do this
        myhue.deactivate_link_button()
Esempio n. 18
0
    def _get_client(self):
        hue = Hue()
        hue.station_ip = self.config['station_ip']
        hue.client_identifier = self.config['client_identifier']
        hue.get_state()

        return hue
Esempio n. 19
0
def test_autocreate_user(testhue):
    testhue.activate_link_button()
    # Let the device create a user
    myhue = Hue.discover_one(devicetype='PythonHueClientTests')
    assert len(myhue.create_user()) > 10
    assert myhue.devicetype == 'PythonHueClientTests'
    conf = myhue.get_config()
    # we got the full config values
    assert 'whitelist' in conf
    myhue.delete_user()
    # And now this user is no longer whitelisted
    with pytest.raises(Exception):
        myhue.deactivate_link_button()
Esempio n. 20
0
def sleepytime():
    h = Hue()
    h.station_ip = '192.168.42.89'
    h.get_state()

    minutes = 30
    transition = minutes * 60 * 10

    h.lights['l3'].off()
    h.lights['l3'].set_state({
        "bri": 50,
        "colormode": "xy",
        "xy": [0.5, 0.4],
        "transitiontime": transition,
    })

    h.lights['l1'].off()
    h.lights['l1'].set_state({
        "bri": 50,
        "colormode": "xy",
        "xy": [0.5, 0.4]
        "transitiontime": transition
    })
Esempio n. 21
0
    def __init__(self,id=-1,ip='192.168.1.99',lig='l1'):
        self.h = Hue()
        self.h.station_ip = ip

        self.h.get_state()
  
        self.level=60
        self.status=0
        self.id=id
        self.lig=lig
        self.color=[255,255,255,0,0]
        
        self.h.lights[self.lig].rgb(self.color[0],self.color[1],self.color[2])
        self.h.lights[self.lig].bri(self.level,1)
        self.h.lights[self.lig].off()
Esempio n. 22
0
 def setup_hue_bridge(self):
     self.hue_bridge = Hue(settings.HUE_USERNAME, settings.HUE_BRIDGE_IP)
Esempio n. 23
0
 def connect_to_bridge( self, dt ):
     logging.info( 'Connecting to Hue bridge' )
     hue = Hue()
     self.bridge = hue.bridge()
     self.ids.screen_manager.current = 'discovering lights'
     Clock.schedule_once( self.discover_lights, 3 )
Esempio n. 24
0
from flask.ext.socketio import SocketIO, emit
import random
import requests
import os
import json
from hue import Hue

app = Flask(__name__, static_folder='static', static_url_path='/static')
app.config['SECRET_KEY'] = 'secret!'
app.debug = True
socketio = SocketIO(app)

resp = requests.get('https://www.meethue.com/api/nupnp')
ip = json.loads(resp.content)[0]["internalipaddress"]

h = Hue()
h.station_ip = ip
h.get_state()


@app.route('/')
def index():
    return render_template('index.html')


@socketio.on('update_light', namespace='/lights')
def message(message):
    print message
    h.lights[message["light"]].set_state(message["state"])

    h.get_state()
Esempio n. 25
0
from hue import Hue
import requests
import json
import time
import logging

h = Hue()
resp = requests.get('https://www.meethue.com/api/nupnp')
ip = json.loads(resp.content)[0]["internalipaddress"]

h = Hue()
h.station_ip = ip
h.get_state()


logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('scratch')



SECS_PER_FRAME = 6

frames = [
    {                                                   # Frame 1
    "l1": {"on": True, "xy": [0.21, 0.04], "bri": 255},
    "l2": {"on": True, "xy": [0.21, 0.04], "bri": 255},
    "l3": {"on": True, "xy": [0.21, 0.04], "bri": 255},
    "l4": {"on": True, "xy": [0.21, 0.04], "bri": 255},
    "l5": {"on": True, "xy": [0.21, 0.04], "bri": 255},
    "l6": {"on": True, "xy": [0.21, 0.04], "bri": 255},
    },{                                                 # Frame 2
Esempio n. 26
0
#!/usr/bin/python
from random import randint
from time import sleep

from hue import Hue

myhue = Hue.discover_one('ExampleScript')

lights = myhue.get_lights()
for light in lights:
    light.put_state(on=True, transitiontime=10)

try:
    interval = 5
    while True:
        for light in lights:
            light.put_state(hue=randint(0, 65535),
                            sat=randint(200, 255),
                            bri=randint(200, 255),
                            # Transition is an integer in steps of 100ms
                            transitiontime=int(interval * 10))
            sleep(interval/len(lights))

except KeyboardInterrupt:
    for light in lights:
        light.put_state(on=False, transitiontime=10)
Esempio n. 27
0
from hue import HueLight
from hue import Hue

hue = Hue()
hue.getState()
#hue.setLightState(light=1, on=True, bri=254, sat=254, hue=10000)
hue.getLights()
hue.rgbtocie(255,0,0)
hue.rgbtocie(0,255,0)
hue.rgbtocie(0,0,255)
hue.setLightState(light=1, on=True, xy=hue.rgbtocie(0,0,255))
Esempio n. 28
0
from hue import Hue

new_hue = Hue.discover_one('BasePythonHueClientTestUser',
                           'PythonHueClientTests')
try:
    result = new_hue.create_user()
except Exception:
    raw_input('Press the link button now, then press enter.')
    result = new_hue.create_user()
print "User %s successfully added. Tests should run now." % result
Esempio n. 29
0
def auth():
    '''
    Press the hue button!
    '''
    h = Hue()
    h.auth()
Esempio n. 30
0
def test_arg_devicetype():
    myhue = Hue.discover_one()
    assert myhue.devicetype == 'PythonHueClientTests'
    myhue = Hue.discover_one(devicetype='PythonHueTestClient2')
    assert myhue.devicetype == 'PythonHueTestClient2'
Esempio n. 31
0
from hue import Hue

h = Hue()
# Initialize the class
h.station_ip = "192.168.1.222"  # Your base station IP
h.get_state()
# Authenticate, bootstrap your lighting system
l = h.lights.get('l3')  # get bulb number 3
l.bri(0)  # Dimmest
l.bri(255)  # Brightest
l.rgb(120, 120, 0)  # [0-255 rgb values]
l.rgb("#9af703")  # Hex string
l.on()
time.sleep(1)
l.off()
l.toggle()
l.alert()  # short alert
l.alert("lselect")  # long alert
l.setState({"bri": 220, "alert": "select"})  # Complex send
Esempio n. 32
0
    def _get_client(self):
        hue = Hue();
        hue.station_ip = self.config['station_ip']
        hue.get_state();

        return hue
Esempio n. 33
0
from flask import Flask, request, url_for, jsonify, render_template, redirect
import logging
import os

from todo import Todo
from roku import Roku
from hue import Hue

app = Flask(__name__)

todo = Todo(db='todo.db')
tv = Roku(ip=os.environ['roku_ip'])
light = Hue(ip=os.environ['hue_ip'], username=os.environ['hue_username'])

@app.route('/', methods=['GET', 'POST'])
def index():
    tasks = todo.get()
    lights = light.get()

    if request.method == 'POST' and 'addtask' in request.form:
        try:
            task = request.form['addtask']
            todo.post(task)
            tasks = todo.get()
            app.logger.info("Home: Added todo: " + str(task))
            return render_template("index.html", tasks=tasks, lights=lights)
        except:
            app.logger.error("Home: Failed to add todo: " + str(task))

    if request.method == 'POST' and 'deletetask' in request.form:
        try:
Esempio n. 34
0
from flask import Flask
from flask import render_template
from hue import Hue

h = Hue()
h.station_ip = "192.168.1.100"
h.get_state()
l = h.lights.get("l1")

# l.on()
# l.bri(255)

app = Flask(__name__)


@app.route("/")
def hello(name=None):
    return render_template("jshtml.html")


@app.route("/changecolor/<int:red>/<int:green>/<int:blue>")
def changecolor(red, green, blue):
    l.rgb(red, green, blue)
    return "pray"


if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=False, port=80)
Esempio n. 35
0
def alert():
    l = Hue()
    l.alert()
Esempio n. 36
0
def toggle(light):
    myhue = Hue()
    myhue.toggle_light(light)
    return json.dumps({'success': True})
from hue import Hue;
h = Hue(); # Initialize the class
h.station_ip = "192.168.2.169"  # Your base station IP
h.get_state(); # Authenticate, bootstrap your lighting system

l = h.lights.get('l5') # get bulb #5
#l.bri(0) # Dimmest
l.bri(255) # Brightest
#l.rgb(120, 120, 0) # [0-255 rgb values]
#l.rgb("#9af703") # Hex string
l.on()
#l.off()
#l.toggle()
#l.alert() # short alert
#l.alert("lselect") # long alert
#l.setState({"bri": 220, "alert": "select"}) # Complex send




def handleUserMessage(command):
    #TODO parse the user string.
    command.split(" ")
    print command
    #TODO get the set of nodes to work on from the device
    setOfLightsToOperateOn = ['l5']
    #TODO which function should I apply?
    funcToApply = ExtendedColorLight
    for light in setOfLightsToOperateOn:
        pass
Esempio n. 38
0
def toggle_all():
    myhue = Hue()
    myhue.toggle_lights()
    return json.dumps({'success': True})
Esempio n. 39
0
def test_user_length():
    with pytest.raises(Exception):
        myhue = Hue.discover_one('tooshort', 'PythonHueClientTests')
Esempio n. 40
0
import sys, time
sys.path.append( '/Users/huynh/Desktop/livebyte_webserver/lib/python-hue' );
from hue import Hue;
h = Hue(); # Initialize the class
h.station_ip = "192.168.1.101"  # Your base station IP
h.client_identifier = "newdeveloper"
# h.authenticate
state = h.get_state(); # Authenticate, bootstrap your lighting system
li = h.lights
for key, element in li.items():
	print key, element

l = h.lights.get('l1') # get bulb #1
while 1:
	ts = time.time()
	print ts
# l.alert() # short alert
# time.sleep(0.1)
# l.alert() # short alert
# time.sleep(0.1)
# l.set_state({"bri": 220, "alert": "select","transitiontime":1}) # Complex send
# time.sleep(0.1)
# l.alert() # short alert
# time.sleep(0.1)
# l.alert() # short alert
	# l.set_state({"bri": 230, "xy":[0.3,0.322],"sat":255}) # Complex send
	# l.set_state({"bri": 230, "xy":[0.3,0.322],"sat":255}) # Complex send
	l.rgb(255, 255, 240,transitiontime=1)
	time.sleep(0.1)
	l.rgb(255,255,255,transitiontime=1)
	# l.set_state({"bri": 255, "xy":[0.3,0.322],"sat":255}) # Complex send
Esempio n. 41
0
from flask import Flask, jsonify, request
from django.http import HttpResponse
from hue import Hue

hue = Hue()

app = Flask(__name__)

@app.route('/', methods = ['GET'])
def main():
    return "Welcome to Hue", 200

@app.route('/all/on', methods = ['GET'])
def all_on():
    hue.all_on(.2)
    return "All lights now on", 200


if __name__ == '__main__':
    app.run(host = '0.0.0.0', port = 5001)
Esempio n. 42
0
 def setup(self):
     self.hue = Hue('newdeveloper', 'localhost:8080')
Esempio n. 43
0
import time
import math
import random as rand

from hue import Hue
from rgb_cie import Converter
from detect_object import detect_object
from detect_object import get_rgb
from detect_rectangle import detect_rectangle

h = Hue()
h.station_ip = '172.20.11.203'
h.get_state()
l = h.lights.get('l2')
l.set_state({
    "on": True,
    "sat": 254,
    "bri": 140,
    "xy": [0.3127,0.329] # Reset to White
})


def main():

    center     = detect_object()
    target_rgb = get_pics(center)
    target_lab = convert(target_rgb)

    vled       = [127,127,127] # White
    now_rgb    = [255, 255, 255]
    now_lab    = [255, 255, 255]
Esempio n. 44
0
def auth():
    '''
    Press the hue button!
    '''
    h = Hue()
    h.auth()
Esempio n. 45
0
def alert():
    l = Hue()
    l.alert()
Esempio n. 46
0
class HueLight():

    
    def __init__(self,id=-1,ip='192.168.1.99',lig='l1'):
        self.h = Hue()
        self.h.station_ip = ip

        self.h.get_state()
  
        self.level=60
        self.status=0
        self.id=id
        self.lig=lig
        self.color=[255,255,255,0,0]
        
        self.h.lights[self.lig].rgb(self.color[0],self.color[1],self.color[2])
        self.h.lights[self.lig].bri(self.level,1)
        self.h.lights[self.lig].off()
    def getId(self):
        return self.id
        #returns the ID
    def getWhoIm(self):
        print "HueLight"
        return "Hue Light"
        #returns what kind of object are
    def changeStatus(self):
        if self.status == 0 :
            self.status=1
            self.h.lights[self.lig].on()
            self.h.lights[self.lig].bri(self.level,1)
        else :
            self.h.lights[self.lig].off()
            self.status=0
        #here is going to change the status of the onject, example ON/OF
    def setIntensity(self,intensity=100):
        self.h.lights[self.lig].bri(self.level,1)
        #Intensity it means like a potenciometer, if I have a light is going to be the brignest of the light
        #de value of the intensity it shoud be between 0 and 255
    def setOn(self):
        self.h.lights[self.lig].on()
        self.status=1
        #Turns on the device
    def setOff(self):
        self.h.lights[self.lig].off()
        self.status=0
        #Turns off the device
    def setParameter(self,parameter=100):
        self.h.get_state()
        #This is going to be a caracteristinc, for example the color of the light also a value between 0 and 255
    def getParameter(self):
        self.h.get_state()
        #retunrs the parameter for example de color if its a light

    def getStatus(self):
        return self.status
    def copy(self):
        aux=[self.color[0],self.color[1],self.color[2],self.status,self.level]
        return aux
        
    def paste(self,data):
        
        if data[3]==1:
            if self.status==0 :
                self.setOn()
                self.status=1
            if data[0]!=-1 and data[1]!=-1 and data[2]!=-1:
                self.color[0]=data[0]
                self.color[1]=data[1]
                self.color[2]=data[2]
                self.color[3]=data[3]
                self.color[4]=data[4]
                self.level=data[4]
                self.updateColor()
                print "pasting intensity tooo to: "+ str ( self.level)
                self.setIntensity()
                print "-------------- I'm pasting----------------\n-------"+str(self.color)+"-------------\n"
                
            else :
                if data[4]!=-1:#audio copy
                    self.level=data[4]
                    self.setIntensity()
                    print "pasting intensity tooo to: "+ str ( self.level)
          
        else :
            self.status=0
            self.setOff()
    def Increase(self,value=40):
        self.level+=value
        if self.level > 255 :
            self.level=255
        self.h.lights[self.lig].bri(self.level,1)
    def Decrease(self,value=40):
        self.level-=value
        if self.level <5 :
            self.level=5
        self.h.lights[self.lig].bri(self.level,1)
        

    def Param_Increase(self,value=10):
        self.color[1]+=value
        self.color[2]-=value
        if self.color[1] >250 :
            self.color[1]=0
        if self.color[2] <0 :
            self.color[2]=250
        self.updateColor()

    def Param_Decrease(self,value=10):
        self.color[2]+=value
        self.color[1]-=value
        if self.color[2] >250 :
            self.color[2]=0
        if self.color[1] <0 :
            self.color[1]=250
        self.updateColor()

    def updateColor(self):
        try:
            self.h.lights[self.lig].rgb(self.color[0],self.color[1],self.color[2])
        except:
            print "colooooooooor errorrrr"
Esempio n. 47
0
import time
from hue import Hue
from camera import Camera
import RPi.GPIO as GPIO  # Raspberry Pi GPIO library

GPIO.setwarnings(False)  # Ignore warning for now
GPIO.setmode(GPIO.BOARD)  # Use physical pin numbering
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

pressed = False
hue = Hue()
camera = Camera()
camera.takePicture()

while True:  # Run forever
    if GPIO.input(10) == GPIO.HIGH and not (pressed):
        pressed = True
        print("Pressed -- toggle")
        hue.toggle()
    elif GPIO.input(10) == GPIO.LOW and pressed:
        pressed = False
        print("Released")
    time.sleep(0.1)
Esempio n. 48
0
class TestHue(object):

    def setup(self):
        self.hue = Hue('newdeveloper', 'localhost:8080')

    def test_init(self):
        assert_equal(self.hue.bridge_ip, 'localhost:8080')
        assert_equal(self.hue.user_id, 'newdeveloper')

    def test_groups(self):
        groups = [{u'name': u'Group 1', 'id': 1}]
        assert_equal(self.hue.groups(), groups)

    def test_single_group(self):
        group = {u'action': {u'on': True}, u'lights': [u'1', u'2'], u'name': u'Group 1'}
        assert_equal(self.hue.groups(1), group)

    def test_turn_on_group(self):
        result = {'resource': [{u'success': {u'/groups/1/action/on': True}}]}
        assert_equal(self.hue.group_set_on(1, True), result)

    def test_turn_off_group(self):
        result = {'resource': [{u'success': {u'/groups/1/action/on': False}}]}
        assert_equal(self.hue.group_set_on(1, False), result)

    def test_single_light(self):
        light = {
                u'name': u'Hue Lamp 1',
                u'swversion': u'65003148',
                u'pointsymbol': {
                    u'1': u'none',
                    u'3': u'none',
                    u'2': u'none',
                    u'5': u'none',
                    u'4': u'none',
                    u'7': u'none',
                    u'6': u'none',
                    u'8': u'none'
                },
                u'state': {
                    u'on': True,
                    u'hue': 0,
                    u'colormode': u'hs',
                    u'effect': u'none',
                    u'alert':
                    u'none',
                    u'xy': [0, 0],
                    u'reachable': True,
                    u'bri': 0,
                    u'sat': 0,
                    u'ct': 0
                },
                u'type': u'Extended color light',
                u'modelid': u'LCT001'
            }
        assert_equal(self.hue.lights(1), light)

    def test_turn_on_light(self):
        result = {'resource': [{u'success': {u'/lights/1/state/on': True}}]}
        assert_equal(self.hue.light_set_on(1, True), result)

    def test_turn_off_light(self):
        result = {'resource': [{u'success': {u'/lights/2/state/on': False}}]}
        assert_equal(self.hue.light_set_on(2, False), result)
#!/root/tony/python/bin/python

from hue import Hue
import time, datetime
import ConfigParser

p = ConfigParser.SafeConfigParser()
p.readfp(open("./light_runner.conf", "r"))

config_ip_address = p.get("config", "ip_address")
config_light_number = p.get("config", "light_number")
config_feedback_url = p.get("config", "feedback_url")

h = Hue()
h.station_ip = config_ip_address
# TC: 201602??
# the get_state will hang the program if the button is needed to be pressed
# we need a way to timeout this command
# if it has not come back in 15 write a log message and kill the program
res = h.get_state()

light2 = h.lights.get(config_light_number)

import requests
from requests.auth import HTTPBasicAuth


def get_prod_data():
    r = requests.get(config_feedback_url,
                     auth=HTTPBasicAuth("cbtadmin", "_w9y8ZdVtF"))
    return r.text
Esempio n. 50
0
def testhue(request):
    return Hue.discover_one('BasePythonHueClientTestUser')