Esempio n. 1
0
    def rebuild_bulbs(self):
        found_bulb_ips = sorted(bulb['ip']
                                for bulb in yeelight.discover_bulbs(3)
                                if bulb['ip'] in room_to_ips[self.name])
        current_bulb_ips = sorted(bulb._ip for bulb in self.bulbs)
        if current_bulb_ips != found_bulb_ips:
            logger.info('Different bulbs!')
            logger.info('Found bulbs: %s', ', '.join(found_bulb_ips))

            # Clear out the bulbs, since they don't like having multiple
            #   connections to the same machine.
            del self.bulbs[:]

            if YEELIGHT_STATIC_REBUILD:
                logger.info('Statically rebuilding bulb list')
                self.bulbs = [
                    yeelight.Bulb(ip) for ip in room_to_ips[self.name]
                ]
            else:
                self.bulbs = [
                    yeelight.Bulb(found_ip) for found_ip in found_bulb_ips
                ]
            try:
                self.resetFromLoggedState()
            except Exception:
                logger.exception(
                    'Got exception when restting bulbs in rebuild_bulbs')
Esempio n. 2
0
 def __init__(self, ip):
     self.clients = [
         yeelight.Bulb(
             ip,
             effect="smooth",
             duration=100,
             auto_on=False,
             model=yeelight.BulbType.WhiteTempMood,
         ),
         yeelight.Bulb(
             ip,
             effect="smooth",
             duration=100,
             auto_on=False,
             model=yeelight.BulbType.WhiteTempMood,
         ),
         yeelight.Bulb(
             ip,
             effect="smooth",
             duration=100,
             auto_on=False,
             model=yeelight.BulbType.WhiteTempMood,
         ),
     ]
     self.index = 0
Esempio n. 3
0
def get_bulb():
    def get_parameters(bulb_dict):
        capabilities = bulb_dict.get('capabilities')
        return \
            bulb_dict.get('ip'), \
            bulb_dict.get('port'), \
            capabilities.get('model'), \
            capabilities.get('name'), \
            capabilities.get('power')

    bulbs_discovered = yeelight.discover_bulbs()
    log_message = 'ip = {0}, port = {1}, model = {2}, name = {3}, power = {4}'

    if len(bulbs_discovered) == 1:
        ip, port, model, name, power = get_parameters(bulbs_discovered.pop())
        logging.info('One bulb found, proceeding: ' +
                     log_message.format(ip, port, model, name, power))

        return yeelight.Bulb(ip)

    elif len(bulbs_discovered) == 0:
        raise Exception(
            'No bulbs found nearby. '
            'Make sure you\'re running the script using the same local network your bulb connected to.'
        )
    else:  # more than one bulb found
        bulbs_found_msg = ''
        for index, bulb in enumerate(bulbs_discovered):
            ip, port, model, name, power = get_parameters(bulb)
            bulbs_found_msg += f'\t#{index}:\t\t{log_message.format(ip, port, model, name, power)}\n'

        logging.info(f'More than one bulb found:\n {bulbs_found_msg}')
        while True:
            try:
                chosen_index = int(
                    input('Please input the # of the bulb you want to use '
                          f'(0-{len(bulbs_discovered) - 1}): '))
            except ValueError:
                logging.error('Input must be an integer!\n')
                continue
            if chosen_index in range(len(bulbs_discovered)):
                ip, port, model, name, power = get_parameters(
                    bulbs_discovered[chosen_index])
                logging.info('Proceeding: ' +
                             log_message.format(ip, port, model, name, power))

                return yeelight.Bulb(ip)
            else:
                logging.error(
                    f'The bulb # should be in range [0-{len(bulbs_discovered) - 1}]\n'
                )
Esempio n. 4
0
def main():
    global bulb, alarm
    cparse = argparse.ArgumentParser(
        prog = 'yeelight-alarm-clock',
        description = 'Turn on yeelight at certain time, like an alarm clock')
    cparse.add_argument('time', help = 'time to turn on the clock', type = parse_time)
    cargs = cparse.parse_args()

    alarm = get_next_time(cargs.time)

    bulb = yeelight.Bulb(ip)
    bulb.turn_on()
    #print(bulb.get_properties())
    bulb.start_flow(blink_flow)
    time.sleep(5)

    # Bulb will reconnect on next command, we do not want to maintain the socket the whole night
    disconnect_bulb(bulb)

    wait_until(alarm)
    print('Alarm on')
    try:
        d = 5
        bulb.effect = 'sudden'
        bulb.turn_on()
        bulb.start_flow(alarm_flow)
        while True:
            time.sleep(100)
    except KeyboardInterrupt:
        bulb.turn_off()
        print('Alarm off')
Esempio n. 5
0
def build_bulb(bulb, yee_effect):
    port = 55443
    if 'port' in bulb:
        port = bulb['port']

    effect = 'sudden'
    if 'effect' in yee_effect:
        effect = yee_effect['effect']
    elif 'effect' in bulb:
        effect = bulb['effect']

    duration = 500
    if 'duration' in yee_effect:
        duration = yee_effect['duration']
    elif 'duration' in bulb:
        duration = bulb['duration']

    auto_on = True
    if 'auto_on' in yee_effect:
        auto_on = yee_effect['auto_on']
    elif 'auto_on' in bulb:
        auto_on = bulb['auto_on']

    return yeelight.Bulb(
        ip=bulb['ip'],
        port=port,
        effect=effect,
        duration=duration,
        auto_on=auto_on,
    )
    async def _async_try_connect(self, host):
        """Set up with options."""
        for entry in self._async_current_entries():
            if entry.data.get(CONF_HOST) == host:
                raise AlreadyConfigured

        bulb = yeelight.Bulb(host)
        try:
            capabilities = await self.hass.async_add_executor_job(
                bulb.get_capabilities)
            if capabilities is None:  # timeout
                _LOGGER.debug("Failed to get capabilities from %s: timeout",
                              host)
            else:
                _LOGGER.debug("Get capabilities: %s", capabilities)
                await self.async_set_unique_id(capabilities["id"])
                self._abort_if_unique_id_configured()
                return
        except OSError as err:
            _LOGGER.debug("Failed to get capabilities from %s: %s", host, err)
            # Ignore the error since get_capabilities uses UDP discovery packet
            # which does not work in all network environments

        # Fallback to get properties
        try:
            await self.hass.async_add_executor_job(bulb.get_properties)
        except yeelight.BulbException as err:
            _LOGGER.error("Failed to get properties from %s: %s", host, err)
            raise CannotConnect from err
        _LOGGER.debug("Get properties: %s", bulb.last_properties)
def add_device(name, ip):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(1)
    try:
        response = sock.connect_ex((ip, 55443))
        if response == 0:
            bulb = yeelight.Bulb(ip, duration=500)
            bulb_info = bulb.get_capabilities()
            if len(name) == 0:
                if len(bulb_info['name']) != 0:
                    name = bulb_info['name']
                else:
                    name = bulb_info['model']
            bulb.set_name(name)
            cursor.execute(
                '''INSERT INTO lights (
								id, ip, name, model
							)
							VALUES (
								?, ?, ?, ?
							)''', (int(bulb_info['id'][2:], 16), ip, name, bulb_info['model']))
            db.commit()
            print(int(bulb_info['id'][2:], 16), ip, name, bulb_info['model'])
            return True
    except Exception as e:
        print(e)
    return False
Esempio n. 8
0
 def __init__(self, settings, not_used):
     self.setting = settings
     self._find_lamp_ip()
     self._try_connect()
     self.lamp_bulb = yeelight.Bulb(self.setting["lamp_ip"], auto_on=True)
     self.proterius = None
     super().__init__(settings, not_used)
Esempio n. 9
0
def cli(ip, port, effect, duration, bulb, auto_on):
    """
    yeecli is a command-line utility for controlling the YeeLight RGB LED
    lightbulb.
    """
    config = ConfigParser.SafeConfigParser()
    config.read([os.path.expanduser('~/.config/yeecli/yeecli.cfg')])

    ip = param_or_config(ip, config, bulb, "ip", None)
    port = param_or_config(port, config, bulb, "port", 55443)
    effect = param_or_config(effect, config, bulb, "effect", "sudden")
    duration = param_or_config(duration, config, bulb, "duration", 500)

    if not ip:
        click.echo("No IP address specified.")
        sys.exit(1)

    BULBS.append(
        yeelight.Bulb(
            ip=ip,
            port=port,
            effect=effect,
            duration=duration,
            auto_on=auto_on,
        ))
Esempio n. 10
0
    async def _async_try_connect(self, host):
        """Set up with options."""
        self._async_abort_entries_match({CONF_HOST: host})

        bulb = yeelight.Bulb(host)
        try:
            capabilities = await self.hass.async_add_executor_job(
                bulb.get_capabilities)
            if capabilities is None:  # timeout
                _LOGGER.debug("Failed to get capabilities from %s: timeout",
                              host)
            else:
                _LOGGER.debug("Get capabilities: %s", capabilities)
                await self.async_set_unique_id(capabilities["id"])
                return capabilities["model"]
        except OSError as err:
            _LOGGER.debug("Failed to get capabilities from %s: %s", host, err)
            # Ignore the error since get_capabilities uses UDP discovery packet
            # which does not work in all network environments

        # Fallback to get properties
        try:
            await self.hass.async_add_executor_job(bulb.get_properties)
        except yeelight.BulbException as err:
            _LOGGER.error("Failed to get properties from %s: %s", host, err)
            raise CannotConnect from err
        _LOGGER.debug("Get properties: %s", bulb.last_properties)
        return MODEL_UNKNOWN
Esempio n. 11
0
    def __init__(self, group_name, names, loadfile=None):
        self.group_name = group_name
        self.names = names  # store in case you want to reconnect or something idk
        self.loadfile = loadfile
        self.bulbs = []

        bulb_dicts = yl.discover_bulbs()
        for bulb_dict in bulb_dicts:
            if bulb_dict['capabilities']['name'] in names:
                self.bulbs.append(Bulb(yl.Bulb(bulb_dict['ip'])))

        self.prev_t = time.time()

        if loadfile:
            self.load_state()
        else:
            self.loadfile = group_name + '_latest.txt'
            self.turn_on()
            self.on = True
            self.h = 0
            self.s = 0
            self.brightness = 100
            self.degrees = 3800
            self.r = 255
            self.g = 255
            self.b = 255

            self.set_mode(yl.PowerMode.NORMAL)
Esempio n. 12
0
    def __init__(self, parent=None):
        super(TabletSampleWindow, self).__init__(parent)
        self.MAX_CLICK = 10.
        self.MOVE_CHUNK = 40
        self.BRIGHT_INC = 5
        self.CT_INC = 250
        self.MAX_PRESSURE = 50
        self.text = ""
        self.pen_pressure = 0
        self.max_pressure = 0
        self.mode = None
        self.moved = False

        # Resizing the sample window to full desktop size:
        frame_rect = app.desktop().frameGeometry()
        width, height = frame_rect.width(), frame_rect.height()
        self.resize(width, height)
        self.move(-9, 0)
        self.setWindowTitle("Yeelight Control Center")
        self.width = width
        self.height = height

        # discover all light bulbs and setup first one
        bulbs = yeelight.discover_bulbs()
        if len(bulbs) == 0:
            print("No Yeelight Bulbs discovered! exiting...")
            sys.exit(0)
        self.bulb = yeelight.Bulb(ip=bulbs[0]['ip'])
        print(f"Connected to bulb on ip {bulbs[0]['ip']}")

        self.specs = self.bulb.get_model_specs()
        self.min_ct = self.specs['color_temp']['min']
        self.max_ct = self.specs['color_temp']['max']
        self.sync_bulb()
        schedule.every(5).minutes.do(self.sync_bulb)
def toggle(ip):
    bulb = yeelight.Bulb(ip, duration=TRANSITION_DURATION)
    bulb.toggle()
    try:
        state = bulb.get_capabilities()['power']
    except:
        state = 'Offline'
    return state
Esempio n. 14
0
def connect(light):
    ip = light.protocol_cfg["ip"]
    if ip in Connections:
        c = Connections[ip]
    else:
        c = yeelight.Bulb(ip)
        Connections[ip] = c
    return c
Esempio n. 15
0
 def __init__(self, mqtt, device):
     self.bulb = yeelight.Bulb(device["ip"],
                               effect='smooth',
                               duration=device["duration"],
                               power_mode=yeelight.PowerMode.LAST)
     self.mqtt = mqtt
     self.topic = device["topic"]
     self.report = config["types"][device["type"]]["report"]
     self.actions = config["types"][device["type"]]["actions"]
Esempio n. 16
0
def discover_lights():
    global lights_available
    while len(lights_available) == 0:
        lights_available = dict()
        for light in yeelight.discover_bulbs():
            prefix = light["capabilities"]["name"] + '-'
            name = (prefix if prefix != '-' else '') + light["ip"]
            lights_available[name] = yeelight.Bulb(
                light["ip"], effect=config.lightingMode.lightTransitions)
        return lights_available
Esempio n. 17
0
def toggle(systray):
    var = y.discover_bulbs()

    if len(var) < 1:
        var = "192.168.1.3"
    else:
        var = var[0]["ip"]

    bulb = y.Bulb(var)
    bulb.toggle()
Esempio n. 18
0
 def __init__(self, ip, new_light=True, **kwargs):
     global lights
     super().__init__(**kwargs)
     self.ip = ip
     self.light = len(lights)
     lights.append(yeelight.Bulb(self.ip))
     lights[self.light].auto_on = True
     if new_light:
         light_data.append({"ip": self.ip, "name": self.name})
     with open(__file__[:-11] + "lights.json", "w") as f:
         json.dump(light_data, f)
Esempio n. 19
0
def get_bulbs(timeout=0.2):
    'Get a list of bulbs that are reachable'
    # TODO
    return BULBS
    bulbs = [
        yeelight.Bulb(blb['ip']) for blb in yeelight.discover_bulbs(timeout)
        if blb['ip'] in BULB_IPS
    ]
    if len(bulbs) != len(BULB_IPS):
        logger.info('Found %d bulbs, expected %d', len(bulbs), len(BULB_IPS))
    return bulbs
def assert_connect_bulbs():
    infos = yeelight.discover_bulbs()

    bulbs = []

    for info in infos:
        bulbs.append(yeelight.Bulb(info['ip']))
    if(len(bulbs) == 0):
        raise yeelight.BulbException(ERROR_STR)

    return bulbs
Esempio n. 21
0
def do_set_hsv(address, hue, saturation, value, lighttype):
    try:
        bulb = yeelight.Bulb(address)
        if value and lighttype:
            bulb.set_hsv(hue, saturation, value, lighttype)
        elif value:
            bulb.set_hsv(hue, saturation, value)
        elif lighttype:
            bulb.set_hsv(hue, saturation, None, lighttype)
        else:
            bulb.set_hsv(hue, saturation)
    except Exception as e:
        log.error(e)
Esempio n. 22
0
    def _bulb(self) -> 'yeelight.Bulb':
        import yeelight
        if self._bulb_device is None:
            try:
                self._bulb_device = yeelight.Bulb(self._ipaddr)
                self._bulb_device.get_properties()  # force init for type

                self._available = True
            except yeelight.BulbException as ex:
                self._available = False
                _LOGGER.error("Failed to connect to bulb %s, %s: %s",
                              self._ipaddr, self._name, ex)

        return self._bulb_device
Esempio n. 23
0
def getBulb():
    global bulb_connected
    
    if (len(yee.discover_bulbs())):
        for bulb_meta in yee.discover_bulbs():
            if bulb_meta['capabilities']['id'] == bulb_id:
                bulb_connected = True
                bulb = yee.Bulb(bulb_meta['ip'])
                bulb.set_brightness(BRIGHTNESS)
                return bulb
    else:
        bulb_connected = False
        print("unable to connect to bulb... Retrying!..")
        time.sleep(10)
        return getBulb()
Esempio n. 24
0
    def bulb(self):
        """Return bulb device."""
        if self._bulb_device is None:
            import yeelight
            try:
                self._bulb_device = yeelight.Bulb(self._ipaddr,
                                                  model=self._model)
                # force init for type
                self.update()

                self._available = True
            except yeelight.BulbException as ex:
                self._available = False
                _LOGGER.error("Failed to connect to bulb %s, %s: %s",
                              self._ipaddr, self._name, ex)

        return self._bulb_device
Esempio n. 25
0
 async def _async_try_connect(self, host):
     """Set up with options."""
     bulb = yeelight.Bulb(host)
     try:
         capabilities = await self.hass.async_add_executor_job(
             bulb.get_capabilities)
         if capabilities is None:  # timeout
             _LOGGER.error("Failed to get capabilities from %s: timeout",
                           host)
             raise CannotConnect
     except OSError as err:
         _LOGGER.error("Failed to get capabilities from %s: %s", host, err)
         raise CannotConnect from err
     _LOGGER.debug("Get capabilities: %s", capabilities)
     self._capabilities = capabilities
     await self.async_set_unique_id(capabilities["id"])
     self._abort_if_unique_id_configured()
Esempio n. 26
0
    def _bulb(self) -> object:
        import yeelight
        if self._bulb_device is None:
            try:
                self._bulb_device = yeelight.Bulb(self._ipaddr)
                self._bulb_device.get_properties()  # force init for type

                btype = self._bulb_device.bulb_type
                if btype == yeelight.BulbType.Color:
                    self._supported_features |= SUPPORT_YEELIGHT_RGB
                self._available = True
            except yeelight.BulbException as ex:
                self._available = False
                _LOGGER.error("Failed to connect to bulb %s, %s: %s",
                              self._ipaddr, self._name, ex)

        return self._bulb_device
def get_lights():
    cursor.execute('''SELECT * FROM lights;''')
    result = cursor.fetchall()
    lights = []
    for id, ip, name, model in result:
        bulb = yeelight.Bulb(ip)
        try:
            state = bulb.get_capabilities()['power']
        except:
            state = 'Offline'
        lights.append({
            'id': id,
            'ip': ip,
            'name': name,
            'model': model,
            'state': state
        })
    return lights
Esempio n. 28
0
def control_init():
    # bulb and sonos init
    sonos = soco.SoCo('192.168.3.159')
    # bulb = yeelight.Bulb(yeelight.discover_bulbs(timeout=10)[0].get('ip'))
    bulb = yeelight.Bulb('192.168.3.155')

    print(sonos)
    if sonos:
        sonos.play_mode = 'REPEAT_ONE'
        sonos.play_uri(
            'http://img.tukuppt.com/newpreview_music/09/01/52/5c89f044e48f61497.mp3'
        )
        sonos.volumn = 6
        sonos.mute = False
    print(bulb)
    if bulb:
        bulb.turn_off()
        # bulb.set_brightness(10)

    return sonos, bulb
def rebuild_bulbs():
    "Rebuild the bulb list."
    if YEELIGHT_ROOM_HANDLES_REBUILD:
        for room in ROOMS.values():
            room.rebuild_bulbs()
    else:
        global bulbs
        found_bulbs_ip = sorted(bulb['ip'] for bulb in yeelight.discover_bulbs(1))
        current_bulbs_ips = sorted(bulb._ip for bulb in bulbs)
        if current_bulbs_ips != found_bulbs_ip:
            new_ips = set(found_bulbs_ip) - set(current_bulbs_ips)
            missing_ips = set(current_bulbs_ips) - set(found_bulbs_ip)
            for new_ip in new_ips:
                logger.info('Found new bulb at ip addr: %s', new_ip)
            for missing_ip in missing_ips:
                logger.info('Missing bulb at ip addr: %s', missing_ip)
                
            bulbs = [yeelight.Bulb(found_ip) for found_ip in found_bulbs_ip]
            for room in ROOMS.values():
                room.rebuild_bulbs()
Esempio n. 30
0
def main():
    get_saved_lights()
    check_ip_change()
    try:
        while True:
            menu()
            scelta = int_input(0, 4)
            if scelta == 1:
                print("Scegli quale luce vuoi controllare:")
                get_saved_lights()
                sc = int_input(0, ((len(saved_lights) - 1) / 2))
                print("Ciao")
                ####Controllare la luce

            elif scelta == 2:
                luci = yee.discover_bulbs()
                if len(luci) == 0:
                    print("Non ho trovato luci nella tua rete")
                else:
                    print_lights(luci)
                    sc = int_input(0, len(luci) - 1)
                    add_light(luci[sc])
                get_saved_lights()

            elif scelta == 3:
                del_file()
                print("Luci associate eliminate")
                get_saved_lights()

            elif scelta == 4:
                for light in saved_lights:
                    luce = yee.Bulb(light["ip"])
                    luce.toggle()
                    print("Toggle di {}".format(light["name"]))
            elif scelta == 0:
                raise KeyboardInterrupt
            else:
                print("La scelta corrispondente non esiste")
    except KeyboardInterrupt:
        print("\n\nHai terminato il programma.")
        exit()