def setup_platform(opp, config, add_entities, discovery_info=None): """Set up the Nanoleaf light.""" if DATA_NANOLEAF not in opp.data: opp.data[DATA_NANOLEAF] = {} token = "" if discovery_info is not None: host = discovery_info["host"] name = None device_id = discovery_info["properties"]["id"] # if device already exists via config, skip discovery setup if host in opp.data[DATA_NANOLEAF]: return _LOGGER.info("Discovered a new Nanoleaf: %s", discovery_info) conf = load_json(opp.config.path(CONFIG_FILE)) if host in conf and device_id not in conf: conf[device_id] = conf.pop(host) save_json(opp.config.path(CONFIG_FILE), conf) token = conf.get(device_id, {}).get("token", "") else: host = config[CONF_HOST] name = config[CONF_NAME] token = config[CONF_TOKEN] nanoleaf_light = Nanoleaf(host) if not token: token = nanoleaf_light.request_token() if not token: _LOGGER.error( "Could not generate the auth token, did you press " "and hold the power button on %s" "for 5-7 seconds?", name, ) return conf = load_json(opp.config.path(CONFIG_FILE)) conf[host] = {"token": token} save_json(opp.config.path(CONFIG_FILE), conf) nanoleaf_light.token = token try: info = nanoleaf_light.info except Unavailable: _LOGGER.error("Could not connect to Nanoleaf Light: %s on %s", name, host) return if name is None: name = info.name opp.data[DATA_NANOLEAF][host] = nanoleaf_light add_entities([NanoleafLight(nanoleaf_light, name)], True)
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Nanoleaf light.""" from pynanoleaf import Nanoleaf, Unavailable if DATA_NANOLEAF not in hass.data: hass.data[DATA_NANOLEAF] = dict() token = "" if discovery_info is not None: host = discovery_info["host"] name = discovery_info["hostname"] # if device already exists via config, skip discovery setup if host in hass.data[DATA_NANOLEAF]: return _LOGGER.info("Discovered a new Nanoleaf: %s", discovery_info) conf = load_json(hass.config.path(CONFIG_FILE)) if conf.get(host, {}).get("token"): token = conf[host]["token"] else: host = config[CONF_HOST] name = config[CONF_NAME] token = config[CONF_TOKEN] nanoleaf_light = Nanoleaf(host) if not token: token = nanoleaf_light.request_token() if not token: _LOGGER.error( "Could not generate the auth token, did you press " "and hold the power button on %s" "for 5-7 seconds?", name, ) return conf = load_json(hass.config.path(CONFIG_FILE)) conf[host] = {"token": token} save_json(hass.config.path(CONFIG_FILE), conf) nanoleaf_light.token = token try: nanoleaf_light.available except Unavailable: _LOGGER.error("Could not connect to Nanoleaf Light: %s on %s", name, host) return hass.data[DATA_NANOLEAF][host] = nanoleaf_light add_entities([NanoleafLight(nanoleaf_light, name)], True)
async def _async_discovery_handler( self, discovery_info: DiscoveryInfoType) -> FlowResult: """Handle Nanoleaf discovery.""" host = discovery_info["host"] # The name is unique and printed on the device and cannot be changed. name = discovery_info["name"].replace(f".{discovery_info['type']}", "") await self.async_set_unique_id(name) self._abort_if_unique_id_configured({CONF_HOST: host}) self.nanoleaf = Nanoleaf(host) # Import from discovery integration self.device_id = discovery_info["properties"]["id"] self.discovery_conf = cast( dict, await self.hass.async_add_executor_job( load_json, self.hass.config.path(CONFIG_FILE)), ) self.nanoleaf.token = self.discovery_conf.get(self.device_id, {}).get( "token", # >= 2021.4 self.discovery_conf.get(host, {}).get("token"), # < 2021.4 ) if self.nanoleaf.token is not None: _LOGGER.warning( "Importing Nanoleaf %s from the discovery integration", name) return await self.async_setup_finish( discovery_integration_import=True) self.context["title_placeholders"] = {"name": name} return await self.async_step_link()
async def async_step_user(self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Handle Nanoleaf flow initiated by the user.""" if user_input is None: return self.async_show_form(step_id="user", data_schema=USER_SCHEMA, last_step=False) self._async_abort_entries_match({CONF_HOST: user_input[CONF_HOST]}) self.nanoleaf = Nanoleaf(user_input[CONF_HOST]) try: await self.hass.async_add_executor_job(self.nanoleaf.authorize) except Unavailable: return self.async_show_form( step_id="user", data_schema=USER_SCHEMA, errors={"base": "cannot_connect"}, last_step=False, ) except NotAuthorizingNewTokens: pass except Exception: # pylint: disable=broad-except _LOGGER.exception("Unknown error connecting to Nanoleaf") return self.async_show_form( step_id="user", data_schema=USER_SCHEMA, last_step=False, errors={"base": "unknown"}, ) return await self.async_step_link()
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Nanoleaf light.""" from pynanoleaf import Nanoleaf, Unavailable if DATA_NANOLEAF not in hass.data: hass.data[DATA_NANOLEAF] = dict() token = '' if discovery_info is not None: host = discovery_info['host'] name = discovery_info['hostname'] # if device already exists via config, skip discovery setup if host in hass.data[DATA_NANOLEAF]: return _LOGGER.info("Discovered a new Nanoleaf: %s", discovery_info) conf = load_json(hass.config.path(CONFIG_FILE)) if conf.get(host, {}).get('token'): token = conf[host]['token'] else: host = config[CONF_HOST] name = config[CONF_NAME] token = config[CONF_TOKEN] nanoleaf_light = Nanoleaf(host) if not token: token = nanoleaf_light.request_token() if not token: _LOGGER.error("Could not generate the auth token, did you press " "and hold the power button on %s" "for 5-7 seconds?", name) return conf = load_json(hass.config.path(CONFIG_FILE)) conf[host] = {'token': token} save_json(hass.config.path(CONFIG_FILE), conf) nanoleaf_light.token = token try: nanoleaf_light.available except Unavailable: _LOGGER.error( "Could not connect to Nanoleaf Light: %s on %s", name, host) return hass.data[DATA_NANOLEAF][host] = nanoleaf_light add_entities([NanoleafLight(nanoleaf_light, name)], True)
async def async_step_import(self, config: dict[str, Any]) -> FlowResult: """Handle Nanoleaf configuration import.""" self._async_abort_entries_match({CONF_HOST: config[CONF_HOST]}) _LOGGER.debug("Importing Nanoleaf on %s from your configuration.yaml", config[CONF_HOST]) self.nanoleaf = Nanoleaf(config[CONF_HOST]) self.nanoleaf.token = config[CONF_TOKEN] return await self.async_setup_finish()
async def async_step_reauth(self, data: dict[str, str]) -> FlowResult: """Handle Nanoleaf reauth flow if token is invalid.""" self.reauth_entry = cast( config_entries.ConfigEntry, self.hass.config_entries.async_get_entry(self.context["entry_id"]), ) self.nanoleaf = Nanoleaf(data[CONF_HOST]) self.context["title_placeholders"] = {"name": self.reauth_entry.title} return await self.async_step_link()
def __init__(self, controller, primary, address, name, ip, token): super(AuroraNode, self).__init__(controller, primary, address, name) self.queryON = True self.nano_ip = ip self.nano_token = token self.arrEffects = None try: self.my_aurora = Nanoleaf(host=self.nano_ip, token=self.nano_token) except Exception as ex: LOGGER.error('Error unable to connect to NanoLeaf Aurora: %s', str(ex)) self.__getEffetsList() self.__BuildProfile() self.query()
def start(self): LOGGER.info('Started NanoLeaf Aurora for v2 NodeServer version %s', str(VERSION)) try: # Get and set IP if 'ip' in self.polyConfig['customParams']: self.nano_ip = self.polyConfig['customParams']['ip'] LOGGER.info('Custom IP address specified: {}'.format( self.nano_ip)) else: LOGGER.error('Need to have ip address in custom param ip') self.setDriver('ST', 0, True) return False # Get saved token if 'nano_token' in self.polyConfig['customParams']: self.nano_token = self.polyConfig['customParams']['nano_token'] if self.nano_token == ' ': self.nano_token = None LOGGER.debug('Retrieved token : {}'.format(self.nano_token)) # If token is provided overwrite the saved token if 'token' in self.polyConfig['customParams']: self.nano_token = self.polyConfig['customParams']['token'] self.saveCustomData({'nano_token': self.nano_token}) LOGGER.debug('Custom token specified: {}'.format( self.nano_token)) LOGGER.info('Saving token to the Database') # Reinitialize token only if token was not provided if 'requestNewToken' in self.polyConfig[ 'customParams'] and 'token' not in self.polyConfig[ 'customParams']: self.nano_token = None self.saveCustomData({'nano_token': ' '}) LOGGER.debug('Resetting token') # Obtain NanoLeaf token, make sure to push on the power button of Aurora until Light is Flashing if self.nano_token is None: LOGGER.debug('Requesting Token') for myHost in self.nano_ip.split(','): nanoleaf = Nanoleaf(host=myHost) myToken = nanoleaf.request_token() if myToken is None: myToken = ' ' LOGGER.error( 'Unable to obtain one of the token, make sure all NanoLeaf are in Linking mode.' ) if self.nano_token is None: self.nano_token = myToken else: self.nano_token = self.nano_token + ',' + myToken self.saveCustomData({'nano_token': self.nano_token}) LOGGER.debug('Token received: {}'.format(self.nano_token)) LOGGER.info('Saving token to the Database') self.setDriver('ST', 1) self.discover() except Exception as ex: LOGGER.error('Error starting NanoLeaf NodeServer: %s', str(ex)) self.setDriver('ST', 0) return False