def discover_and_connect_bridge():
    ssdp_responses = ssdp.discover("device")
    registered = False
    help_printed = False

    for response in ssdp_responses:

        hub_ip = verify_hue_upnp(response.location)

        if hub_ip:
            print("Found hub at: %s" % hub_ip)
    
    discover_start = time.time()
    
    while not(registered and (time.time() - discover_start > 90)):  # Time out in 90 seconds
        try:
            bridge = phue.Bridge(hub_ip)
            registered = True
            print("Conected to hub at: %s" % hub_ip)
            return bridge
        except phue.PhueRegistrationException:
            registered = False
            time.sleep(1)
            if not help_printed:
                print(
                    "Please press the button on the Hue bridge to connect this app.")
                help_printed = True
    print ("Hub discovery timed out.")
Beispiel #2
0
def setup_bridge(host, hass, add_devices_callback):
    """ Setup a phue bridge based on host parameter. """
    import phue

    try:
        bridge = phue.Bridge(
            host,
            config_file_path=hass.config.path(PHUE_CONFIG_FILE))
    except ConnectionRefusedError:  # Wrong host was given
        _LOGGER.exception("Error connecting to the Hue bridge at %s", host)

        return

    except phue.PhueRegistrationException:
        _LOGGER.warning("Connected to Hue at %s but not registered.", host)

        request_configuration(host, hass, add_devices_callback)

        return

    # If we came here and configuring this host, mark as done
    if host in _CONFIGURING:
        request_id = _CONFIGURING.pop(host)

        configurator = get_component('configurator')

        configurator.request_done(request_id)

    lights = {}

    @util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
    def update_lights():
        """ Updates the Hue light objects with latest info from the bridge. """
        try:
            api = bridge.get_api()
        except socket.error:
            # socket.error when we cannot reach Hue
            _LOGGER.exception("Cannot reach the bridge")
            return

        api_states = api.get('lights')

        if not isinstance(api_states, dict):
            _LOGGER.error("Got unexpected result from Hue API")
            return

        new_lights = []

        for light_id, info in api_states.items():
            if light_id not in lights:
                lights[light_id] = HueLight(int(light_id), info,
                                            bridge, update_lights)
                new_lights.append(lights[light_id])
            else:
                lights[light_id].info = info

        if new_lights:
            add_devices_callback(new_lights)

    update_lights()
Beispiel #3
0
    def connect(self):
        """ Connect to Phillips Hue Hub """
        # pylint: disable=broad-except
        # get hub settings
        hub = self.nodes['hub']
        ip_addr = '{}.{}.{}.{}'.format(
            hub.get_driver('GV1')[0],
            hub.get_driver('GV2')[0],
            hub.get_driver('GV3')[0],
            hub.get_driver('GV4')[0])

        # try to authenticate with the hub
        try:
            self.hub = phue.Bridge(ip_addr,
                                   config_file_path=os.path.join(
                                       os.getcwd(), 'bridges'))
        except phue.PhueRegistrationException:
            self.poly.send_error('IP Address OK. Node Server not registered.')
            return False
        except Exception:
            self.poly.send_error('Cannot find hub at {}'.format(ip_addr))
            return False  # bad ip Addressse:
        else:
            # ensure hub is connectable
            api = self._get_api()

            if api:
                hub.set_driver('GV5', 1)
                hub.report_driver()
                return True
            else:
                self.hub = None
                return False
Beispiel #4
0
def hue_connect(ip):
    global hueBridge
    hueBridge = phue.Bridge(ip)
    try:
        # Note: If Hue data is saved, then this will always succeed, even if the Hue isn't actually on the network!
        hueBridge.connect()  # Press on the Hue button before this line runs
    except:
        print(
            "Error connecting to Hue", ip,
            "Check if it's connected to the network and make sure the button is pressed."
        )
        errorData = {
            "status": "hydra_failed",
            "error": 91,
            "errorMessage": "Connecting to Hue failed",
            "request": {
                "route": "hueconnect"
            }
        }
        client.publish(hueBaseReturnTopic + "/connect", json.dumps(errorData))
    else:
        errorData = {
            "status": "ok",
            "request": {
                "route": "hueconnect"
            },
            "username": hueBridge.username
        }
        client.publish(hueBaseReturnTopic + "/connect", json.dumps(errorData))
Beispiel #5
0
def main():
    audio = pyaudio.PyAudio()
    hue = phue.Bridge('172.17.172.101')

    token = harmony.auth.login('*****@*****.**', '1yD27amH1')
    session_token = harmony.auth.swap_auth_token('172.17.172.100', 5222, token)
    harmony_client = harmony.client.create_and_connect_client(
        '172.17.172.100', 5222, session_token)

    config = harmony_client.get_config()
    activity_map = {act['label']: act['id'] for act in config['activity']}

    while True:
        #triggered = listen_for_trigger(audio, 'Eddie')
        triggered = True
        if triggered:
            say('What can I do for you?')
            wit.init()

            query = wit.voice_query_auto(WIT_TOKEN)

            query = json.loads(query)

            process_query(hue, query, harmony_client, activity_map)

            # Wrapping up
            wit.close()
Beispiel #6
0
    def _connect(self, host, username):
        if host and username:
            self.bridge = phue.Bridge(self.host, username=username)

            self._init()
        else:
            self._setup()
Beispiel #7
0
def check_bridge():
    global bridge
    if not bridge:
        bridge = phue.Bridge(
            ip=config.bridge_host,
            username=config.bridge_username
        )
        bridge.connect()
Beispiel #8
0
 def find_bridge(self):
     try:
         bridge = phue.Bridge(self.bridge_address)
         bridge.connect()
         return bridge
     except phue.PhueRegistrationException:
         logging.info("hue: No bridge registered, press button on bridge and try again")
         self.say(_("No bridge registered, press button on bridge and try again"))
Beispiel #9
0
 def wrapper(*a, **kw):
     global bridge
     if not bridge:
         bridge = phue.Bridge(
             ip=config.bridge_host,
             username=config.bridge_username
         )
         bridge.connect()
     return fn(*a, **kw)
Beispiel #10
0
def connect():
    # found = discoverhue.find_bridges()

    # bridgeIP.lower()
    # bridgeIP = bridgeIP.replace(':80', '')
    # bridgeIP = bridgeIP.replace('http://', '')
    # bridgeIP = bridgeIP.replace('/', '')
    
    bridge = phue.Bridge('192.168.86.21', username)
    bridge.connect()
    return bridge
def discover():
    args = getargs()
    pp = pprint.PrettyPrinter()
    bridge = phue.Bridge(config_file_path=args.conf)
    bridge.connect()

    print("List of Groups")
    pp.pprint(bridge.groups)

    print("List of Scenes")
    pp.pprint(bridge.scenes)
Beispiel #12
0
def get_br():
    '''singleton for bridge'''
    global _brbr

    if not _brbr:
        _brbr = phue.Bridge('192.168.56.150')
        try:
            _brbr.get_light(0)
        except Exception as e:
            print e.message
            _brbr = False
    return _brbr
Beispiel #13
0
def get_lights(ip, user):
    print(ip, user)
    bridge = phue.Bridge(ip, username=user)
    bridge.connect()

    lights = bridge.get_light_objects('name')
    name_id_pair = dict()

    for light in lights:
        name_id_pair[light] = lights[light].light_id

    return name_id_pair
Beispiel #14
0
    def test_register(self):
        """test that registration happens automatically during setup."""
        confname = os.path.join(self.home.path, '.python_hue')
        with mock.patch("phue.Bridge.request") as req:
            req.return_value = [{'success': {'username': '******'}}]
            bridge = phue.Bridge(ip="10.0.0.0")
            self.assertEqual(bridge.config_file_path, confname)

        # check contents of file
        with open(confname) as f:
            contents = f.read()
            self.assertEqual(contents, '{"10.0.0.0": {"username": "******"}}')

        # make sure we can open under a different file
        bridge2 = phue.Bridge(ip="10.0.0.0")
        self.assertEqual(bridge2.username, "fooo")

        # and that we can even open without an ip address
        bridge3 = phue.Bridge()
        self.assertEqual(bridge3.username, "fooo")
        self.assertEqual(bridge3.ip, "10.0.0.0")
Beispiel #15
0
def get_philips_hue_favorites(request):  # pragma: no cover,
    nuimo_app_config_path = request.registry.settings['nuimo_app_config_path']
    mac_address = request.matchdict['mac_address'].replace('-', ':')
    component_id = request.matchdict['component_id']

    with open(nuimo_app_config_path, 'r') as f:
        config = yaml.load(f)

    try:
        nuimo = config['nuimos'][mac_address]
    except (KeyError, TypeError):
        return HTTPNotFound("No Nuimo with such ID")

    components = nuimo['components']

    try:
        component = next(c for c in components if c['id'] == component_id)
    except StopIteration:
        raise HTTPNotFound("No Component with such ID")

    if component['type'] != 'philips_hue':
        return HTTPNotFound("No Philips Hue Component with such ID")

    philips_hue_bridge = phue.Bridge(component['ip_address'], component['username'])
    try:
        scenes = philips_hue_bridge.get_scene()
    except ConnectionResetError:
        return HTTPNotFound("Philips Hue Device not reachable")

    if len(list(scenes.keys())) < 3:
        return HTTPNotFound("less than Three Favorites on Philips Hue")

    scenes_list = []
    supported_scenes = custom_phue_scenes.CUSTOM_SCENES['scenes']

    for scene in scenes:
        if scenes[scene]['name'] in supported_scenes:
            scenes[scene]['id'] = scene
            scenes_list.append(scenes[scene])

    sc = []
    for s in scenes_list:
        sc.append(s['name'])

    scenes_name_list = list(set(sc))
    logger.info(scenes_name_list)

    scene_response = {'favorites': []}
    for s in scenes_name_list:
        scene_response['favorites'].append({'name': s})

    return scene_response
Beispiel #16
0
 def __init__(self, ip_address=None):
     CloudLog.log(self._component, "Initializing.")
     try:
         if ip_address is None:
             ip_address = UDPListener.search(self._search_ip,
                                             self._search_port,
                                             self._search_strings)
         self._phue = phue.Bridge(ip=ip_address, username=self._hueAppID)
         self._ready = True
         CloudLog.log(self._component, "Ready.")
     except Exception, e:
         CloudLog.error(self._component, "Error searching for Hue Bridge",
                        e)
Beispiel #17
0
def _create_bridge(bridge_config):
    if 'host' in bridge_config:
        host = bridge_config['host']
    else:
        response = request.urlopen("https://www.meethue.com/api/nupnp")
        upnp = json.loads(response.read().decode('utf-8'))
        print("upnp:", upnp)

        bridge_object = next(x for x in upnp if x['id'] == bridge_config['id'])
        host = bridge_object['internalipaddress']

        print("Trying hub with address:", host)
    return phue.Bridge(host)
Beispiel #18
0
    def _connect(self):
        if not self.huebridge:
            done = False
            while not done:
                try:
                    self.huebridge = phue.Bridge(self.ip, None, self.pwfile)
                    done = True
                    print("HUE bridge login succesful")
                except phue.PhueRegistrationException:
                    print("Please press the 'connect' button on your HUE bridge.")
                    print("Trying again in 10 seconds..")
                    time.sleep(10)

        logging.debug(f"Attempting to connect to bridge {self.ip} - if this fails, try pushing the button first")
Beispiel #19
0
 def __init__(self, ip, name):
     super(Hue, self).__init__()
     phue.logger.setLevel(logging.INFO)
     self.bridge = phue.Bridge(ip=ip, config_file_path='.hue_config')
     self.light = None
     self.bridge.get_light_objects(mode='id')
     for light in self.bridge.lights_by_id.values():
         if light.name.lower() == name.lower():
             self.light = light
             break
     if not self.light:
         raise Exception("Light with id {0} not found".format(name))
     self.timer = threading.Timer(None, 1)
     self.timer.daemon = True
Beispiel #20
0
    def setup(self):
        """Set up a phue bridge based on host parameter."""
        import phue

        try:
            kwargs = {}
            if self.username is not None:
                kwargs['username'] = self.username
            if self.filename is not None:
                kwargs['config_file_path'] = \
                    self.hass.config.path(self.filename)
            self.bridge = phue.Bridge(self.host, **kwargs)
        except OSError:  # Wrong host was given
            _LOGGER.error("Error connecting to the Hue bridge at %s",
                          self.host)
            return
        except phue.PhueRegistrationException:
            _LOGGER.warning("Connected to Hue at %s but not registered.",
                            self.host)
            self.request_configuration()
            return
        except Exception:  # pylint: disable=broad-except
            _LOGGER.exception("Unknown error connecting with Hue bridge at %s",
                              self.host)
            return

        # If we came here and configuring this host, mark as done
        if self.config_request_id:
            request_id = self.config_request_id
            self.config_request_id = None
            configurator = self.hass.components.configurator
            configurator.request_done(request_id)

        self.configured = True

        discovery.load_platform(self.hass, 'light', DOMAIN,
                                {'bridge_id': self.bridge_id})

        # create a service for calling run_scene directly on the bridge,
        # used to simplify automation rules.
        def hue_activate_scene(call):
            """Service to call directly into bridge to set scenes."""
            group_name = call.data[ATTR_GROUP_NAME]
            scene_name = call.data[ATTR_SCENE_NAME]
            self.bridge.run_scene(group_name, scene_name)

        self.hass.services.register(DOMAIN,
                                    SERVICE_HUE_SCENE,
                                    hue_activate_scene,
                                    schema=SCENE_SCHEMA)
Beispiel #21
0
    def setup(self):
        """Set up a phue bridge based on host parameter."""
        import phue

        try:
            self.bridge = phue.Bridge(
                self.host,
                config_file_path=self.hass.config.path(self.filename))
        except ConnectionRefusedError:  # Wrong host was given
            _LOGGER.error("Error connecting to the Hue bridge at %s",
                          self.host)
            return
        except phue.PhueRegistrationException:
            _LOGGER.warning("Connected to Hue at %s but not registered.",
                            self.host)
            self.request_configuration()
            return

        # If we came here and configuring this host, mark as done
        if self.config_request_id:
            request_id = self.config_request_id
            self.config_request_id = None
            configurator = self.hass.components.configurator
            configurator.request_done(request_id)

        self.configured = True

        # discovery.load_platform(
        #    self.hass, 'light', DOMAIN,
        #    {'bridge_id': socket.gethostbyname(self.host)})
        for platform in PLATFORMS:
            discovery.load_platform(
                self.hass, platform, DOMAIN,
                {'bridge_id': socket.gethostbyname(self.host)})

        # create a service for calling run_scene directly on the bridge,
        # used to simplify automation rules.
        def hue_activate_scene(call):
            """Service to call directly into bridge to set scenes."""
            group_name = call.data[ATTR_GROUP_NAME]
            scene_name = call.data[ATTR_SCENE_NAME]
            self.bridge.run_scene(group_name, scene_name)

        descriptions = load_yaml_config_file(
            os.path.join(os.path.dirname(__file__), 'services.yaml'))
        self.hass.services.register(
            DOMAIN, SERVICE_HUE_SCENE, hue_activate_scene,
            descriptions.get(SERVICE_HUE_SCENE),
            schema=SCENE_SCHEMA)
Beispiel #22
0
def get_devices(hass, config):
    """ Gets the Hue lights. """
    logger = logging.getLogger(__name__)
    try:
        import phue
    except ImportError:
        logger.exception("Error while importing dependency phue.")

        return []

    host = config.get(CONF_HOST, None)

    try:
        bridge = phue.Bridge(
            host, config_file_path=hass.get_config_path(PHUE_CONFIG_FILE))
    except socket.error:  # Error connecting using Phue
        logger.exception(("Error while connecting to the bridge. "
                          "Did you follow the instructions to set it up?"))

        return []

    lights = {}

    @util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
    def update_lights():
        """ Updates the Hue light objects with latest info from the bridge. """
        try:
            api = bridge.get_api()
        except socket.error:
            # socket.error when we cannot reach Hue
            logger.exception("Cannot reach the bridge")
            return

        api_states = api.get('lights')

        if not isinstance(api_states, dict):
            logger.error("Got unexpected result from Hue API")
            return

        for light_id, info in api_states.items():
            if light_id not in lights:
                lights[light_id] = HueLight(int(light_id), info, bridge,
                                            update_lights)
            else:
                lights[light_id].info = info

    update_lights()

    return list(lights.values())
Beispiel #23
0
    def __init__(self, config: Dict[str, Any]):
        self.destination_kafka_topic = config['kafka']['to_slack']['topic']
        self.kafka_producer = kafka.KafkaProducer(
            bootstrap_servers=config['kafka']['bootstrap_servers'], )

        self.kafka_consumer = kafka.KafkaConsumer(
            config['kafka']['from_slack']['topic'],
            bootstrap_servers=config['kafka']['bootstrap_servers'],
            group_id=config['kafka']['from_slack']['group_id'],
        )

        self.hue_bridge = phue.Bridge(
            ip=config['hue_bridge']['ip_address'],
            username=config['hue_bridge']['username'],
        )
Beispiel #24
0
    def __init__(self):
        config_dir = get_config_dir()
        if not os.path.exists(config_dir):
            print 'NOT EXISTS: %r' % config_dir
            os.mkdir(config_dir)

        self.queue = collections.deque()
        self.last_mtime = None

        self.bridge_config_path = os.path.join(config_dir, 'bridge.json')
        self.schedule_config_path = os.path.join(config_dir, 'schedule.json')

        logger.info('using bridge config at %s', self.bridge_config_path)
        self.bridge = phue.Bridge(config_file_path=self.bridge_config_path)
        self.schedule_jobs()
Beispiel #25
0
    def try_bridge_connection(self, cb):
        import phue

        while True:
            try:
                bridge = phue.Bridge(ip=self.selected_bridge)
            except phue.PhueRegistrationException:
                time.sleep(1)
            except Exception:
                import traceback
                traceback.print_exc()
                break
            else:
                self.bridge = bridge
                break

        GLib.idle_add(cb)
Beispiel #26
0
def init_hue(hue_ip):
    """
    Connect to the philips hue bridge. The first time that a connection is
    made, you will need to press the button on the Philips bridge to generate
    user credentials. Credentials are then stored in the home directory for
    future sessions.
    """
    bridge = phue.Bridge(hue_ip)
    _logger.debug(bridge.get_api())

    for i, light in enumerate(bridge.lights, start=1):
        light.on = True
        _logger.info('Found light %s: %s', i, light.name)

    for i, group in enumerate(bridge.groups, start=1):
        _logger.info('Found group %s: %s', i, group.name)

    return bridge
    def __init__(self, ip_address, hue_lights=None, limitlessled_groups=None):
        # setup and connect to Hue bridge
        self.limitless_groups = []
        self.hue_lights = []
        self.lights = []
        if hue_lights:
            b = phue.Bridge(ip_address)
            b.connect()
            self.hue_bridge = b
            self._get_hue_lights(hue_lights)

        if limitlessled_groups:
            for group in limitlessled_groups:
                w = WirelessLights(group)
                self.limitless_groups.append(w)

        self.lights = self.hue_lights + self.limitless_groups
        print("LightManager: lights added together")
Beispiel #28
0
    def get(self):
        print(":P")

        #        try:
        ip = open("ip.txt", "r")
        ip = ip.readline()

        bridge = phue.Bridge(ip=ip)

        bridge.connect()

        function = self.get_argument("function", True)
        name = self.get_argument("light", True)
        value = self.get_argument("value", True)

        print(name)

        if isinstance(function, str):
            function = parse.unquote(function)

        else:
            self.render("lights.html", groups=bridge.groups)

        if isinstance(name, str):
            name = parse.unquote(name)

        light = phue.Group(bridge, name)

        if function == "Turn-on":
            light.on = True

            self.redirect_to_main()

        elif function == "Turn-off":
            light.on = False

            self.redirect_to_main()

        elif function == "Brightness":
            light.brightness = int(value)

            self.redirect_to_main()
Beispiel #29
0
    def __init__(self):
        # always call this first, or OS may crash when you try to open a stream
        pypm.Initialize()

        # wireup input/output
        # TODO : pull MIDI control into separate class
        self.midi_out, self.midi_in = connect_midi()

        # turn off internal LED finger tracking and enable pressure
        set_LEDs_ignore_touch(self.midi_out)
        enable_pressure_output(self.midi_out)

        # TODO : use upnp to get the bridge IP
        #      : phue attempts to do this, but fails in httplib...
        self.b = phue.Bridge(BRIDGE_IP)

        # initialize "all" group
        self.lights = phue.AllLights(bridge=self.b)

        # initialize internal state
        self.brightness = self.lights.brightness
        self.dirty = False

        self.reader = MidiReader(self, interval=.001)
        self.reader.start()

        self.updater = HueUpdater(self, interval=.1)
        self.updater.start()

        for i in range(38):
            led_array_deque[i] = 0

        send_array(led_array_deque, self.midi_out)

        for i in range(19, 38):
            led_array_deque[i] = 1
            led_array_deque[38 - 1 - i] = 1
            send_array(led_array_deque, self.midi_out)
            time.sleep(.05)

        draw_bar(self.midi_out, self.brightness / 2, CURSOR_SIZE)
Beispiel #30
0
    def __init__(self):
        super().__init__("Whistler")

        # self.center = (0.1, 0.1, 0.2)

        # self.velocity = 9  # lower is brighter
        # self.curve = 1
        # self.cap = 1
        # # self.cutin = 0.0
        # # self.cutoff = 1
        # self.hueCo = (1 / 4)
        # self.satCo = (1 / 5)
        # self.briCo = (1 / 1)

        self.velocity = 0.001
        self.curve = 2
        self.cap = 2
        # self.cutin = 0.0
        # self.cutoff = 1
        self.hueCo = 1
        self.satCo = 1 / 5
        self.briCo = 10

        self.frame_rate = 10

        in_stream, input_info = openInputStream(2, self.frame_rate)
        # in_stream, input_info = openOutpoutStream(None, self.frame_rate)
        stream_framerate = int(input_info["defaultSampleRate"])
        chunk_size = stream_framerate // self.frame_rate
        self.live_input_stream = LiveInputStream(in_stream, chunk_size)
        self.live_input_stream.start()

        self.threshold = 4

        bridgeIP = '192.168.1.227'
        self.b = phue.Bridge(bridgeIP)
        self.b.connect()