Ejemplo n.º 1
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Flux lights."""
    lights = []
    light_ips = []

    for ipaddr, device_config in config.get(CONF_DEVICES, {}).items():
        device = {}
        device["name"] = device_config[CONF_NAME]
        device["ipaddr"] = ipaddr
        device[CONF_PROTOCOL] = device_config.get(CONF_PROTOCOL)
        device[ATTR_MODE] = device_config[ATTR_MODE]
        device[CONF_CUSTOM_EFFECT] = device_config.get(CONF_CUSTOM_EFFECT)
        light = FluxLight(device)
        lights.append(light)
        light_ips.append(ipaddr)

    if not config.get(CONF_AUTOMATIC_ADD, False):
        add_entities(lights, True)
        return

    # Find the bulbs on the LAN
    scanner = BulbScanner()
    scanner.scan(timeout=10)
    for device in scanner.getBulbInfo():
        ipaddr = device["ipaddr"]
        if ipaddr in light_ips:
            continue
        device["name"] = f"{device['id']} {ipaddr}"
        device[ATTR_MODE] = None
        device[CONF_PROTOCOL] = None
        device[CONF_CUSTOM_EFFECT] = None
        light = FluxLight(device)
        lights.append(light)

    add_entities(lights, True)
Ejemplo n.º 2
0
    def discover(self, *args, **kwargs):
        _success = False
        try:
            LOGGER.info('Discovering MagicHome LED Controllers...')
            _scanner = BulbScanner()
            _scanner.scan(timeout=5)
            _devices = _scanner.getBulbInfo()
            LOGGER.info('%i bulbs found. Checking status and adding to ISY', len(_devices))
            for d in _devices:
                self._addNode(d)
            _success = True
        except Exception as ex:
            LOGGER.error('Error running magichome discovery (%s)', str(ex))
        
        try:
            _items = 0
            self.discoveryTries = 0
            _params = self.polyConfig['customParams']
            for key,value in _params.items():
                _key = key.lower()
                if _key.startswith('led'):
                    _items += 1
                    try:
                        if 'ip' in value and 'mac' in value:
                            _value = json.loads(value)
                            _ip = _value['ip']
                            _mac = _value['mac'].lower().replace(':','')
                            d = {'ipaddr': _ip, 'id': _mac}
                            self._addNode(d)
                    except Exception as ex:
                        LOGGER.error('Error adding node from Polyglot configuration (%s): %s', str(value), str(ex))
            if _items == 0:
                LOGGER.info('NOTE: LED Controllers can be specified for addition even if not detected via discovery.  Add a custom configuration parameter to Polyglot for each LED controller with a key starting with "LED".  The value should be in the following format, note the use of double quotes: {"ip":"192.168.0.84", "mac":"F0FEAF241937"}  "mac" is the MAC address without colons.')
        except Exception as ex:
            LOGGER.error('Error processing custom node addition from Polyglot configuration: %s', str(ex))
            
        try:
            _params = self.polyConfig['customParams']
            global UPDATE_DELAY
            if 'delay' in _params:
                UPDATE_DELAY = float(_params['delay'])
            else:
                LOGGER.info("NOTE: A delay can be specified to wait a bit for the LED controller to process commands before querying them to update the controller's state in the ISY.  Defaults to %s sec.", str(UPDATE_DELAY))
        except Exception as ex:
            LOGGER.error('Error obtaining device delay value from Polyglot configuration: %s',str(ex))
        
        try:
            _params = self.polyConfig['customParams']
            global QUERY_BEFORE_CMD
            if 'query_before_cmd' in _params:
                QUERY_BEFORE_CMD = bool(_params['query_before_cmd'])
        except Exception as ex:
            LOGGER.error('Error obtaining query_before_cmd flag from Polyglot configuration: %s',str(ex))

        self.firstRun = False
        return _success
Ejemplo n.º 3
0
class Scanner(object):
    def __init__(self, bulb_map, period, fake=False):
        self._bulb_map = bulb_map
        self._period = period
        self._fake = fake
        self._thread = None
        self._lock = threading.Lock()
        self._stop = threading.Event()
        self._scanner = BulbScanner()

        self._lights = {}

        self._thread = threading.Thread(target=self._scan)
        self._thread.start()

    def stop(self):
        self._stop.set()
        self._thread.join()

    def lights(self):
        with self._lock:
            return self._lights

    def lock(self):
        return self._lock

    def _scan(self):
        while not self._stop.is_set():
            with self._lock:
                new_lights = {}
                print('Scanning for bulbs')
                old_names = tuple(self._lights.keys())
                found_names = []
                if not self._fake:
                    self._scanner.scan(timeout=4)

                    for scanned in self._scanner.getBulbInfo():
                        bid = scanned['id']
                        if bid in self._bulb_map:
                            print('Found real bulb: %s' %
                                  (self._bulb_map[bid], ))
                            new_lights[self._bulb_map[bid]] = {'info': scanned}
                            found_names.append(self._bulb_map[bid])
                else:
                    for i, id in enumerate(self._bulb_map):
                        print('Found fake bulb: %s' % (self._bulb_map[id], ))
                        new_lights[self._bulb_map[id]] = {
                            'info': {
                                'ipaddr': '10.0.0.%d' % i
                            }
                        }
                        found_names.append(self._bulb_map[id])

                # Clear out any bulbs that went missing
                for name in old_names:
                    if name not in found_names:
                        print('Removing missing light: ', name)
                for name in found_names:
                    if name not in old_names:
                        print('Adding new bulb: ', name)

                for name, l in new_lights.items():
                    if not l['info']:
                        print('Did not find expected bulb', name)
                        sys.exit(1)
                    if not self._fake:
                        l['bulb'] = WifiLedBulb(l['info']['ipaddr'])
                    else:
                        l['bulb'] = FakeBulb(name)

                if len(new_lights) != len(self._bulb_map):
                    print("Warning: didn't find all the lights")
                self._lights = new_lights

            # Sleep, but keep checking for quit while we do.
            for i in range(0, self._period):
                if self._stop.is_set():
                    return
                time.sleep(1)