Beispiel #1
0
class HueCommand:
    def __init__(self, duration, states):
        self.b = Bridge('********')
        self.duration = duration
        self.states = states

    def get_states(self, ids):
        lights = []
        for light_id in ids:
            is_on = self.b.get_light(light_id, 'on')
            bri = self.b.get_light(light_id, 'bri')
            hue = self.b.get_light(light_id, 'hue')
            lights.append({
                'id': light_id,
                'on': is_on,
                'hue': hue,
                'bri': bri
            })
        return lights

    def execute(self):
        # set hue bulbs
        self.b.connect()
        # Get a dictionary with the light ids as the key
        # lights = self.b.get_light_objects('id')

        for state in self.states:
            try:
                self.b.set_light(state.id, state.cmd)
            except Exception as e:
                print e.message
                continue

        time.sleep(self.duration)
Beispiel #2
0
def config_lights(ip):
    print('Retrieving lights...')
    bridge = Bridge(ip)
    lights = []
    for light in bridge.lights:
        try:
            bridge.get_light(light.name, 'colormode')
        except KeyError:
            pass
        else:
            lights.append(light.name)

    try:
        title = 'Please use the spacebar to select at least one light from the choices below: '
        selectedLights = pick(lights,
                              title,
                              multi_select=True,
                              min_selection_count=1,
                              indicator='->')
    except:
        print(
            'Sorry, setup was unable to find any color capable hue lights connected to your bridge.'
        )
        return
    else:
        goal_lights = {}
        goal_lights['Lights'] = []
        for light in selectedLights:
            goal_lights['Lights'].append(light[0])

    return goal_lights
Beispiel #3
0
 def get_status(self, log, device_id, address, bridge_ip):
     while not self._stop.isSet():
         data = {}
         try:
             b = Bridge(
                 ip=bridge_ip,
                 config_file_path=
                 "/var/lib/domogik/domogik_packages/plugin_hue/data/bridge.config"
             )
             b.connect()
             status = b.get_light(address, 'on')
             brightness = b.get_light(address, 'bri') / 254.00 * 100.00
             reachable = b.get_light(address, 'reachable')
             self.log.info(
                 u"==> Device '%s' state '%s', brightness '%s', reachable '%s'"
                 % (device_id, status, brightness, reachable))
             self.log.debug(u"Trying to send data sensor...")
         except:
             self.log.debug(u"Unable to get device information for id " +
                            str(device_id))
             pass
         data[self.sensors[device_id]
              ['light']] = self.from_off_on_to_DT_Switch(status)
         data[self.sensors[device_id]['brightness']] = brightness
         data[self.sensors[device_id]
              ['reachable']] = self.from_off_on_to_DT_Switch(reachable)
         try:
             self._pub.send_event('client.sensor', data)
         except:
             # We ignore the message if some values are not correct
             self.log.debug(
                 u"Bad MQ message to send. This may happen due to some invalid rainhour data. MQ data is : {0}"
                 .format(data))
             pass
         time.sleep(1)
Beispiel #4
0
class AutoHomeHue:
    hue = None

    def __init__(self):
        self.hue = Bridge(ip='10.90.0.106', config_file_path="/var/lib/hue/hue.conf")

    def lights(self):
        return self.hue.lights

    def lights_name(self):
        return self.hue.get_light_objects('name')

    def is_locked(self, lamp):
        return os.path.isfile("/var/lib/hue/locks/{}".format(lamp.light_id))

    def lock(self, lamp):
        open("/var/lib/hue/locks/{}".format(lamp.light_id), 'a').close()

    def unlock(self, lamp):
        os.remove("/var/lib/hue/locks/{}".format(lamp.light_id))

    def brightness(self, lamp, value, time=100):
        lamp.on = True
        self.hue.set_light(lamp.light_id, 'bri', value, transitiontime=time)

    def color(self, lamp, hue=None, sat=None, xy=None):
        lamp.on = True
        if hue:
            lamp.hue = hue
        if sat:
            lamp.sat = sat
        if xy:
            lamp.xy = xy

    def time_based_white(self, light):
        if not self.hue.get_light(light.name, 'on'): return False
        if not self.hue.get_light(light.name, 'reachable'): return False

        hour = datetime.datetime.now().hour

        # Be nice, show a nice warm light
        # between 00:00 - 08:00
        if hour < 8:
            hour = 24

        ct = 154 + ((500-154)/24) * hour

        if light.light_id != 13 and light.colortemp != ct:
            self.hue.set_light(light.name, 'ct', ct)
            return True

        return False
Beispiel #5
0
def get_office_lights():
    ''' Gets the current state of my office lights so I know what values
    to plug in to presets.

    '''
    from phue import Bridge
    b = Bridge(settings.HUE_BRIDGE)
    b.connect()
    b.get_api()
    light_index = 9
    print b.get_light(light_index, 'on')
    print b.get_light(light_index, 'hue')
    print b.get_light(light_index, 'sat')
Beispiel #6
0
def main(args):
    global b
    b = Bridge(args.ip)
    if args.id:
        lid = int(args.id)
        if args.off:
            set_light(lid, False)
        else:
            set_light(lid, not b.get_light(lid, 'on'))

    elif args.off:
        set_light(1, False)
    else:
        set_light(1, not b.get_light(1, 'on'))
class CommonHardwareHue(object):
    """
    Class for interfacing with hue
    """

    def __init__(self, ip_addr):
        self.hue_inst = Bridge(ip_addr, config_file_path='/mediakraken/phue/phue.config')
        # 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)
        self.hue_inst.connect()

    def com_hardware_hue_get_api(self):
        # Get the bridge state (This returns the full dictionary that you can explore)
        return self.hue_inst.get_api()

    def com_hardware_hue_get_lights(self):
        return self.com_hardware_hue_get_api()['lights']

    def com_hardware_hue_light_info(self, light_num, status_type):
        # 'on' - wether on/off
        # 'name' - name of light
        return self.hue_inst.get_light(light_num, status_type)

    def com_hardware_hue_light_set(self, light_list, function_type='on', var_value=True):
        # You can also control multiple lamps by sending a list as lamp_id
        # 'on' on/off via bool
        # 'bri' 1-100 value for brightness
        self.hue_inst.set_light(light_list, function_type, var_value)
Beispiel #8
0
def lights_shift_ko(hermes, intent_message):
    # type: (Hermes, IntentMessage) -> None
    ip, user, no = read_configuration_file(CONFIG_FILE)
    bridge = Bridge(ip, user)
    slot_map = to_slot_map(intent_message)
    brightness = bridge.get_light(no, "bri")
    print "brightness", brightness

    up_down = slot_map.get("up_down")[0]
    print dir(up_down.slot_value.value.value)
    if up_down.slot_value.value.value == "up":
        up = True
    else:
        up = False
    if up:
        brightness = brightness + 25
        if brightness > 254:
            brightness = 254
            message += u"最大値でつけました"
        else:
            message += u"明るくしました"
        print bridge.set_light(no, command(bri=brightness))
    else:
        brightness = brightness - 25
        if brightness < 0:
            brightness = 0
            message += u"消しました"
        else:
            message += u"暗くしました"
        print bridge.set_light(no, command(bri=brightness))
Beispiel #9
0
def process_request(req):
    result = req.get('result')
    if result is None:
        return {}
    parameters = result.get('parameters')
    if parameters is None:
        return {}
    state = parameters.get('LightState')
    if state is None:
        return {}

    speech = ""
    b = Bridge(huehost)
    b.connect()
    # b.get_api()

    # Should take groupname into account when deciding on which lamp to turn on
    # b.get_group()
    if state == "on" or state == "On":
        if not b.get_light(1, 'on'):
            b.set_light(1, 'on', True)
            b.set_light(1, 'bri', 254)
            speech = "Turned lamp on"
        else:
            speech = "Lamp was already on."
    elif state == "off" or state == "Off":
        if b.get_light(1, 'on'):
            b.set_light(1, 'on', False)
            speech = "Turned lamp off"
        else:
            speech = "Lamp was already off"

    else:
        speech = "I couldn't understand the lampstate: " + state

    return {
        "speech": speech,
        "displayText": speech,
        # "data": data,
        # "contextOut": [],
        "source": "apiai-hue-webhook"
    }
Beispiel #10
0
class PhueOnOffManager:
  def __init__(self, addr, lightname):
    self.b = Bridge(addr)
    self.b.connect()
    self.lightname = lightname

  def read(self):
    value = self.b.get_light(self.lightname, 'on')
    return str(value)

  def write(self, value):
    self.b.set_light(self.lightname, 'on', value)
Beispiel #11
0
class LightSkill(object):

    def __init__(self):

        self.bridge = Bridge('192.168.1.10')
        self.bridge.connect()

        self.intent = 'lightIntent'

        # define vocabulary
        self.light_keyword = [
                "allume",
                "éteint",
                "baisse",
                "diminue",
                "augmente",
                "luminosité"
                ]

        self.room_keyword = [
                "salon",
                "cuisine"
                ]

        # structure intent
        self.light_intent = IntentBuilder(self.intent)\
                .require("LightKeyword")\
                .require("RoomKeyword")\
                .optionally("NumericValue")\
                .build()

    def register(self, engine):
        for wk in self.light_keyword:
            engine.register_entity(wk, "LightKeyword")
        for wk in self.room_keyword:
            engine.register_entity(wk, "RoomKeyword")
        engine.register_regex_entity("(?P<NumericValue>\d+)")
        engine.register_intent_parser(self.light_intent)

    def process(self, json):
         room = json.get('RoomKeyword')
         if json.get('LightKeyword') == "allume":
            self.bridge.set_light(room, 'on', True)
            return "J'allume '%s'" % room
         if json.get('LightKeyword') == "éteint":
            self.bridge.set_light(room, 'on', False)
            return "J'éteins '%s'" % room
         if json.get('LightKeyword') == "baisse":
             bri = self.bridge.get_light(room).get('state').get('bri')
             self.bridge.set_light(room, 'bri', bri-20)
             return "J'ai diminué la lumière dans le '%s'" % room
def find_a_light():
    """Finds an appropriate light and returns it."""

    hue = Bridge('192.168.1.11')
    # If running for the first time:
    # press button on bridge and run with b.connect() uncommented
    # b.connect()

    lights = hue.get_light_objects('name')

    # reachable is supposed to be an option but isn't..?
    # if lights['Bedroom ceiling'].reachable:
    if (hue.get_light('Bedroom ceiling')['state']['reachable'] and
            hue.get_light('Bedroom ceiling')['state']['on']):
        alert_light = lights['Bedroom ceiling']

    elif (hue.get_light('Bedroom bed')['state']['reachable'] and
            hue.get_light('Bedroom bed')['state']['on']):
        alert_light = lights['Bedroom bed']

    elif hue.get_light('Bedroom desk')['state']['reachable']:
        alert_light = lights['Bedroom desk']

    return alert_light
Beispiel #13
0
def list_lights(ip):
    output = ""
    try:
        b = Bridge(
            ip=ip,
            config_file_path=
            "/var/lib/domogik/domogik_packages/plugin_hue/data/bridge.config")
        b.connect()
        lights = b.get_light()
        for light in lights:
            output += "Light ID : " + light[0] + "\n"
            output += "    Name : " + lights[light]["name"] + "\n"
            output += "\n"
    except:
        output = "Error while retrieving Hue lamps... Have you push the bridge button?"
    return output
Beispiel #14
0
class HueControl():

    def initBridge(self, ip):
        self.bridge = Bridge(ip)
        self.bridge.connect()
        self.bridge.get_api()

    def __init__(self, jarvis, hueBridgeIP):
        self.initBridge(hueBridgeIP)
        self.jarvis = jarvis

    def setHue(self, hueValue):
        """
        Set Hue from 0 to 65280
        """
        
        self.bridge.set_light(2,'hue', hueValue)

    def setSaturation(self, satValue):
        """
        Set Saturation from 0 to 254
        """
        
        self.bridge.set_light(2,'sat', hueValue)

    def setBrightness(self, briValue):
        """
        Set brightness from 0 to 254
        """
        
        self.bridge.set_light(2,'bri', hueValue)

    def setCommand(self, command):
        
        self.bridge.set_light(2, command)

    def setState(self, state):
        
        self.bridge.set_light(2,'on', state)

    def getState(self):
        
        return self.bridge.get_light(2,'on')

    def toggleState(self):
        wantedState = not self.getState()
        self.setState(wantedState)
Beispiel #15
0
class PhueOnOffManager:
    def __init__(self, addr, lightname):
        self.b = Bridge(addr)
        self.b.connect()
        self.lightname = lightname

    def read(self):
        value = self.b.get_light(self.lightname, 'bri')
        return int(value)

    def write(self, value):
        if value > 254:
            value = 254
        elif value < 0:
            value = 0

        self.b.set_light(self.lightname, 'bri', value)
Beispiel #16
0
class HueControl():
    def initBridge(self, ip):
        self.bridge = Bridge(ip)
        self.bridge.connect()
        self.bridge.get_api()

    def __init__(self, jarvis, hueBridgeIP):
        self.initBridge(hueBridgeIP)
        self.jarvis = jarvis

    def setHue(self, hueValue):
        """
        Set Hue from 0 to 65280
        """

        self.bridge.set_light(2, 'hue', hueValue)

    def setSaturation(self, satValue):
        """
        Set Saturation from 0 to 254
        """

        self.bridge.set_light(2, 'sat', hueValue)

    def setBrightness(self, briValue):
        """
        Set brightness from 0 to 254
        """

        self.bridge.set_light(2, 'bri', hueValue)

    def setCommand(self, command):

        self.bridge.set_light(2, command)

    def setState(self, state):

        self.bridge.set_light(2, 'on', state)

    def getState(self):

        return self.bridge.get_light(2, 'on')

    def toggleState(self):
        wantedState = not self.getState()
        self.setState(wantedState)
Beispiel #17
0
class Hue:
  def __init__(self):
    self.ip = 'Philips-hue.local'
    self.bridge = Bridge(self.ip)

  def pink(self) :
    self.bridge.set_light('Strip', { 'hue' : 3000, 'bri' : 220 })

  def on(self) :
    self.bridge.set_light('Strip', 'on', True)

  def off(self) :
    self.bridge.set_light('Strip', 'on', False)

  def toggle(self) :
    if self.bridge.get_light('Strip', 'on') :
      self.off()
    else :
      self.on()
def read_bulb_state():
    state = None
    try:
        b = Bridge(HUE_BRIGE_IP)

        # 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()

        bulb_state = b.get_light(HUE_BULB_NAME)
        if 'name' in bulb_state:
            print(bulb_state['state']['on'])
            print(bulb_state['state']['bri'])
            state = bulb_state['state']
        else:
            print("Error reading bulb state: ", bulb_state[0]['error'])
    except Exception as e:
        s = traceback.format_exc()
        print("unexpected failure, {} ,{}".format(e, s))

    return state
def control_light(bridge_ip,
                  key,
                  room_name,
                  light_id,
                  new_state,
                  dry_run=False):
    assert new_state in (True, False)
    logger.info("Setting light %s(%s) to %s" %
                (room_name, light_id, "ON" if new_state else "OFF"))
    if dry_run:
        return
    b = Bridge(bridge_ip, username=key)
    b.get_api()
    b.set_light(light_id, {'on': new_state})
    result = b.get_light(light_id)
    if result['state']['on'] == new_state:
        logger.info("  Set light %s to %s" %
                    (light_id, "ON" if new_state else "OFF"))
    else:
        logger.info("  Tried to set light %s to %s, but new state is %s" %
                    (light_id, new_state, result['state']['on']))
Beispiel #20
0
def main():
    hue_bridge = Bridge(BRIDGE_IP)

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

    # turn the lamp on if it is not already, make note of what color lamp is currently set at
    hue_bridge.set_light(LIGHT_ID, 'on', True)
    initial_state = hue_bridge.get_light(LIGHT_ID)['state']

    # Get weather Info
    max_temp, rain_probabilities = get_weather(WEATHER_URL)
    yday_temp = get_yesterday_temp(TEMPERATURE_FILE)

    # Change lamp color depending on weather data
    change_color(yday_temp, max_temp, rain_probabilities, hue_bridge)

    # delay for 2 hour then set lamp to previous color
    time.sleep(7200)
    hue_bridge.set_light(LIGHT_ID, initial_state)
    save_max_temp(TEMPERATURE_FILE, max_temp)
Beispiel #21
0
class HueService(ParentService):
    def __init__(self, ip=None):
        self.ip = ip
        self.id = None
        self.bridge = Bridge(self.ip)

    def get_function(self, message=None):
        api = self.bridge.get_api()
        for each_light in api['lights']:
            if (api['lights'][each_light]['name'].lower() == message.get(
                    "bulb_name", "none").lower()):
                self.id = each_light

        return self.toggle

    def toggle(self):
        self.bridge.connect()
        curr_state = self.bridge.get_light(int(self.id), 'on')
        if curr_state:
            self.bridge.set_light(int(self.id), 'on', False)
        else:
            self.bridge.set_light(int(self.id), 'on', True)
Beispiel #22
0
class Hue():
    def __init__(self, bridge, lightbulb=None):
        self.bridgeAddress = bridge
        self.lightsMap = {}

        if lightbulb:
            m = re.split('\s*,\s*', lightbulb)
            self.lightbulbs = m if m else [lightbulb]

    def connect(self):
        self.bridge = Bridge(self.bridgeAddress)
        self.bridge.connect()
        self.bridge.get_api()

        for light in self.bridge.lights:
            self.lightsMap[light.name] = light

        if not hasattr(self, 'lightbulbs'):
            self.lightbulbs = []
            for light in self.bridge.lights:
                self.lightbulbs.append(light.name)

    def setBri(self, bri):
        if bri == 0:
            for light in self.lightbulbs:
                self.bridge.set_light(light, 'on', False)
        else:
            for light in self.lightbulbs:
                if not self.bridge.get_light(light, 'on'):
                    self.bridge.set_light(light, 'on', True)

        self.bridge.set_light(self.lightbulbs, 'bri', bri)

    def setSat(self, sat):
        self.bridge.set_light(self.lightbulbs, 'sat', sat)

    def setHue(self, hue):
        self.bridge.set_light(self.lightbulbs, 'hue', hue)
Beispiel #23
0
def handle(text, luna, profile):
	bridge = Bridge('192.168.178.85')

	xy = bridge.get_light(1, 'xy')
	print('XY: {}'.format(xy))
Beispiel #24
0
class Component(ThreadComponent):
    MATRIX = matrices.LIGHT_BULB

    def __init__(self, component_config):
        super().__init__(component_config)

        self.bridge = Bridge(component_config['ip_address'],
                             component_config['username'])

        self.delta_range = range(-254, 254)
        self.delta = 0

        # Extract light IDs, they are stored with format `<bridgeID>-light-<lightID>`
        light_ids = component_config['device_ids']
        light_ids = [i.split('-light-')[1].strip() for i in light_ids]

        self.lights = self.create_lights(light_ids)
        self.lights.update_state()

        self.station_id_1 = component_config.get('station1', None)
        self.station_id_2 = component_config.get('station2', None)
        self.station_id_3 = component_config.get('station3', None)

        # seed random nr generator (used to get random color value)
        seed()

    def create_lights(self, light_ids):
        reachable_lights = self.filter_reachable(light_ids)
        if not reachable_lights:
            lights = EmptyLightSet()
        elif len(reachable_lights) > 10:
            lights = Group(self.bridge, reachable_lights)
        else:
            lights = LightSet(self.bridge, reachable_lights)

        return lights

    def filter_reachable(self, light_ids):
        lights = self.bridge.get_light()
        reachable = [
            i for i in light_ids
            if i in lights and lights[i]['state']['reachable']
        ]
        logger.debug("lights: %s reachable: %s", list(lights.keys()),
                     reachable)
        return reachable

    def on_button_press(self):
        self.set_light_attributes(on=not self.lights.on)

    def on_longtouch_left(self):
        logger.debug("on_longtouch_left()")
        if self.station_id_1 is not None:
            self.bridge.activate_scene('0', self.station_id_1)
            self.nuimo.display_matrix(matrices.STATION1)

    def on_longtouch_bottom(self):
        logger.debug("on_longtouch_bottom()")
        if self.station_id_2 is not None:
            self.bridge.activate_scene('0', self.station_id_2)
            self.nuimo.display_matrix(matrices.STATION2)

    def on_longtouch_right(self):
        logger.debug("on_longtouch_right()")
        if self.station_id_3 is not None:
            self.bridge.activate_scene('0', self.station_id_3)
            self.nuimo.display_matrix(matrices.STATION3)

    def set_light_attributes(self, **attributes):
        response = self.lights.set_attributes(attributes)

        if 'errors' in response:
            logger.error("Failed to set light attributes: %s",
                         response['errors'])
            self.nuimo.display_matrix(matrices.ERROR)
            return

        if 'xy' in attributes:
            if 'bri' in attributes:
                self.nuimo.display_matrix(matrices.LETTER_W)
            else:
                self.nuimo.display_matrix(matrices.SHUFFLE)

        elif 'on' in attributes and not ('bri_inc' in attributes):
            if self.lights.on:
                self.nuimo.display_matrix(matrices.LIGHT_ON)
            else:
                self.nuimo.display_matrix(matrices.LIGHT_OFF)

        elif 'bri' in attributes or 'bri_inc' in attributes:
            if self.lights.brightness:
                matrix = matrices.progress_bar(self.lights.brightness /
                                               self.delta_range.stop)
                self.nuimo.display_matrix(matrix,
                                          fading=True,
                                          ignore_duplicates=True)
            else:
                self.set_light_attributes(on=False)

    def on_swipe_left(self):
        self.set_light_attributes(on=True,
                                  bri=self.lights.brightness,
                                  xy=COLOR_WHITE_XY)

    def on_swipe_right(self):
        self.set_light_attributes(on=True, xy=(random(), random()))

    def on_rotation(self, value):
        self.delta += value

    def run(self):
        prev_sync_time = time()
        prev_update_time = time()

        while not self.stopped:
            now = time()

            if self.delta and now - prev_update_time >= self.lights.update_interval:
                self.send_updates()
                self.delta = 0

                prev_update_time = now

            if now - max([prev_sync_time, prev_update_time
                          ]) >= self.lights.sync_interval:
                self.lights.update_state()

                prev_sync_time = now

            sleep(0.05)

    def send_updates(self):
        delta = round(
            clamp_value(self.delta_range.stop * self.delta, self.delta_range))

        if self.lights.on:
            self.set_light_attributes(bri_inc=delta)
        else:
            if delta > 0:
                self.set_light_attributes(on=True)
                self.set_light_attributes(bri_inc=delta)
Beispiel #25
0
    b.connect()
    print("connecting to bridge...")
else:
    print("bridge is connected")

print(b.get_group(1, 'lights'))
#/BRIDGE SETUP

#GET COLOR LIGHTS
for room in b.get_group():
    for name in rainbowRooms:
        iRoom = int(room)
        if b.get_group(iRoom, 'name') == name.__str__():
            for light in b.get_group(iRoom, 'lights'):
                iLight = int(light)
                if b.get_light(iLight, 'type') == "Extended color light":
                    colorLights.append(b.get_light(iLight, 'name'))
                    b.set_light(iLight, 'on', True)
                    b.set_light(iLight, 'bri', 254)

print(colorLights)
#/GET COLOR LIGHTS

#RAINBOW
while playing:
    for x in my_range(0, 1, .05):
        for cLight in colorLights:
            b.set_light(cLight, 'xy', [0, 1 - x])
        time.sleep(intervalTime)

    for x in my_range(0, 1, .05):
#!/usr/bin/python

from phue import Bridge
import pprint

# hard coded ip address, found by looking at the router settings.
b = Bridge('10.0.0.44')

# only use the first group
group = b.get_group(1)

# print current status
print(f"Any lights on in {group['name']}: {group['state']['any_on']}")
light_status = "["
for light in group['lights']:
    light = b.get_light(int(light))
    status = f"{light['state']['bri']:3}" if light['state']['on'] else "off"
    light_status += f"({light['name']}: {status}), "
print(light_status[:-2]+"]")

# print available scenes and inputs
indexed_scenes = list(enumerate([scene.name for scene in b.scenes]))
print("Available scenes:")
pprint.pp(indexed_scenes)
commands = input("Enter scene index, 'on', 'off', or -brightness value (1-255) (empty cancels): ")

# handle the command(s) given
for command in commands.split():
    if command == "":
        pass
    elif command == 'on':
Beispiel #27
0
class LightHuePlugin(LightPlugin):
    """
    Philips Hue lights plugin.

    Requires:

        * **phue** (``pip install phue``)
    """

    MAX_BRI = 255
    MAX_SAT = 255
    MAX_HUE = 65535
    ANIMATION_CTRL_QUEUE_NAME = 'platypush/light/hue/AnimationCtrl'
    _BRIDGE_RECONNECT_SECONDS = 5
    _MAX_RECONNECT_TRIES = 5

    class Animation(Enum):
        COLOR_TRANSITION = 'color_transition'
        BLINK = 'blink'

        def __eq__(self, other):
            if isinstance(other, str):
                return self.value == other
            elif isinstance(other, self.__class__):
                return self == other

    def __init__(self, bridge, lights=None, groups=None):
        """
        :param bridge: Bridge address or hostname
        :type bridge: str

        :param lights: Default lights to be controlled (default: all)
        :type lights: list[str]

        :param groups Default groups to be controlled (default: all)
        :type groups: list[str]
        """

        super().__init__()

        self.bridge_address = bridge
        self.bridge = None
        self.logger.info('Initializing Hue lights plugin - bridge: "{}"'.format(self.bridge_address))

        self.connect()
        self.lights = []; self.groups = []

        if lights:
            self.lights = lights
        elif groups:
            self.groups = groups
            self._expand_groups()
        else:
            self.lights = [l.name for l in self.bridge.lights]

        self.redis = None
        self.animation_thread = None
        self.animations = {}
        self._init_animations()
        self.logger.info('Configured lights: "{}"'. format(self.lights))

    def _expand_groups(self):
        groups = [g for g in self.bridge.groups if g.name in self.groups]
        for g in groups:
            for l in g.lights:
                self.lights += [l.name]

    def _init_animations(self):
        self.animations = {
            'groups': {},
            'lights': {},
        }

        for g in self.bridge.groups:
            self.animations['groups'][g.group_id] = None
        for l in self.bridge.lights:
            self.animations['lights'][l.light_id] = None

    @action
    def connect(self):
        """
        Connect to the configured Hue bridge. If the device hasn't been paired
        yet, uncomment the ``.connect()`` and ``.get_api()`` lines and retry
        after clicking the pairing button on your bridge.
        """

        # Lazy init
        if not self.bridge:
            from phue import Bridge, PhueRegistrationException
            success = False
            n_tries = 0

            while not success:
                try:
                    n_tries += 1
                    self.bridge = Bridge(self.bridge_address)
                    success = True
                except PhueRegistrationException as e:
                    self.logger.warning('Bridge registration error: {}'.
                                        format(str(e)))

                    if n_tries >= self._MAX_RECONNECT_TRIES:
                        self.logger.error(('Bridge registration failed after ' +
                                           '{} attempts').format(n_tries))
                        break

                    time.sleep(self._BRIDGE_RECONNECT_SECONDS)

            self.logger.info('Bridge connected')
            self.get_scenes()
        else:
            self.logger.info('Bridge already connected')

    @action
    def get_scenes(self):
        """
        Get the available scenes on the devices.

        :returns: The scenes configured on the bridge.

        Example output::

            {
                "scene-id-1": {
                    "name": "Scene 1",
                    "lights": [
                        "1",
                        "3"
                    ],

                    "owner": "owner-id",
                    "recycle": true,
                    "locked": false,
                    "appdata": {},
                    "picture": "",
                    "lastupdated": "2018-06-01T00:00:00",
                    "version": 1
                }
            }

        """

        return self.bridge.get_scene()

    @action
    def get_lights(self):
        """
        Get the configured lights.

        :returns: List of available lights as id->dict.

        Example::

            {
                "1": {
                    "state": {
                        "on": true,
                        "bri": 254,
                        "hue": 1532,
                        "sat": 215,
                        "effect": "none",
                        "xy": [
                            0.6163,
                            0.3403
                        ],

                        "ct": 153,
                        "alert": "none",
                        "colormode": "hs",
                        "reachable": true
                    },

                    "type": "Extended color light",
                    "name": "Lightbulb 1",
                    "modelid": "LCT001",
                    "manufacturername": "Philips",
                    "uniqueid": "00:11:22:33:44:55:66:77-88",
                    "swversion": "5.105.0.21169"
                }
            }

        """

        return self.bridge.get_light()

    @action
    def get_groups(self):
        """
        Get the list of configured light groups.

        :returns: List of configured light groups as id->dict.

        Example::

            {
                "1": {
                    "name": "Living Room",
                    "lights": [
                        "16",
                        "13",
                        "12",
                        "11",
                        "10",
                        "9",
                        "1",
                        "3"
                    ],

                    "type": "Room",
                    "state": {
                        "all_on": true,
                        "any_on": true
                    },

                    "class": "Living room",
                    "action": {
                        "on": true,
                        "bri": 241,
                        "hue": 37947,
                        "sat": 221,
                        "effect": "none",
                        "xy": [
                            0.2844,
                            0.2609
                        ],

                        "ct": 153,
                        "alert": "none",
                        "colormode": "hs"
                    }
                }
            }

        """

        return self.bridge.get_group()

    @action
    def get_animations(self):
        """
        Get the list of running light animations.

        :returns: dict.

        Structure::

            {
                "groups": {
                    "id_1": {
                        "type": "color_transition",
                        "hue_range": [0,65535],
                        "sat_range": [0,255],
                        "bri_range": [0,255],
                        "hue_step": 10,
                        "sat_step": 10,
                        "bri_step": 2,
                        "transition_seconds": 2

                    }

                },

                "lights": {
                    "id_1": {}

                }

            }

        """

        return self.animations

    def _exec(self, attr, *args, **kwargs):
        try:
            self.connect()
            self.stop_animation()
        except Exception as e:
            # Reset bridge connection
            self.bridge = None
            raise e

        lights = []; groups = []
        if 'lights' in kwargs:
            lights = kwargs.pop('lights').split(',').strip() \
                if isinstance(lights, str) else kwargs.pop('lights')
        if 'groups' in kwargs:
            groups = kwargs.pop('groups').split(',').strip() \
                if isinstance(groups, str) else kwargs.pop('groups')

        if not lights and not groups:
            lights = self.lights
            groups = self.groups

        if not self.bridge:
            self.connect()

        try:
            if attr == 'scene':
                self.bridge.run_scene(groups[0], kwargs.pop('name'))
            else:
                if groups:
                    self.bridge.set_group(groups, attr, *args, **kwargs)
                if lights:
                    self.bridge.set_light(lights, attr, *args, **kwargs)
        except Exception as e:
            # Reset bridge connection
            self.bridge = None
            raise e

    @action
    def set_light(self, light, **kwargs):
        """
        Set a light (or lights) property.

        :param light: Light or lights to set. Can be a string representing the light name,
            a light object, a list of string, or a list of light objects.
        :param kwargs: key-value list of parameters to set.

        Example call::

            {
                "type": "request",
                "target": "hostname",
                "action": "light.hue.set_light",
                "args": {
                    "light": "Bulb 1",
                    "sat": 255
                }
            }

        """

        self.connect()
        self.bridge.set_light(light, **kwargs)

    @action
    def set_group(self, group, **kwargs):
        """
        Set a group (or groups) property.

        :param group: Group or groups to set. Can be a string representing the group name, a group object, a list of strings, or a list of group objects.
        :param kwargs: key-value list of parameters to set.

        Example call::

            {
                "type": "request",
                "target": "hostname",
                "action": "light.hue.set_group",
                "args": {
                    "light": "Living Room",
                    "sat": 255
                }
            }

        """

        self.connect()
        self.bridge.set_group(group, **kwargs)

    @action
    def on(self, lights=None, groups=None, **kwargs):
        """
        Turn lights/groups on.

        :param lights: Lights to turn on (names or light objects). Default: plugin default lights
        :param groups: Groups to turn on (names or group objects). Default: plugin default groups
        """

        if groups is None:
            groups = []
        if lights is None:
            lights = []
        return self._exec('on', True, lights=lights, groups=groups, **kwargs)

    @action
    def off(self, lights=None, groups=None, **kwargs):
        """
        Turn lights/groups off.

        :param lights: Lights to turn off (names or light objects). Default: plugin default lights
        :param groups: Groups to turn off (names or group objects). Default: plugin default groups
        """

        if groups is None:
            groups = []
        if lights is None:
            lights = []
        return self._exec('on', False, lights=lights, groups=groups, **kwargs)

    @action
    def toggle(self, lights=None, groups=None, **kwargs):
        """
        Toggle lights/groups on/off.

        :param lights: Lights to turn off (names or light objects). Default: plugin default lights
        :param groups: Groups to turn off (names or group objects). Default: plugin default groups
        """

        if groups is None:
            groups = []
        if lights is None:
            lights = []
        lights_on  = []
        lights_off = []
        groups_on  = []
        groups_off = []

        if groups:
            all_groups = self.bridge.get_group().values()

            groups_on = [
                group['name'] for group in all_groups
                if group['name'] in groups and group['state']['any_on'] is True
            ]

            groups_off = [
                group['name'] for group in all_groups
                if group['name'] in groups and group['state']['any_on'] is False
            ]

        if not groups and not lights:
            lights = self.lights

        if lights:
            all_lights = self.bridge.get_light().values()

            lights_on = [
                light['name'] for light in all_lights
                if light['name'] in lights and light['state']['on'] is True
            ]

            lights_off = [
                light['name'] for light in all_lights
                if light['name'] in lights and light['state']['on'] is False
            ]

        if lights_on or groups_on:
            self._exec('on', False, lights=lights_on, groups=groups_on, **kwargs)

        if lights_off or groups_off:
            self._exec('on', True, lights=lights_off, groups=groups_off, **kwargs)

    @action
    def bri(self, value, lights=None, groups=None, **kwargs):
        """
        Set lights/groups brightness.

        :param lights: Lights to control (names or light objects). Default: plugin default lights
        :param groups: Groups to control (names or group objects). Default: plugin default groups
        :param value: Brightness value (range: 0-255)
        """

        if groups is None:
            groups = []
        if lights is None:
            lights = []
        return self._exec('bri', int(value) % (self.MAX_BRI+1),
                          lights=lights, groups=groups, **kwargs)

    @action
    def sat(self, value, lights=None, groups=None, **kwargs):
        """
        Set lights/groups saturation.

        :param lights: Lights to control (names or light objects). Default: plugin default lights
        :param groups: Groups to control (names or group objects). Default: plugin default groups
        :param value: Saturation value (range: 0-255)
        """

        if groups is None:
            groups = []
        if lights is None:
            lights = []
        return self._exec('sat', int(value) % (self.MAX_SAT+1),
                          lights=lights, groups=groups, **kwargs)

    @action
    def hue(self, value, lights=None, groups=None, **kwargs):
        """
        Set lights/groups color hue.

        :param lights: Lights to control (names or light objects). Default: plugin default lights
        :param groups: Groups to control (names or group objects). Default: plugin default groups
        :param value: Hue value (range: 0-65535)
        """

        if groups is None:
            groups = []
        if lights is None:
            lights = []
        return self._exec('hue', int(value) % (self.MAX_HUE+1),
                          lights=lights, groups=groups, **kwargs)

    @action
    def xy(self, value, lights=None, groups=None, **kwargs):
        """
        Set lights/groups XY colors.

        :param value: xY value
        :type value: list[float] containing the two values
        """
        if groups is None:
            groups = []
        if lights is None:
            lights = []
        return self._exec('xy', value, lights=lights, groups=groups, **kwargs)

    @action
    def ct(self, value, lights=None, groups=None, **kwargs):
        """
        Set lights/groups color temperature.

        :param value: Temperature value (range: 0-255)
        :type value: int
        """
        if groups is None:
            groups = []
        if lights is None:
            lights = []
        return self._exec('ct', value, lights=lights, groups=groups, **kwargs)

    @action
    def delta_bri(self, delta, lights=None, groups=None, **kwargs):
        """
        Change lights/groups brightness by a delta [-100, 100] compared to the current state.

        :param lights: Lights to control (names or light objects). Default: plugin default lights
        :param groups: Groups to control (names or group objects). Default: plugin default groups
        :param delta: Brightness delta value (range: -100, 100)
        """

        if groups is None:
            groups = []
        if lights is None:
            lights = []
        bri = 0

        if lights:
            bri = statistics.mean([
                light['state']['bri']
                for light in self.bridge.get_light().values()
                if light['name'] in lights
            ])
        elif groups:
            bri = statistics.mean([
                group['action']['bri']
                for group in self.bridge.get_group().values()
                if group['name'] in groups
            ])
        else:
            bri = statistics.mean([
                light['state']['bri']
                for light in self.bridge.get_light().values()
                if light['name'] in self.lights
            ])

        delta *= (self.MAX_BRI/100)
        if bri+delta < 0:
            bri = 0
        elif bri+delta > self.MAX_BRI:
            bri = self.MAX_BRI
        else:
            bri += delta

        return self._exec('bri', int(bri), lights=lights, groups=groups, **kwargs)

    @action
    def delta_sat(self, delta, lights=None, groups=None, **kwargs):
        """
        Change lights/groups saturation by a delta [-100, 100] compared to the current state.

        :param lights: Lights to control (names or light objects). Default: plugin default lights
        :param groups: Groups to control (names or group objects). Default: plugin default groups
        :param delta: Saturation delta value (range: -100, 100)
        """

        if groups is None:
            groups = []
        if lights is None:
            lights = []
        sat = 0

        if lights:
            sat = statistics.mean([
                light['state']['sat']
                for light in self.bridge.get_light().values()
                if light['name'] in lights
            ])
        elif groups:
            sat = statistics.mean([
                group['action']['sat']
                for group in self.bridge.get_group().values()
                if group['name'] in groups
            ])
        else:
            sat = statistics.mean([
                light['state']['sat']
                for light in self.bridge.get_light().values()
                if light['name'] in self.lights
            ])

        delta *= (self.MAX_SAT/100)
        if sat+delta < 0:
            sat = 0
        elif sat+delta > self.MAX_SAT:
            sat = self.MAX_SAT
        else:
            sat += delta

        return self._exec('sat', int(sat), lights=lights, groups=groups, **kwargs)

    @action
    def delta_hue(self, delta, lights=None, groups=None, **kwargs):
        """
        Change lights/groups hue by a delta [-100, 100] compared to the current state.

        :param lights: Lights to control (names or light objects). Default: plugin default lights
        :param groups: Groups to control (names or group objects). Default: plugin default groups
        :param delta: Hue delta value (range: -100, 100)
        """

        if groups is None:
            groups = []
        if lights is None:
            lights = []
        hue = 0

        if lights:
            hue = statistics.mean([
                light['state']['hue']
                for light in self.bridge.get_light().values()
                if light['name'] in lights
            ])
        elif groups:
            hue = statistics.mean([
                group['action']['hue']
                for group in self.bridge.get_group().values()
                if group['name'] in groups
            ])
        else:
            hue = statistics.mean([
                light['state']['hue']
                for light in self.bridge.get_light().values()
                if light['name'] in self.lights
            ])

        delta *= (self.MAX_HUE/100)
        if hue+delta < 0:
            hue = 0
        elif hue+delta > self.MAX_HUE:
            hue = self.MAX_HUE
        else:
            hue += delta

        return self._exec('hue', int(hue), lights=lights, groups=groups, **kwargs)

    @action
    def scene(self, name, lights=None, groups=None, **kwargs):
        """
        Set a scene by name.

        :param lights: Lights to control (names or light objects). Default: plugin default lights
        :param groups: Groups to control (names or group objects). Default: plugin default groups
        :param name: Name of the scene
        """

        if groups is None:
            groups = []
        if lights is None:
            lights = []
        return self._exec('scene', name=name, lights=lights, groups=groups, **kwargs)

    @action
    def is_animation_running(self):
        """
        :returns: True if there is an animation running, false otherwise.
        """

        return self.animation_thread is not None

    @action
    def stop_animation(self):
        """
        Stop a running animation if any
        """

        if self.animation_thread and self.animation_thread.is_alive():
            redis = self._get_redis()
            redis.rpush(self.ANIMATION_CTRL_QUEUE_NAME, 'STOP')
            self._init_animations()

    @action
    def animate(self, animation, duration=None,
                hue_range=None, sat_range=None,
                bri_range=None, lights=None, groups=None,
                hue_step=1000, sat_step=2, bri_step=1, transition_seconds=1.0):
        """
        Run a lights animation.

        :param animation: Animation name. Supported types: **color_transition** and **blink**
        :type animation: str

        :param duration: Animation duration in seconds (default: None, i.e. continue until stop)
        :type duration: float

        :param hue_range: If you selected a color color_transition.html, this will specify the hue range of your color color_transition.html.
            Default: [0, 65535]
        :type hue_range: list[int]

        :param sat_range: If you selected a color color_transition.html, this will specify the saturation range of your color
            color_transition.html. Default: [0, 255]
        :type sat_range: list[int]

        :param bri_range: If you selected a color color_transition.html, this will specify the brightness range of your color
            color_transition.html. Default: [254, 255] :type bri_range: list[int]

        :param lights: Lights to control (names, IDs or light objects). Default: plugin default lights
        :param groups: Groups to control (names, IDs or group objects). Default: plugin default groups

        :param hue_step: If you selected a color color_transition.html, this will specify by how much the color hue will change
            between iterations. Default: 1000 :type hue_step: int

        :param sat_step: If you selected a color color_transition.html, this will specify by how much the saturation will change
            between iterations. Default: 2 :type sat_step: int

        :param bri_step: If you selected a color color_transition.html, this will specify by how much the brightness will change
            between iterations. Default: 1 :type bri_step: int

        :param transition_seconds: Time between two transitions or blinks in seconds. Default: 1.0
        :type transition_seconds: float
        """

        if bri_range is None:
            bri_range = [self.MAX_BRI - 1, self.MAX_BRI]
        if sat_range is None:
            sat_range = [0, self.MAX_SAT]
        if hue_range is None:
            hue_range = [0, self.MAX_HUE]
        if groups:
            groups = [g for g in self.bridge.groups if g.name in groups or g.group_id in groups]
            lights = lights or []
            for g in groups:
                lights.extend([l.name for l in g.lights])
        elif lights:
            lights = [l.name for l in self.bridge.lights if l.name in lights or l.light_id in lights]
        else:
            lights = self.lights

        info = {
            'type': animation,
            'duration': duration,
            'hue_range': hue_range,
            'sat_range': sat_range,
            'bri_range': bri_range,
            'hue_step': hue_step,
            'sat_step': sat_step,
            'bri_step': bri_step,
            'transition_seconds': transition_seconds,
        }

        if groups:
            for g in groups:
                self.animations['groups'][g.group_id] = info

        for l in self.bridge.lights:
            if l.name in lights:
                self.animations['lights'][l.light_id] = info

        def _initialize_light_attrs(lights):
            if animation == self.Animation.COLOR_TRANSITION:
                return { l: {
                    'hue': random.randint(hue_range[0], hue_range[1]),
                    'sat': random.randint(sat_range[0], sat_range[1]),
                    'bri': random.randint(bri_range[0], bri_range[1]),
                } for l in lights }
            elif animation == self.Animation.BLINK:
                return { l: {
                    'on': True,
                    'bri': self.MAX_BRI,
                    'transitiontime': 0,
                } for l in lights }

        def _next_light_attrs(lights):
            if animation == self.Animation.COLOR_TRANSITION:
                for (light, attrs) in lights.items():
                    for (attr, value) in attrs.items():
                        attr_range = [0,0]
                        attr_step = 0

                        if attr == 'hue':
                            attr_range = hue_range
                            attr_step = hue_step
                        elif attr == 'bri':
                            attr_range = bri_range
                            attr_step = bri_step
                        elif attr == 'sat':
                            attr_range = sat_range
                            attr_step = sat_step

                        lights[light][attr] = ((value - attr_range[0] + attr_step) %
                                                (attr_range[1]-attr_range[0]+1)) + \
                                                attr_range[0]
            elif animation == self.Animation.BLINK:
                lights = { light: {
                    'on': False if attrs['on'] else True,
                    'bri': self.MAX_BRI,
                    'transitiontime': 0,
                } for (light, attrs) in lights.items() }

            return lights

        def _should_stop():
            try:
                redis = self._get_redis(transition_seconds)
                redis.blpop(self.ANIMATION_CTRL_QUEUE_NAME)
                return True
            except QueueTimeoutError:
                return False

        def _animate_thread(lights):
            set_thread_name('HueAnimate')
            self.logger.info('Starting {} animation'.format(
                animation, (lights or groups)))

            lights = _initialize_light_attrs(lights)
            animation_start_time = time.time()
            stop_animation = False

            while True:
                if stop_animation or \
                        (duration and time.time() - animation_start_time > duration):
                    break

                try:
                    if animation == self.Animation.COLOR_TRANSITION:
                        for (light, attrs) in lights.items():
                            self.logger.debug('Setting {} to {}'.format(light, attrs))
                            self.bridge.set_light(light, attrs)
                            stop_animation = _should_stop()
                            if stop_animation: break
                    elif animation == self.Animation.BLINK:
                        conf = lights[list(lights.keys())[0]]
                        self.logger.debug('Setting lights to {}'.format(conf))

                        if groups:
                            self.bridge.set_group([g.name for g in groups], conf)
                        else:
                            self.bridge.set_light(lights.keys(), conf)

                        stop_animation = _should_stop()
                        if stop_animation: break
                except Exception as e:
                    self.logger.warning(e)
                    time.sleep(2)

                lights = _next_light_attrs(lights)

            self.logger.info('Stopping animation')
            self.animation_thread = None
            self.redis = None

        self.stop_animation()
        self.animation_thread = Thread(target=_animate_thread,
                                       name='HueAnimate',
                                       args=(lights,))
        self.animation_thread.start()

    def _get_redis(self, socket_timeout=1.0):
        if not self.redis:
            redis_args = get_backend('redis').redis_args
            redis_args['socket_timeout'] = socket_timeout
            self.redis = Redis(**redis_args)
        return self.redis

    def status(self):
        # TODO
        pass
Beispiel #28
0
#!/usr/bin/python
# Minimal Motion Detection Logic written by Claude Pageau Dec-2014
# Updated by Richard Polzin Mai-2018

import time
import datetime
import picamera
import picamera.array
from fractions import Fraction
from phue import Bridge

b = Bridge('192.168.178.25')  
b.connect()
if b.get_light('Decke Esszimmer')['state']['on']:
    print("Lights are on - skipping checks")
    quit()  #don't deactive the screen while someone is in there :)
# Logging
verbose = True     # False= Non True=Display showMessage

# Motion Settings
threshold = 30     # How Much a pixel has to change
sensitivity = 300  # How Many pixels need to change for motion detection

# Camera Settings
testWidth = 128
testHeight = 80
nightShut = 5.5    # seconds Night shutter Exposure Time default = 5.5  Do not exceed 6 since camera may lock up
nightISO = 800
if nightShut > 6:
    nightShut = 5.9
SECONDS2MICRO = 1000000  # Constant for converting Shutter Speed in Seconds to Microseconds
    signal.signal(signal.SIGTERM, signal_handler)

    b = Bridge(get_environment_variable("bridge_ip"))
    b.connect()

    groups = get_groups()

    previous_room_brightnesses = {
        group_id: None
        for group_id
        in groups.keys()
    }

    while True:
        for group_id, light_ids in groups.items():
            group = b.get_group(group_id)
            group_brightness = group['action']['bri']

            if previous_room_brightnesses[group_id] != group_brightness:
                previous_room_brightnesses[group_id] = group_brightness

                time.sleep(.5)

                for light_id in light_ids:
                    light = b.get_light(light_id)

                    # if light['state']['bri'] != group_brightness:
                    b.set_light(light_id, "bri", group_brightness)

        time.sleep(.1)
Beispiel #30
0
def main():
    import random as random
    random.seed()
    from time import sleep
    from time import time
    import re
    import sys
    from phue import Bridge
#    b = Bridge()
    b = Bridge('192.168.1.110')
#    b.connect()

    # command-line argument parser
    import argparse
    parser = argparse.ArgumentParser(
            prog = 'ColorCycle',
            prefix_chars = '-/',
            description = """This program takes a series of color and brightness inputs and changes bulb charateristics accordingly.
                             It assumes that lights that are on will be used. Lights are tested for 'on' status every transition.""")
    timinggroup = parser.add_mutually_exclusive_group()
    timinggroup.add_argument('-t', '--timing', help='Set tempo in seconds, decimal values allowed; positive values produce gradual changes, ' + 
                                               'negative values produce flash transitions', type=float)
    timinggroup.add_argument('-r', '--bpm', '--rate', help='Set tempo as beats per minute, decimal values allowed; positive values produce gradual changes, ' + 
                                            'negative values produce flash transitions', type=float)
    parser.add_argument('-w', '--wait', help='Set wait time separately from transition time (bpm or seconds)', type=float, default=0.0)
    parser.add_argument('-c', '--hues', '--colors', help='A list of color values the lights will cycle through (0 - 65535)', type=int, nargs='+', default=[-1])
    parser.add_argument('-b', '--brightness', help='Set bulb brightness (0 - 254, can be a list)', type=int, nargs='+', default=[254])
    parser.add_argument('-s', '--saturation', help='Set bulb color saturation (0 - 254)', type=int, nargs='+', default=[254])
    parser.add_argument('-m', '--monochrome', help='Cycle through color list with all lights the same color', action="store_true", default=False)
    parser.add_argument('-o', '--ordered', help='Cycle through color list in order (do not randomize); apparent ' +
                                                'color "chase" order will be in reverse bulb order', action="store_true", default=False)
    selectiongroup = parser.add_mutually_exclusive_group()
    selectiongroup.add_argument('-n', '--names', help='A list of bulb names to cycle through; regex OK; bulbs will be turned on', nargs='+')
    selectiongroup.add_argument('-i', '--ids', help='A list of bulb id values to cycle through; bulbs will be turned on', type=int, nargs='+')
    selectiongroup.add_argument('-nx', '--excludednames', help='Cycle through all bulbs except these; regex OK; bulbs will be turned on', nargs='+')
    selectiongroup.add_argument('-ix', '--excludedids', help='Cycle through all bulbs except these id values; bulbs will be turned on', type=int, nargs='+')
    parser.add_argument('-d', '--duration', help='Duration for which the pattern should repeat (minutes)', type=float) #, default = 0.0)
    parser.add_argument('-v', '--verbose', help='Increase output verbosity', action="store_true")
    parser.add_argument('-x', '--exit', help='Exit by turning bulbs off', action="store_true")

    # TODO: add option to print list of bulb name/ID combos (with additional option to sort by ID# or name? -d, -di, -dn for 'directory, by id, by name'?)
    # TODO: add option to print list of 'legal' named colors (green, red, energize)
    # TODO: add option to specify colors as names
    # TODO: consider using the data from this page to write color names corresponding to hues: http://en.wikipedia.org/wiki/List_of_colors_(compact)
    # TODO: add option to specify bridge IP
    # TODO: design a GUI with checkboxes, etc. for options (Kivy?)
    # TODO: add option to specify colors (and more?) as ranges, e.g. hues = [0-1000, 5000-6800, 40000-41000] would assign three colors chosen from those ranges (-cr, -br, -sr, -wr, -tr)
    # TODO: add an option that increases hue/brightness/etc. by an increment of X for each time Y -- this is a maybe
    # TODO: set up a series of testing comand lines (e.g. 0, 1, 5 bulbs, 0, 1, 5 colors, bad parameter values)
    
    args = parser.parse_args()
    if args.verbose:
        print('Verbosity set to ON')
        if args.timing is not None:
            if args.timing >= 0:
                print('Transition timing is set to ' + str(abs(args.timing)) + ' seconds with a wait time of ' + str(abs(args.wait)) + ' seconds')
            if args.timing < 0 and args.wait > 0.0:
                print('Transition timing is set to 0.0 seconds with a wait time of ' + str(abs(args.wait) + abs(args.timing)) + ' seconds')
            if args.timing == 0:
                print('Lights will be set once and program will exit')
            if args.timing >= 0:
                print('Transitions will be gradual')
            else:
                print('Transitions will be instant')
        if args.bpm is not None:
            # For bpm time specification, assume that sum(bpm, wait) = intended total bpm.
            # So for bpm=10 and wait=20, transitions should begin at a rate of 30 bpm (every 2.0 seconds)
            netbpm = abs(args.bpm) + abs(args.wait)
            print('Timing is set to ' + str(netbpm) + ' bpm with a transition/wait split of ' + 
                  str(round(abs(args.bpm) / netbpm, 0)) + '/' + str(round(abs(args.wait) / netbpm, 0)) + '%')
            if args.bpm == 0:
                print('Lights will be set once and program will exit')
            if args.bpm >= 0:
                print('Transitions will be gradual')
            else:
                print('Transitions will be instant')

        print('Hues that will be cycled through: ' + str(args.hues))
        if args.ids is not None:
            print('Bulbs that will be cycled through: ' + str(args.ids))
        if args.ordered:
            print('Colors and lamps will be cycled in the specified order')
        else:
            print('Colors and lamps will be cycled in random order')
        print('Color saturation set to: ' + str(args.saturation))
        print('Brightness set to: ' + str(args.brightness))
        if args.duration is not None:
            print('Pattern will be repeated for ' + str(args.duration) + ' minute(s)')
    
    # Convert timing/frequency to integer tenths of seconds (transitiontime).
    # Wait times are handled by sleep(), so wait time is in actual seconds.
    if args.timing is not None:
        # Frequency is in seconds
        if args.timing >= 0: 
            transitiontime = int(round(args.timing * 10, 0))
            waittime = args.wait
        else: # use negative timing to specify flash transitions
            transitiontime = 0
            waittime = -args.timing + args.wait
            # This arrangement allows a benign but nonsensical combination 
            # (e.g. flash transition of -10 seconds with a wait of 5 seconds).
            # If a negative timing and a wait time are specified, 
            # the timing and wait times will be added together.
            # This way, flipping a negative sign does not change the 
            # observed rate of changes.
    if args.bpm is not None:
        # Frequency is in bpm; netbpm is the sum of transition and wait values
        if args.bpm >= 0:
            transitiontime = int(round(60 / (args.bpm / netbpm) * 10, 0))
            waittime = 60 / (args.wait / netbpm)
        else: # use negative bpm to specify flash transitions
            transitiontime = 0
            waittime = 60 / netbpm
    if args.timing is None and args.bpm is None:
        transitiontime = 0
        waittime = 0

    # Get light names and ID numbers, and choose which lights will be active
    # Note: Bulb changes are transmitted using ID number.
    lights_in_play = b.get_light_objects('name')
    light_ids_in_play = []
    for name in lights_in_play:
        light_ids_in_play.append(int(b.get_light_id_by_name(name)))
    # Use a selection method: ID #s, names, exclude by #, exclude by name, default = all bulbs
    if args.ids is not None: # Set bulbs using ID numbers
        # Filter lights in use so that only specified bulbs are used.
        # Turn specified bulbs on.
        light_ids_in_play = [id_ for id_ in light_ids_in_play if id_ in args.ids]
        b.set_light(light_ids_in_play, 'on', True)
        lights_in_play = []
        for id_ in light_ids_in_play:
            lights_in_play.append(b.get_light(id_, 'name'))
    elif args.excludedids is not None: # Exclude bulbs using ID numbers
        # Filter lights in use so that only specified bulbs are used.
        # Turn specified bulbs on.
        light_ids_in_play = [id_ for id_ in light_ids_in_play if id_ not in args.excludedids]
        b.set_light(light_ids_in_play, 'on', True)
        lights_in_play = []
        for id_ in light_ids_in_play:
            lights_in_play.append(b.get_light(id_, 'name'))
    elif args.names is not None: # Set bulbs using names
        # Filter lights in use so that only specified bulbs are used.
        # Turn specified bulbs on.
        regex = re.compile('|'.join(args.names), re.IGNORECASE) # names joined with OR '|' connector
        # Usage note: '.*' is equivalent to DOS '*', '.' is equivalent to DOS '?'
        lights_in_play = [a for a in lights_in_play if re.search(regex, a)]
        light_ids_in_play = []
        for name in lights_in_play:
            light_ids_in_play.append(int(b.get_light_id_by_name(name)))
        b.set_light(light_ids_in_play, 'on', True)
    elif args.excludednames is not None: # Exclude bulbs using names
        # Filter lights in use so that only specified bulbs are used.
        # Turn specified bulbs on.
        regex = re.compile('|'.join(args.excludednames), re.IGNORECASE) # names joined with OR '|' connector
        # Usage note: '.*' is equivalent to DOS '*', '.' is equivalent to DOS '?'
        lights_in_play = [a for a in lights_in_play if not re.search(regex, a)]
        light_ids_in_play = []
        for name in lights_in_play:
            light_ids_in_play.append(int(b.get_light_id_by_name(name)))
        b.set_light(light_ids_in_play, 'on', True)
    else:
        pass # All lights will be adjusted as specified, but will not be switched on

    # randomly assign colors to lights and issue the commands via the hub
    try:
        if args.monochrome:
            # Set all bulbs to the same color; cycle through colors
            light_ids_on = []
            huenum = -1
            brinum = -1
            satnum = -1
            start = time()
            while True:
                loopstart = time()
                if args.duration is not None:
                    if args.duration < (time() - start) / 60:
                            break
                if args.ordered:
                    # This results in each bulb moving through the parameter list in order.
                    huenum = (huenum + 1) % len(args.hues)
                    brinum = (brinum + 1) % len(args.brightness)
                    satnum = (satnum + 1) % len(args.saturation)
                    hue = args.hues[huenum]
                    bri = args.brightness[brinum]
                    sat = args.saturation[satnum]
                else:
                    hue = random.choice(args.hues)
                    bri = random.choice(args.brightness)
                    sat = random.choice(args.saturation)
    
                hue_verbose = hue # used only for verbose printing
                if hue == -1: # flag for white
                    sat = 0 # 0 to 254
                    hue = random.choice([i for i in args.hues if i >= 0]) # choose from non-white values
    
                if hue == -2: # flag for black (off)
                    # get light 'on' status and build a list of lights that are on; build fresh every time
                    for id_ in light_ids_in_play:
                        if b.get_light(id_, 'on'):
                            light_ids_on.append(id_)
                    command =  {'transitiontime' : transitiontime, 'on' : False}
                    result = b.set_light(light_ids_in_play, command)
                else:
                    # Set bulbs
                    if len(light_ids_on) > 0:
                        # If any bulbs are in the list, turn them on
                        command =  {'on' : True, 'transitiontime' : transitiontime, 'hue' : hue, 'sat' : sat, 'bri' : bri}
                        result = b.set_light(light_ids_on, command)
                    else: # empty list
                        command =  {'transitiontime' : transitiontime, 'hue' : hue, 'sat' : sat, 'bri' : bri}
                        result = b.set_light(light_ids_in_play, command)
    
                if args.verbose:
                    if len(light_ids_in_play) > 0:
    #                    print('Hue Bulb(s) ' + str(light_ids_in_play) + ' set to hue = ' + str(hue) + ', sat = ' + str(sat) + ', bri = ' + str(bri))
                        print('Bulb(s) {light_id} set to hue = {hue:>5}, sat = {sat:>3}, bri = {bri:>3}'.format(light_id=light_ids_in_play, hue=hue_verbose, sat=sat, bri=bri))
                    print('-- pass complete, waiting ' + str(transitiontime / 10 + waittime) + ' seconds --')
                    if args.duration is not None:
                        elapsed = time() - start
                        print('-- ' + str(int(args.duration - elapsed/60)) + ' minutes ' + str(round(max((args.duration*60 - elapsed), 0) % 60, 1)) + ' seconds remaining --')
                if transitiontime + waittime == 0.0:
                    if args.verbose:
                        print('-- lights set, bpm = 0.0, exiting program --')
                    break # end program
                else:
                    loopelapsed = time() - loopstart
                    sleep(max(transitiontime / 10 + waittime - loopelapsed, 0))
    
                if len(args.hues) == 1 and len(args.brightness) == 1 and len(args.saturation) == 1:
                    if args.verbose:
                        print('-- only one color to cycle, exiting program --')
                    # only one color, no reason to keep changing it
                    break
        else:
            # Set bulbs to random colors; wait; repeat
            light_ids_on = []
            huenum = -1
            brinum = -1
            satnum = -1
            start = time()
            while True:
                loopstart = time()
                if args.duration is not None:
                    if args.duration < (time() - start) / 60:
                            break
    #            sat = args.saturation # 0 to 254
                if args.ordered:
                    huenum = (huenum + 1) % len(args.hues)
                    brinum = (brinum + 1) % len(args.brightness)
                    satnum = (satnum + 1) % len(args.saturation)
                else:
                    random.shuffle(light_ids_in_play)
                for light_index, light_id in enumerate(light_ids_in_play):
                    if args.ordered:
                        # Each bulb is assigned hues in the user-specified order.
                        # The intial hue is set by cycling through the color list in order.
                        # Visual note: the apparent "chase" direction of colors is the reverse 
                        # of the order of lights. 
                        hue = args.hues[(light_index + huenum) % len(args.hues)]
                        bri = args.brightness[(light_index + brinum) % len(args.brightness)]
                        sat = args.saturation[(light_index + satnum) % len(args.saturation)]
                    else:
                        hue = random.choice(args.hues)
                        bri = random.choice(args.brightness)
                        sat = random.choice(args.saturation)
                    hue_verbose = hue # used only for verbose printing
                    if hue == -1: # flag for white
                        sat = 0 # 0 to 254
                        if len([i for i in args.hues if i >= 0]) > 0:
                            hue = random.choice([i for i in args.hues if i >= 0]) # choose from non-white/black values
                        else:
                            hue = 0 # no colors available to choose, assume red
                    elif hue == -2: # flag for black
                        light_ids_on.append(light_id)
                        hue = random.choice([i for i in args.hues if i >= 0]) # choose from non-white/black values
                        command =  {'on' : False, 'transitiontime' : transitiontime}
    
                    if hue_verbose != -2: # if not black
                        # Set bulbs
                        if light_id in light_ids_on:
                            command =  {'on' : True, 'transitiontime' : transitiontime, 'hue' : hue, 'sat' : sat, 'bri' : bri}
                            light_ids_on.remove(light_id)
                        else:
                            command =  {'transitiontime' : transitiontime, 'hue' : hue, 'sat' : sat, 'bri' : bri}
                    result = b.set_light(light_id, command)
    
                    if args.verbose:
                        if light_id in light_ids_in_play:
                            print('Bulb {light_id:>2} set to hue = {hue:>5}, sat = {sat:>3}, bri = {bri:>3}'.format(light_id=light_id, hue=hue_verbose, sat=sat, bri=bri))
    
                    sat = args.saturation # 0 to 254
    
                if args.verbose:
                    print('-- pass complete, waiting ' + str(transitiontime / 10 + waittime) + ' seconds --')
                    if args.duration is not None:
                        elapsed = time() - start
                        # the following command could use some analysis for the max portion.
                        # the following command, with max removed, will result in an incorrect "59.9 seconds remaining" message at the end
                        # c:\python32\python ColorCycle.py -v -t 3.0 -b 1 -c 0 500 1000 1500 2000 63000 63500 64000 64500 65000 65535 -i10 12 15 19 -d 0.2 -s 254 250 245 240 -x
    #                    print('-- ' + str(int(args.duration - elapsed/60)) + ' minutes ' + str(round(max((args.duration*60 - elapsed), 0) % 60, 1)) + ' seconds remaining --')
                if transitiontime + waittime == 0.0:
                    if args.verbose:
                        print('-- lights set, bpm = 0.0, exiting program --')
                    break # end program
                else:
                    loopelapsed = time() - loopstart
                    len_text = 0
                    while (transitiontime / 10 + waittime - loopelapsed) > 0:
                        loopelapsed = time() - loopstart
                        elapsed = time() - start
                        len_text = underwrite('-- ' + str(int(args.duration - elapsed/60)) + ' minutes ' + str(round(max((args.duration*60 - elapsed), 0) % 60, 1)) + ' seconds remaining --', len_text)
                        sleep(min(1, max(0, transitiontime / 10 + waittime - loopelapsed)))
            if args.exit:
                command =  {'transitiontime' : transitiontime, 'on' : False}
                result = b.set_light(light_ids_in_play, command)
                print('-- lights off, exiting program --')
    except KeyboardInterrupt:
        # Quit if we get a CTRL-C from the user
        if args.verbose:
            print('-- CTRL-C received, exiting program --')
        sys.exit()
Beispiel #31
0
class Hue(object):
    """
    Plugin to interact with Philips Hue devices
    @author: Fabio "BlackLight" Manganiello <*****@*****.**>
    @depend: Philips Hue phue Python bridge [pip install phue]
    """

    __hue = None
    __hue_lock = threading.RLock()

    def __init__(self, lightbulbs=None):
        """
        bridge -- Name or IP address of the Philips Hue bridge host
        lightbulbs -- Lightbulbs to act on - single lightbulb name or comma separated list.
            In case nothing is passed, the plugin will act on all the lightbulbs connected to the bridge
        """
        self.__config = Config.get_config()
        self.__logger = Logger.get_logger(__name__)

        self.bridge_address = self.__config.get('hue.bridge')
        self.lightbulbs = self.__config.get('hue.lightbulbs')
        self.connected = False

        if self.lightbulbs:
            m = re.split('\s*,\s*', self.lightbulbs)
            self.lightbulbs = m or [self.lightbulbs]

        self.__logger.info({
            'msg_type': 'Hue bridge started',
            'bridge': self.bridge_address,
            'lightbulbs': self.lightbulbs or None,
        })

    @classmethod
    def get_hue(cls):
        """
        Static helper used for rules.xml <action> tags of type Python, which are run through eval().
        Thread-safe singleton to access or initialize the static default hue object
        """
        cls.__hue_lock.acquire()
        try:
            if cls.__hue is None:
                cls.__hue = Hue()
        finally:
            cls.__hue_lock.release()
        return cls.__hue

    def connect(self):
        " Connect to the Philips Hue bridge "

        if self.connected:
            return

        self.__logger.info({
            'msg_type': 'Connecting to the Hue bridge',
        })

        self.bridge = Bridge(self.bridge_address)
        self.bridge.connect()
        self.bridge.get_api()

        if not self.lightbulbs:
            self.lightbulbs = []
            for light in self.bridge.lights:
                self.lightbulbs.append(light.name)

        self.__logger.info({
            'msg_type': 'Connected to the Hue bridge',
            'lightbulbs': self.lightbulbs,
        })

        self.connected = True
        return self

    def is_connected(self):
        " Return true if we are connected to the bridge "
        return self.connected

    def set_on(self, on):
        """
        Set the lightbulbs on status
        on -- If False, turn the lights off, otherwise turn them on
        """

        self.__logger.info({
            'msg_type': 'Set lightbulbs on',
            'on': on,
        })

        for light in self.lightbulbs:
            self.bridge.set_light(light, 'on', on)
            if on:
                self.bridge.set_light(light, 'bri', 255)
        return self

    def set_bri(self, bri):
        """
        Set the lightbulbs brightness
        bri -- Brightness value, in range [0-255]
        """

        self.__logger.info({
            'msg_type': 'Set lightbulbs brightness',
            'brightness': bri,
        })

        if bri == 0:
            for light in self.lightbulbs:
                self.bridge.set_light(light, 'on', False)
        else:
            for light in self.lightbulbs:
                if not self.bridge.get_light(light, 'on'):
                    self.bridge.set_light(light, 'on', True)

        self.bridge.set_light(self.lightbulbs, 'bri', bri)
        return self

    def set_sat(self, sat):
        """
        Set the lightbulbs saturation
        sat -- Saturation value, in range [0-500]
        """

        self.__logger.info({
            'msg_type': 'Set lightbulbs saturation',
            'saturation': sat,
        })

        self.bridge.set_light(self.lightbulbs, 'sat', sat)
        return self

    def set_hue(self, hue):
        """
        Set the lightbulbs hue
        hue -- Hue/tint value, in range [0-65535]
        """

        self.__logger.info({
            'msg_type': 'Set lightbulbs hue',
            'saturation': hue,
        })

        self.bridge.set_light(self.lightbulbs, 'hue', hue)
        return self
Beispiel #32
0
#b.connect()

root = Tk()

horizontal_frame = Frame(root)
horizontal_frame.pack()

lights = b.get_light_objects('id')

for light_id in lights:
    channel_frame = Frame(horizontal_frame)
    channel_frame.pack(side = LEFT)

    scale_command = lambda x, light_id=light_id: b.set_light(light_id,{'bri': int(x), 'transitiontime': 1})
    scale = Scale(channel_frame, from_ = 254, to = 0, command = scale_command, length = 200, showvalue = 0)
    scale.set(b.get_light(light_id,'bri'))
    scale.pack()

    button_var = BooleanVar()
    button_var.set(b.get_light(light_id, 'on'))
    button_command = lambda button_var=button_var, light_id=light_id: b.set_light(light_id, 'on', button_var.get())
    button = Checkbutton(channel_frame, variable = button_var, command = button_command)
    button.pack()

    label = Label(channel_frame)
    label.config(text = b.get_light(light_id,'name'))
    label.pack()

root.mainloop()
########NEW FILE########
__FILENAME__ = tk_gui_hsb
Beispiel #33
0
#!/usr/bin/python

from phue import Bridge

b = Bridge('10.0.0.137')

# 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
Beispiel #34
0
    conn = sqlite3.connect(dbname)
    curs = conn.cursor()

    curs.execute(
        "SELECT * FROM temps WHERE timestamp>datetime('now','-%s hours')" %
        500)

    rows = curs.fetchall()

    conn.close()

    return rows


# get data from the database
records = get_data()
records = str(get_data())
records = records[-10:]
number = int(records[records.find(',') + 2:records.find(')')])
print(number)

bLight = b.get_light(3, 'on')

if number < 620:
    if bLight:
        lights[2].xy = [0.96, 0.96]

savefile(number)
dropbox_upload()
log_temperature(number)
Beispiel #35
0
# 12 Couch

##Groups
# 1 Bedroom Dome
# 2 Bathroom Mirror
# 3 Closet

#Set Target Bulbs and Groups
b1 = 2
b2 = 10
b3 = 12
g1 = 2
g2 = 3

#Get Current Status of Bulbs and Groups
h1 = b.get_light(b1,'hue')
h2 = b.get_light(b2,'hue')
h3 = b.get_light(b3,'hue')

br1 = b.get_light(b1,'bri')
br2 = b.get_light(b2,'bri')
br3 = b.get_light(b3,'bri')
brg1 = b.get_group(g1,'bri')
brg2 = b.get_group(g2,'bri')

p1 = b.get_light(b1,'on')
p2 = b.get_light(b2,'on')
p3 = b.get_light(b3,'on')
pg1 = b.get_group(g1,'on') 
pg2 = b.get_group(g2,'on')
print("Philups hue connecting...")
print(
    "Get ready to enter the ip address of your hue, before you press enter press the connect button on your hue device"
)
ip = input("Please enter the IP ADDRESS of your hue: ")
light = input("Enter the NAME of the light, caps sensitive: ")

bridge = Bridge(ip)

bridge.connect()

bridge.get_api()
print("Connected to " + ip + "'s api")

light_real = bridge.get_light(light)

light_obj = bridge.get_light_objects(light_real["name"])

print(light_obj)
SCREEN_SIZE = (600, 400)

fourcc = cv2.VideoWriter_fourcc(*"XVID")
print("Starting")

converter = rgbxy.Converter(rgbxy.GamutB)

while True:
    img = pyautogui.screenshot()
    frame = np.array(img)
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
Beispiel #37
0
from phue import Bridge

# https://github.com/studioimaginaire/phue
# in and for meaning: https://www.quora.com/In-Python-what-does-for-return-and-in-mean
# https://stackoverflow.com/questions/19845924/python-how-to-generate-list-of-variables-with-new-number-at-end
# the hub 192.168.1.107

b = Bridge('192.168.1.107')

b.connect()
b.get_api()

b.get_light(1, 'on')
b.get_light(1, 'name')

lights = b.lights

print(
    "NOTICE: Only 1 light is supported in this script more will be allowed in the future."
)
print(
    "This script is highly work in progress, contact Yusef (YUZi22) on Github if any errors occur"
)
print()
print(
    "Please make sure to input the local ip address of your hue hub, and press the button on it before you run this script"
)
print()

# Print names of all lights connected to hue hub.
for l in lights:
Beispiel #38
0
from phue import Bridge
import time

b = Bridge('192.168.1.80')

light = 'Bedroom'

# 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
print b.get_light(1, 'on')
print b.get_light(2, 'on')
print b.get_light(3, 'on')

b.set_light('Bedroom', 'on', True)
b.set_light('Bedroom', 'bri', 254)
for i in range(0,10):
	for j in xrange(20,4000,300):
		b.set_light('Bedroom', 'hue', j)
		time.sleep(2)
		print j
	for j in xrange(4000,20,-300):
		b.set_light('Bedroom', 'hue', j)
		time.sleep(2)
		print j
Beispiel #39
0
#!/usr/bin/python

from phue import Bridge
import os
import sys
import requests

b = Bridge('192.168.1.217')
r = (requests.get("http://192.168.1.217/api//sensors/"))
lightlevel = r.json()['18']['state']['lightlevel']

if (sys.argv[1] == "Plex for LG (webOS 04.30.06)"
        or sys.argv[1] == 'LG 43UH6500-UB') and sys.argv[2] == 'agsl':
    if not os.path.isfile('room_s'):
        f = open("room_s", "w")
        print(b.get_light(2), file=f)
        f.close()
    if lightlevel < 10500:
        b.set_light(1, {
            'bri': 80,
            'xy': [0.1538, 0.0722],
            'transitiontime': 20
        })
        b.set_light([2, 3], {'on': False, 'transitiontime': 20})
Beispiel #40
0
    signal.signal(signal.SIGINT, self.exit_gracefully)
    signal.signal(signal.SIGTERM, self.exit_gracefully)

  def exit_gracefully(self,signum, frame):
    logger.info(time.strftime('%x %X %Z')+': Going down for a nap...')
    b.set_light(5, 'on', False)
    self.kill_now = True

if __name__ == '__main__':
  logger.info(time.strftime('%x %X %Z')+': Starting light sequence')
  killer = GracefulKiller()
  while True:
    # Go white
    change_white()
    time.sleep(8)
    if b.get_light(5, 'on') == False:
      break
    elif killer.kill_now:
      break

    # Go red
    change_red()
    time.sleep(8)
    if b.get_light(5, 'on') == False:
      break
    elif killer.kill_now:
      break

    # Go blue
    change_blue()
    time.sleep(8)
Beispiel #41
0
class LightCommands:
    """
    Object for executing command-line commands associated with Hue Lights.
    """
    #
    # only numeric for now
    #
    attributes = {
        "transitiontime",
        "brightness",
        "colortemp",
        "colortemp_k",
        "hue",
        "saturation"
    }

    def __init__(self, parent):
        self.parent = parent
        self.bridge = None

    def _ensure_bridge(self):
        if not self.bridge:
            self.bridge = Bridge()

    # pylint: disable=invalid-name
    async def do(self, parameters: List[str]):
        """
        Implement light control commands such as the following::

           light 4 on
           light group 3 hue 7712

        in which case this function receive the parameters::

           ["4","on"]
           ["group","3","hue","7712"]

        :param parameters:
        :return:
        """
        self._ensure_bridge()

        idx = 0
        first = parameters[idx]
        idx += 1
        pattern = re.compile("[0-9]+")
        if pattern.match(first):
            light_id = int(first)
            light = self.bridge.lights[light_id - 1]
        elif first == "group":
            second = parameters[idx]
            idx += 1
            group_id = int(second)
            light = self.bridge.groups[group_id - 1]
        else:
            raise ValueError("the light command must be followed by "
                             "a number or by 'group' and then a number")

        while idx < len(parameters):
            cmd = parameters[idx]
            idx += 1
            if cmd == "on":
                light.on = True
            elif cmd == "off":
                light.on = False
            elif cmd in LightCommands.attributes:
                amount = int(parameters[idx])
                idx += 1
                setattr(light, cmd, amount)
            else:
                raise ValueError(f"Command {cmd} is not available for lights")

    async def get_unreachable_lights(self, lights, wait_time=10, tries=3):
        """
        Detect unavailable lights.  Every so often a ping fails (for instance when there
        is a lot of Wi-Fi activity) so we will wait and retry to make sure.  Default
        settings are based on a small amount of experience with how rapidly the Hue
        system seems to respond to lights having the AC power turned on and off

        :param lights: list or set of integer light ids
        :param wait_time: how many seconds to wait to try pinging lights a second time
        :param tries: how many tries to try the ping before giving up
        :return: set of unavailable lights
        """

        self._ensure_bridge()
        available = set()
        lights = set(map(int, lights))
        for attempt in range(tries):
            unavailable = lights - available
            if not unavailable:
                return set()

            if attempt:
                await sleep(wait_time)

            for light in lights - available:
                if self.bridge.get_light(light)['state']['reachable']:
                    available.add(light)

        return lights - available
Beispiel #42
0
#!/usr/bin/python
from time import sleep
from phue import Bridge

b = Bridge('192.168.1.26')

hue = b.get_light(2,'hue')
bri = b.get_light(2,'bri')
pwr = b.get_light(2,'on')

# b.set_light(2,'on',True)
if pwr == 'False':
	b.set_light(2,'on',True)

for x in range(0, 2):
	b.set_light(2,'hue',0)
	sleep(0.4)
	b.set_light(2,'hue',hue)
	sleep(0.4)

b.set_light(2,'on',pwr)

#b.set_light(2,'bri',bri)
#b.set_light(2,'hue',hue)
Beispiel #43
0
class BridgeContainer():
    def __init__(self,
                 transitiontime=50,
                 individual=None,
                 ip=None,
                 dummy=False):
        if dummy:
            self.mybridge = DummyBridge()
            self.individual = 1
            self.transitiontime = 50
            return

        self.mybridge = None
        while not self.mybridge:
            try:
                if not ip:
                    # try to find a bridge with meethue api
                    logging.debug("will try finding the hue bridge")
                    print "1111"
                    localbridge = json.loads(urlopen(' /nupnp').read())
                    ip = localbridge[0]["internalipaddress"]
                    logging.info('connecting to localbridge at ' + str(ip))
                    print "????"
                self.mybridge = Bridge(ip)
                self.mybridge.connect()
                self.mybridge.get_api()
            except Exception as e:
                logging.warn(
                    'failed to connect to HUE server did you push the button?')
                self.mybridge = None

            sleep(10)

        self.transitiontime = transitiontime
        self.individual = None
        if individual:
            self.individual = int(individual)
        self.alert()

    def setTransitionTime(self, value):
        # this should be the transistion time in seconds
        self.transitiontime = int(10 * float(value))

    def sendAll(self, **options):
        lamp = self.individual or 0
        for k, v in options.iteritems():
            if v is None:
                del (options[k])
        if self.transitiontime >= 0:
            options['transitiontime'] = self.transitiontime
        if self.individual:
            self.mybridge.set_light(self.individual, options)
        else:
            self.mybridge.set_group(0, options)

    def getAll(self):
        # returns dictionary with all values
        # {"state": {"on":true,"bri":254,"hue":45000,"sat":253,"xy":[0.1914,0.0879],"ct":500,"alert":"select","effect":"none","colormode":"hs","reachable":true},
        # "type": "Extended color light", "name": "Hue Lamp", "modelid": "LCT001", "swversion": "66009663", "pointsymbol": { "1":"none", "2":"none", "3":"none", "4":"none", "5":"none", "6":"none", "7":"none", "8":"none" }}
        return self.mybridge.get_light(self.individual)['state']

    def setEffect(self, value):
        self.sendAll(effect=effect)

    def setHue(self, value):
        self.sendAll(hue=value)

    def setBri(self, value):
        self.sendAll(bri=value)

    def setSat(self, value):
        self.sendAll(sat=value)

    def get_state(self):
        if self.individual:
            logging.debug(str(self.mybridge.get_light(self.individual)))
            return self.mybridge.get_light(self.individual)['state']

    def toggle(self, dummy=None):
        if self.individual:
            if self.mybridge.get_light(self.individual)['state']['on']:
                self.mybridge.set_light(self.individual, {'on': False})
            else:
                self.mybridge.set_light(self.individual, {'on': True})
        else:
            if self.mybridge.get_group(0)['action']['on']:
                self.mybridge.set_group(0, {'on': False})
            else:
                self.mybridge.set_group(0, {'on': True})

    def setOn(self, value):
        if self.individual:
            if value:
                self.mybridge.set_light(self.individual, {'on': True})
            else:
                self.mybridge.set_light(self.individual, {'on': False})

    def alert(self, dummy=None):
        if self.individual:
            self.mybridge.set_light(self.individual, {'alert': 'select'})
        else:
            self.mybridge.set_group(0, {'alert': 'select'})
Beispiel #44
0
# IMPORTANT: If running for the first time:
#    Uncomment the b.connect() line
#    Ppress button on bridge
#    Run the code
# This will save your connection details in /home/pi/.python_hue
# Delete that file if you change bridges
# b.connect() # <<<<<<<<<<

# An array of the light name and the light type.
# Expand if you have something different - please let me know if you do!
lighttype = []
lighttypecolour = 'Extended color light'
lighttypedimmable = 'Dimmable light'
# Get the type of lights that are connected
for light in lights:
    lighttype.append([light, b.get_light(light, 'type')])

# Hue 'xy' colours - expand at will
redxy = (0.675, 0.322)
greenxy = (0.4091, 0.518)
bluexy = (0.167, 0.04)
yellowxy = (0.4325035269415173, 0.5007488105282536)
bluevioletxy = (0.2451169740627056, 0.09787810393609737)
orangexy = (0.6007303214398861, 0.3767456073628519)
whitexy = (0.32272672086556803, 0.3290229095590793)

# Alert Patterns
# Used to change the status of lights
# First two numbers are the number of repeat cycles, and the delay between changes
# Followed by dictionaries of the change of light status.
# Use any valid HUE setting - e.g. on, bri, xy, ct, sat, hue, transformationtime
Beispiel #45
0
#!/usr/bin/python
from Tkinter import *
from phue import Bridge
'''
This example creates a slider that controls the
brightness of the first 3 lights.
'''
b = Bridge() # Enter bridge IP here.
#If running for the first time, press button on bridge and run with b.connect() uncommented
#b.connect()
b.set_light([1,2,3], 'on', True)
def sel(data):
	b.set_light([1,2,3],{'bri':int(data), 'transitiontime': 1})
root = Tk()
scale = Scale( root, from_ = 254, to = 0, command= sel, length = 200 )
scale.set(b.get_light(1,'bri'))
scale.pack(anchor=CENTER)
root.mainloop()
# If running for the first time, press button on bridge and run with b.connect() uncommented
# b.connect()

root = Tk()

horizontal_frame = Frame(root)
horizontal_frame.pack()

lights = b.get_light_objects("id")

for light_id in lights:
    channel_frame = Frame(horizontal_frame)
    channel_frame.pack(side=LEFT)

    scale_command = lambda x, light_id=light_id: b.set_light(light_id, {"bri": int(x), "transitiontime": 1})
    scale = Scale(channel_frame, from_=254, to=0, command=scale_command, length=200, showvalue=0)
    scale.set(b.get_light(light_id, "bri"))
    scale.pack()

    button_var = BooleanVar()
    button_var.set(b.get_light(light_id, "on"))
    button_command = lambda button_var=button_var, light_id=light_id: b.set_light(light_id, "on", button_var.get())
    button = Checkbutton(channel_frame, variable=button_var, command=button_command)
    button.pack()

    label = Label(channel_frame)
    label.config(text=b.get_light(light_id, "name"))
    label.pack()

root.mainloop()
Beispiel #47
0
#!/usr/bin/python

from phue import Bridge
# https://github.com/studioimaginaire/phue

b = Bridge('bridgeipaddress')

# 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', 0)

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

Beispiel #48
0
#!/usr/bin/python
from time import sleep
from phue import Bridge

b = Bridge('192.168.1.26')

hue = b.get_light(2, 'hue')
bri = b.get_light(2, 'bri')
pwr = b.get_light(2, 'on')

# b.set_light(2,'on',True)
if pwr == 'False':
    b.set_light(2, 'on', True)

for x in range(0, 2):
    b.set_light(2, 'hue', 0)
    sleep(0.4)
    b.set_light(2, 'hue', hue)
    sleep(0.4)

b.set_light(2, 'on', pwr)

#b.set_light(2,'bri',bri)
#b.set_light(2,'hue',hue)
Beispiel #49
0
        })
    scale = Scale(frame,
                  from_=254,
                  to=0,
                  activebackground='gray',
                  fg='white',
                  highlightbackground='gray',
                  command=scale_command,
                  length=200,
                  borderwidth=.001,
                  showvalue=0,
                  troughcolor='lightgray',
                  orient='horizontal',
                  bg='gray',
                  label="Brightness")
    scale.set(b.get_light(light_id, 'bri'))
    scale.grid(row=rowNum, column=2)

    button_var = BooleanVar()
    button_var.set(b.get_light(light_id, 'on'))
    button_command = lambda button_var=button_var, light_id=light_id: b.set_light(
        light_id, 'on', button_var.get())

    button = Checkbutton(frame, variable=button_var, command=button_command)
    button.grid(row=rowNum, column=0)

    label = Label(frame)
    label.config(text=b.get_light(light_id, 'name'))
    label.grid(row=rowNum, column=1)
    rowNum = rowNum + 1
Beispiel #50
0
#!/usr/bin/python

# AutoAuroDX
# hueTesting.py (some simple bits to test API behavior)
# Adam J. Bauman
#
# Real-time Philips Hue light programming based off hue and intensity averages of PC monitor display.

import datetime, time
import os
from phue import Bridge

myBridge = Bridge('192.168.1.25')

myBridge.connect()

myBridge.get_api()
myBridge.set_light(1, 'on', True)
myBridge.set_light(1, 'bri', 127, transitiontime=0)
myBridge.set_light(1, 'effect', 'colorloop', transitiontime=0)

raw_input('Press any key to continue... ')

myBridge.set_light(1, 'effect', 'none')

print(myBridge.get_light(1, 'hue'))

Beispiel #51
0
Brightness = 50 # Helligkeit in %

DimTimeOn = DimTimeON*10 # in 1/10 sek
DimTimeOff = DimTimeOFF*10 # in 1/10 sek
bri = Brightness*1000/100*254/1000
commandOn =  {'transitiontime' : DimTimeOn, 'on' : True, 'bri' : bri}
commandOff = {'transitiontime' : DimTimeOff, 'on' : False}
b = Bridge(IP)                                         
GPIO.setmode(GPIO.BCM)
GPIO.setup(InPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

while True:
    now = datetime.datetime.now()
    input_state = GPIO.input(InPin)
    if input_state == False:
        if b.get_light(2,'on') == True:
         StatusL = "An"
        else:
         StatusL = "Aus"
        print "------------------------"
        print
        print now.strftime("%d.%m.%Y %H:%M:%S")
        print "Linker Taster gedrueckt"
        print "Status : %s" % StatusL 
        print "Aktuelle Helligkeit: %d Prozent, %d Lumen" % ((b.get_light(2,'bri'))*1000/254*100/1000,  (b.get_light(2,'bri'))*1000/254*806/1000)
        if b.get_light(2,'on') == True:
            b.set_light(2, commandOff)
            print
            print "linkes Licht aus in %d Sekunden" % DimTimeOFF

        elif b.get_light(2,'on') == False or b.get_light(2,'bri') < 1:                               
Beispiel #52
0
label_name.pack()

hue_slider = Scale(slider_frame, from_ = 65535, to = 0, command = hue_command)
sat_slider = Scale(slider_frame, from_ = 254, to = 0, command = sat_command)
bri_slider = Scale(slider_frame, from_ = 254, to = 0, command = bri_command)
hue_slider.pack(side=LEFT)
sat_slider.pack(side=LEFT)
bri_slider.pack(side=LEFT)


for light_id in lights:
    channel_frame = Frame(channels_frame)
    channel_frame.pack(side = LEFT, padx = 10)
    
    button_var = BooleanVar()
    button_var.set(b.get_light(light_id, 'on'))
    button_command = lambda button_var=button_var, light_id=light_id: b.set_light(light_id, 'on', button_var.get())
    button = Checkbutton(channel_frame, variable = button_var, command = button_command)
    button.pack()

    select_button_var = BooleanVar()
    #select_button_var.set(b.get_light(light_id, 'on'))
    select_button_callback = curry(select_button_command, light_id, select_button_var)
    select_button = Checkbutton(channel_frame, variable = select_button_var, command = select_button_callback)
    select_button.pack()

    label = Label(channel_frame)
    label.config(text = b.get_light(light_id,'name'))
    label.pack()

root.mainloop()
Beispiel #53
-1
class HueCommand:
    def __init__(self, duration, states):
        self.b = Bridge('********')
        self.duration = duration
        self.states = states

    def get_states(self, ids):
        lights =[]
        for light_id in ids:
            is_on = self.b.get_light(light_id, 'on')
            bri = self.b.get_light(light_id, 'bri')
            hue = self.b.get_light(light_id, 'hue')
            lights.append({'id': light_id, 'on': is_on, 'hue': hue, 'bri': bri})
        return lights

    def execute(self):
        # set hue bulbs
        self.b.connect()
        # Get a dictionary with the light ids as the key
        # lights = self.b.get_light_objects('id')

        for state in self.states:
            try:
                self.b.set_light(state.id, state.cmd)
            except Exception as e:
                print e.message
                continue

        time.sleep(self.duration)