async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry): if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) captcha_config = hass.data[DOMAIN].get(CAPTCHA_CONFIG, CaptchaConfig()) coordinator = hass.data[DOMAIN].get( COORDINATOR, EufySecurityDataUpdateCoordinator(hass, config_entry, captcha_config), ) hass.data[DOMAIN][COORDINATOR] = coordinator hass.data[DOMAIN][CAPTCHA_CONFIG] = captcha_config await coordinator.initialize() await coordinator.async_refresh() for platform in PLATFORMS: coordinator.platforms.append(platform) hass.async_add_job( hass.config_entries.async_forward_entry_setup( config_entry, platform)) async def update(event_time_utc): coordinator.async_set_updated_data(coordinator.data) coordinator.update_listener = async_track_time_interval( hass, update, timedelta(seconds=1)) config_entry.add_update_listener(async_reload_entry) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Setup CryptoTracker from config entry""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) crypto = entry.data.get(CONF_CRYPTO) base = entry.data.get(CONF_BASE) session = async_get_clientsession(hass) client = CryptoTrackerApiClient(crypto=crypto, base=base, session=session) coordinator = CryptoTrackerUpdateCoordinator(hass, client=client) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data[DOMAIN][entry.entry_id] = coordinator if entry.options.get("sensor", True): coordinator.platforms.append("sensor") hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, "sensor")) entry.async_on_unload(entry.add_update_listener(async_reload_entry)) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up this integration using UI.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) postcode = entry.data.get(CONF_POSTCODE) _LOGGER.debug("Postcode setup: %s" % postcode) coordinator = CarbonIntensityDataUpdateCoordinator(hass, postcode=postcode) _LOGGER.debug("Coordinator refresh triggered") await coordinator.async_refresh() _LOGGER.debug("Coordinator refresh completed") if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data[DOMAIN][entry.entry_id] = coordinator for platform in PLATFORMS: if entry.options.get(platform, True): _LOGGER.debug("Found platform %s" % platform) coordinator.platforms.append(platform) hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, platform)) entry.add_update_listener(async_reload_entry) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up this integration using UI.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) username = entry.data.get(CONF_USERNAME) password = entry.data.get(CONF_PASSWORD) session = async_get_clientsession(hass) client = traeger(username, password, session) await client.start() grills = client.get_grills() for grill in grills: grill_id = grill["thingName"] await client.update_state(grill_id) hass.data[DOMAIN][entry.entry_id] = client for platform in PLATFORMS: if entry.options.get(platform, True): hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, platform)) entry.add_update_listener(async_reload_entry) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) username = entry.data.get(CONF_USERNAME) password = entry.data.get(CONF_PASSWORD) enable_binary_sensor = entry.data.get(CONF_ENABLE_BINARY_SENSOR) session = async_get_clientsession(hass) client = YaleDoormanViaSmarthubApiClient(username, password, session) coordinator = YaleDoormanViaSmarthubDataUpdateCoordinator(hass, client=client) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data[DOMAIN][entry.entry_id] = coordinator coordinator.platforms.append(LOCK) hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, LOCK)) if enable_binary_sensor: coordinator.platforms.append(BINARY_SENSOR) hass.async_add_job( hass.config_entries.async_forward_entry_setup( entry, BINARY_SENSOR)) entry.add_update_listener(async_reload_entry) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up this integration using UI.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) scan_period = timedelta( seconds=entry.options.get(CONF_SCAN_PERIOD, DEFAULT_SCAN_PERIOD) ) coct_area = entry.options.get(CONF_AREA, DEFAULT_AREA) coordinator = EskomDataUpdateCoordinator(hass, scan_period, coct_area) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data[DOMAIN][entry.entry_id] = coordinator for platform in PLATFORMS: if entry.options.get(platform, True): coordinator.platforms.append(platform) hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, platform) ) if not entry.update_listeners: entry.add_update_listener(async_reload_entry) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up this integration using UI.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) apiKey = entry.data.get(CONF_API_KEY) latitude = entry.data.get(CONF_LATITUDE) longitude = entry.data.get(CONF_LONGITUDE) session = async_get_clientsession(hass) client = KnmiApiClient(apiKey, latitude, longitude, session) coordinator = KnmiDataUpdateCoordinator(hass, client=client) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data[DOMAIN][entry.entry_id] = coordinator for platform in PLATFORMS: if entry.options.get(platform, True): coordinator.platforms.append(platform) hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, platform)) entry.add_update_listener(async_reload_entry) return True
async def async_setup_entry( hass: HomeAssistant, entry: config_entries.ConfigEntry ) -> bool: """Set up tide as config entry.""" hass.async_add_job(hass.config_entries.async_forward_entry_setup(entry, "sensor")) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up this integration using UI.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) username = entry.data.get(CONF_USERNAME) password = entry.data.get(CONF_PASSWORD) session = async_get_clientsession(hass) client = CcHaCciApiClient(username, password, session) coordinator = CcHaCciDataUpdateCoordinator(hass, client=client) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data[DOMAIN][entry.entry_id] = coordinator for platform in PLATFORMS: if entry.options.get(platform, True): coordinator.platforms.append(platform) hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, platform)) entry.add_update_listener(async_reload_entry) return True
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Set up MFP as config entry.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) username = config_entry.data.get(CONF_USERNAME) password = config_entry.data.get(CONF_PASSWORD) display_name = config_entry.data.get(CONF_NAME) coordinator = MyFitnessPalDataUpdateCoordinator( hass, username=username, password=password, display_name=display_name ) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data[DOMAIN][config_entry.entry_id] = coordinator for platform in PLATFORMS: if config_entry.options.get(platform, True): coordinator.platforms.append(platform) hass.async_add_job( hass.config_entries.async_forward_entry_setup(config_entry, platform) ) config_entry.add_update_listener(async_reload_entry) return True
def async_from_config_file(config_path: str, hass: core.HomeAssistant, verbose: bool=False, skip_pip: bool=True, log_rotate_days: Any=None): """Read the configuration file and try to start all the functionality. Will add functionality to 'hass' parameter. This method is a coroutine. """ # Set config dir to directory holding config file config_dir = os.path.abspath(os.path.dirname(config_path)) hass.config.config_dir = config_dir yield from hass.async_add_job(mount_local_lib_path, config_dir) async_enable_logging(hass, verbose, log_rotate_days) try: config_dict = yield from hass.async_add_job( conf_util.load_yaml_config_file, config_path) except HomeAssistantError as err: _LOGGER.error('Error loading %s: %s', config_path, err) return None finally: clear_secret_cache() hass = yield from async_from_config_dict( config_dict, hass, enable_log=False, skip_pip=skip_pip) return hass
def async_see( hass: HomeAssistant, mac: str = None, dev_id: str = None, host_name: str = None, location_name: str = None, gps: GPSType = None, gps_accuracy=None, battery: int = None, attributes: dict = None, ): """Call service to notify you see device.""" data = { key: value for key, value in ( (ATTR_MAC, mac), (ATTR_DEV_ID, dev_id), (ATTR_HOST_NAME, host_name), (ATTR_LOCATION_NAME, location_name), (ATTR_GPS, gps), (ATTR_GPS_ACCURACY, gps_accuracy), (ATTR_BATTERY, battery), ) if value is not None } if attributes: data[ATTR_ATTRIBUTES] = attributes hass.async_add_job(hass.services.async_call(DOMAIN, SERVICE_SEE, data))
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up this integration using UI.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) spa_identifier = entry.data.get(CONF_SPA_IDENTIFIER) _LOGGER.info("Setup entry for %s", spa_identifier) with GeckoLocator(GECKOLIB_MANAGER_UUID, spa_to_find=spa_identifier) as locator: _LOGGER.info("Locator %s ready", locator) try: facade = locator.get_spa_from_identifier( spa_identifier).get_facade(False) _LOGGER.info("Waiting for facade to be ready") while not facade.is_connected: await asyncio.sleep(0.1) _LOGGER.info("Facade is ready") datablock = GeckoDataBlock(facade, entry) hass.data[DOMAIN][entry.entry_id] = datablock except Exception: _LOGGER.exception("Exception during entry setup") return False for platform in datablock.platforms: hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, platform)) entry.add_update_listener(async_reload_entry) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up this integration using UI.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) hub_hash = entry.data.get(CONF_HUB_HASH) session = async_get_clientsession(hass) client = RitualsGenieApiClient(hub_hash, session) coordinator = RitualsGenieDataUpdateCoordinator(hass, client=client) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data[DOMAIN][entry.entry_id] = coordinator if entry.options.get(CONF_SWITCH_ENABLED, True): coordinator.platforms.append(SWITCH) hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, SWITCH)) if (entry.options.get(CONF_FILL_SENSOR_ENABLED, True) or entry.options.get(CONF_PERFUME_SENSOR_ENABLED, True) or entry.options.get(CONF_WIFI_SENSOR_ENABLED, True)): coordinator.platforms.append(SENSOR) hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, SENSOR)) entry.add_update_listener(async_reload_entry) return True
async def async_setup(hass: HomeAssistant, base_config: dict): """Set up the visonic component.""" # initially empty the settings for this component hass.data[DOMAIN] = {} hass.data[DOMAIN][DOMAINDATA] = {} hass.data[DOMAIN][DOMAINCLIENT] = {} # if there are no configuration.yaml settings then terminate if DOMAIN not in base_config: return True # has there been a flow configured panel connection before configured = configured_hosts(hass) # if there is not a flow configured connection previously # then create a flow connection from the configuration.yaml data if len(configured) == 0: # get the configuration.yaml settings and make a 'flow' task :) # this will run 'async_step_import' in config_flow.py conf = base_config.get(DOMAIN) log.info(" Adding job") hass.async_add_job( hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=conf)) return True
def async_from_config_file(config_path: str, hass: core.HomeAssistant, verbose: bool = False, skip_pip: bool = True, log_rotate_days: Any = None): """Read the configuration file and try to start all the functionality. Will add functionality to 'hass' parameter. This method is a coroutine. """ # Set config dir to directory holding config file config_dir = os.path.abspath(os.path.dirname(config_path)) hass.config.config_dir = config_dir yield from hass.async_add_job(mount_local_lib_path, config_dir) async_enable_logging(hass, verbose, log_rotate_days) try: config_dict = yield from hass.async_add_job( conf_util.load_yaml_config_file, config_path) except HomeAssistantError as err: _LOGGER.error('Error loading %s: %s', config_path, err) return None finally: clear_secret_cache() hass = yield from async_from_config_dict(config_dict, hass, enable_log=False, skip_pip=skip_pip) return hass
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up this integration using UI.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) channel_id = entry.data.get(CONF_TV_CHANNEL_ID) channel_name = entry.data.get(CONF_TV_CHANNEL_NAME) coordinator = PortHuTvDataUpdateCoordinator(hass, channel_id=channel_id, channel_name=channel_name) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data[DOMAIN][entry.entry_id] = coordinator for platform in PLATFORMS: if entry.options.get(platform, True): coordinator.platforms.append(platform) hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, platform)) entry.add_update_listener(async_reload_entry) return True
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry): """Set up this integration using UI.""" hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) coordinator = GrocyDataUpdateCoordinator( hass, config_entry.data[CONF_URL], config_entry.data[CONF_API_KEY], config_entry.data[CONF_PORT], config_entry.data[CONF_VERIFY_SSL], ) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data[DOMAIN] = coordinator for platform in PLATFORMS: hass.async_add_job( hass.config_entries.async_forward_entry_setup(config_entry, platform) ) await async_setup_services(hass, config_entry) # Setup http endpoint for proxying images from grocy await async_setup_image_api(hass, config_entry.data) config_entry.add_update_listener(async_reload_entry) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up Easee integration from a config entry.""" if DOMAIN not in hass.data: hass.data[DOMAIN] = {} _LOGGER.debug("Setting up Easee component version %s", VERSION) username = entry.data.get(CONF_USERNAME) password = entry.data.get(CONF_PASSWORD) client_session = aiohttp_client.async_get_clientsession(hass) easee = Easee(username, password, client_session) sites: List[Site] = await easee.get_sites() hass.data[DOMAIN]["session"] = easee hass.data[DOMAIN]["config"] = entry hass.data[DOMAIN]["sites"] = sites hass.data[DOMAIN]["circuits"] = [] hass.data[DOMAIN]["chargers"] = [] entities = [] charger_data_list = [] all_sites = [] for site in sites: all_sites.append(site["name"]) config = hass.data[DOMAIN]["config"] monitored_sites = config.options.get(CONF_MONITORED_SITES, all_sites) for site in sites: if not site["name"] in monitored_sites: _LOGGER.debug("Found site (unmonitored): %s %s", site.id, site["name"]) else: _LOGGER.debug("Found site (monitored): %s %s", site.id, site["name"]) for circuit in site.get_circuits(): _LOGGER.debug("Found circuit: %s %s", circuit.id, circuit["panelName"]) hass.data[DOMAIN]["circuits"].append(circuit) for charger in circuit.get_chargers(): _LOGGER.debug("Found charger: %s %s", charger.id, charger.name) hass.data[DOMAIN]["chargers"].append(charger) charger_data = ChargerData(charger, circuit, site) charger_data_list.append(charger_data) chargers_data = ChargersData(charger_data_list, entities) hass.data[DOMAIN]["chargers_data"] = chargers_data # Setup services await async_setup_services(hass) for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component)) hass.async_add_job(chargers_data.async_refresh) async_track_time_interval(hass, chargers_data.async_refresh, SCAN_INTERVAL) # handle unsub later unsub = entry.add_update_listener(config_entry_update_listener) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up this integration using UI.""" # str_mydict = ''.join('{}{}'.format(key, val) for key, val in entry.data.items()) # logging.warning('ENTRY: %s', str_mydict) if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) thehost = entry.data.get(CONF_HOST) theport = entry.data.get(CONF_PORT) theversion = entry.data.get("version") thestart = entry.data.get(CONF_START) thestop = entry.data.get(CONF_STOP) thescan = entry.data.get(CONF_SCAN_INTERVAL) thesubdevices = entry.data.get(CONF_SHOW_SUBDEVICES) theblade_light = entry.data.get(CONF_SHOW_BLADELIGHT) thestart_method = entry.data.get(CONF_START_METHOD) thestart_body = entry.data.get(CONF_START_BODY) thestop_method = entry.data.get(CONF_STOP_METHOD) thestop_body = entry.data.get(CONF_STOP_BODY) coordinator = LedfxrmDataUpdateCoordinator( hass, thehost, theport, theversion, thestart, thestop, thescan, thesubdevices, theblade_light, thestart_method, thestart_body, thestop_method, thestop_body, ) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data[DOMAIN][entry.entry_id] = coordinator for platform in PLATFORMS: if entry.options.get(platform, True): if platform is SWITCH: if thestart is None: continue coordinator.platforms.append(platform) hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, platform)) entry.add_update_listener(async_reload_entry) return True
def websocket_handle_devices(hass: ha_core.HomeAssistant, connection, msg): @async_wrap def get_devices(): """Handle to get devices. Only for default account""" account = msg.get("account", None) client = spotcast_controller.get_spotify_client(account) me_resp = client._get("me") resp = get_spotify_devices(hass, me_resp["id"]) connection.send_message(websocket_api.result_message(msg["id"], resp)) hass.async_add_job(get_devices())
def websocket_handle_player(hass: ha_core.HomeAssistant, connection, msg): @async_wrap def get_player(): """Handle to get player""" account = msg.get("account", None) _LOGGER.debug("websocket_handle_player msg: %s", msg) client = spotcast_controller.get_spotify_client(account) resp = client._get("me/player") connection.send_message(websocket_api.result_message(msg["id"], resp)) hass.async_add_job(get_player())
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up this integration using UI.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) name = entry.data.get(CONF_NAME) name_no_spaces_but_underscores = name.replace(" ", "_") input_sensor = entry.data.get(CONF_INPUT_SENSOR) operation = entry.data.get(CONF_OPERATION) interval = entry.data.get(CONF_INTERVAL) unit_of_measurement = entry.data.get(CONF_UNIT_OF_MEASUREMENT) auto_reset = entry.data.get(CONF_AUTO_RESET, DEFAULT_AUTO_RESET) # set up coordinator coordinator = DailySensorUpdateCoordinator( hass, name=name, input_sensor=input_sensor, operation=operation, interval=interval, unit_of_measurement=unit_of_measurement, auto_reset=auto_reset, ) await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data[DOMAIN][entry.entry_id] = coordinator for platform in PLATFORMS: coordinator.platforms.append(platform) hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, platform)) # add update listener if not already added. if weakref.ref(async_reload_entry) not in entry.update_listeners: entry.add_update_listener(async_reload_entry) # register services hass.services.async_register( DOMAIN, f"{name_no_spaces_but_underscores}_{SERVICE_RESET}", coordinator.handle_reset, ) hass.services.async_register( DOMAIN, f"{name_no_spaces_but_underscores}_{SERVICE_UPDATE}", coordinator.handle_update, ) return True
async def async_setup_entry(hass: HomeAssistant, config: ConfigEntry): latitude = config.data.get(CONF_LATITUDE) if config.data.get( CONF_LATITUDE) is not None else hass.config.latitude longitude = config.data.get(CONF_LONGITUDE) if config.data.get( CONF_LONGITUDE) is not None else hass.config.longitude radius = config.data.get(CONF_RADIUS) if config.data.get( CONF_RADIUS) is not None else 50 county = config.data.get(CONF_COUNTY) if config.data.get( CONF_COUNTY) is not None else None country = config.data.get(CONF_COUNTRY) if config.data.get( CONF_COUNTRY) is not None else None if not "api" in hass.data[INTEGRATION_DOMAIN]: hass.data[INTEGRATION_DOMAIN]['api'] = KrisinformationAPI( hass, longitude, latitude, county, radius, country) try: device_registry = await dr.async_get_registry(hass) device_registry.async_get_or_create(config_entry_id=config.entry_id, identifiers={(INTEGRATION_DOMAIN, DEVICE_GUID)}, name=DEVICE_NAME, model=DEVICE_MODEL, sw_version=INTEGRATION_VERSION, manufacturer=DEVICE_MANUFACTURER, entry_type=DEVICE_TYPE) except Exception as e: logger.error("Failed to create device") return False try: hass.async_add_job( hass.config_entries.async_forward_entry_setup(config, "sensor")) hass.async_add_job( hass.config_entries.async_forward_entry_setup( config, "binary_sensor")) logger.debug("Forward entry setup succeeded") except Exception as e: logger.error("Forward entry setup failed") return False try: hass.data[INTEGRATION_DOMAIN]['updater'] = config.add_update_listener( reload_entry) except Exception as e: logger.error("Update listener setup failed") return False return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up this integration using UI.""" if entry.source == SOURCE_IMPORT: config = hass.data[DOMAIN][CONF_YAML] else: config = entry.data.copy() config.update(entry.options) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) active_devices = config.get(CONF_DEVICES, []) receive_tvoc_in_ppb = config.get(CONF_RECEIVE_TVOC_IN_PPB) receive_hcho_in_ppb = config.get(CONF_RECEIVE_HCHO_IN_PPB) _LOGGER.debug("Connecting to account %s", mask_email(username)) session = async_get_clientsession(hass) account = Jq300Account( hass, session, username, password, receive_tvoc_in_ppb, receive_hcho_in_ppb ) try: with async_timeout.timeout(UPDATE_TIMEOUT): devices = await hass.async_add_executor_job(account.update_devices) except TimeoutError as exc: raise ConfigEntryNotReady from exc devs = {} for device_id in devices: name = devices[device_id]["pt_name"] if active_devices and name not in active_devices: continue account.active_devices.append(device_id) devs[name] = device_id hass.data[DOMAIN][entry.entry_id] = { CONF_ACCOUNT_CONTROLLER: account, CONF_DEVICES: devs, } # Load platforms for platform in PLATFORMS: hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, platform) ) entry.add_update_listener(async_reload_entry) return True
async def async_setup(hass: HomeAssistant, config): """Set up integration.""" async def service_cleanup_entries(service_call): service_data = service_call.data await async_cleanup_entries_service(hass, service_data) async def service_parse_data(service_call): service_data = service_call.data await async_parse_data_service(hass, service_data) hass.services.async_register( DOMAIN, SERVICE_CLEANUP_ENTRIES, service_cleanup_entries, schema=SERVICE_CLEANUP_ENTRIES_SCHEMA, ) hass.services.async_register( DOMAIN, SERVICE_PARSE_DATA, service_parse_data, schema=SERVICE_PARSE_DATA_SCHEMA, ) if DOMAIN not in config: return True if DOMAIN in hass.data: # One instance only return False # Save and set default for the YAML config global CONFIG_YAML CONFIG_YAML = json.loads(json.dumps(config[DOMAIN])) CONFIG_YAML[CONFIG_IS_FLOW] = False CONFIG_YAML["ids_from_name"] = True _LOGGER.debug("Initializing BLE Monitor integration (YAML): %s", CONFIG_YAML) hass.async_add_job( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=copy.deepcopy(CONFIG_YAML) ) ) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up HASL entries""" logger.debug(f"[setup_entry] Entering for {entry.entry_id}") try: device_registry = await dr.async_get_registry(hass) device_registry.async_get_or_create(config_entry_id=entry.entry_id, identifiers={(DOMAIN, DEVICE_GUID) }, name=DEVICE_NAME, model=DEVICE_MODEL, sw_version=HASL_VERSION, manufacturer=DEVICE_MANUFACTURER, entry_type=DEVICE_TYPE) logger.debug("[setup_entry] Created device") except Exception as e: logger.error("[setup_entry] Failed to create device") return False try: hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, "sensor")) hass.async_add_job( hass.config_entries.async_forward_entry_setup( entry, "binary_sensor")) logger.debug("[setup_entry] Forward entry setup succeeded") except Exception as e: logger.error("[setup_entry] Forward entry setup failed") return False updater = None try: updater = entry.add_update_listener(reload_entry) except Exception as e: logger.error("[setup_entry] Update listener setup failed") return False try: hass.data[DOMAIN]["worker"].instances.add(entry.entry_id, updater) logger.debug("[setup_entry] Worker registration succeeded") except Exception as e: logger.error(f"[setup_entry] Worker registration failed: {str(e)}") return False logger.debug("[setup_entry] Completed") return True
def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the recorder.""" conf = config.get(DOMAIN, {}) keep_days = conf.get(CONF_PURGE_KEEP_DAYS) purge_interval = conf.get(CONF_PURGE_INTERVAL) db_url = conf.get(CONF_DB_URL, None) if not db_url: db_url = DEFAULT_URL.format( hass_config_path=hass.config.path(DEFAULT_DB_FILE)) include = conf.get(CONF_INCLUDE, {}) exclude = conf.get(CONF_EXCLUDE, {}) instance = hass.data[DATA_INSTANCE] = Recorder( hass=hass, keep_days=keep_days, purge_interval=purge_interval, uri=db_url, include=include, exclude=exclude) instance.async_initialize() instance.start() @asyncio.coroutine def async_handle_purge_service(service): """Handle calls to the purge service.""" instance.do_adhoc_purge(service.data[ATTR_KEEP_DAYS]) descriptions = yield from hass.async_add_job( conf_util.load_yaml_config_file, path.join( path.dirname(__file__), 'services.yaml')) hass.services.async_register(DOMAIN, SERVICE_PURGE, async_handle_purge_service, descriptions.get(SERVICE_PURGE), schema=SERVICE_PURGE_SCHEMA) return (yield from instance.async_db_ready)
def _async_process_requirements(hass: core.HomeAssistant, name: str, requirements) -> bool: """Install the requirements for a component. This method is a coroutine. """ if hass.config.skip_pip: return True pip_lock = hass.data.get(DATA_PIP_LOCK) if pip_lock is None: pip_lock = hass.data[DATA_PIP_LOCK] = asyncio.Lock(loop=hass.loop) def pip_install(mod): """Install packages.""" return pkg_util.install_package(mod, target=hass.config.path('deps'), constraints=os.path.join( os.path.dirname(__file__), CONSTRAINT_FILE)) with (yield from pip_lock): for req in requirements: ret = yield from hass.async_add_job(pip_install, req) if not ret: _LOGGER.error( "Not initializing %s because could not install " "dependency %s", name, req) async_notify_setup_error(hass, name) return False return True
async def async_setup_component(hass: core.HomeAssistant, domain: str, config: Optional[Dict] = None) -> bool: """Set up a component and all its dependencies. This method is a coroutine. """ if domain in hass.config.components: return True setup_tasks = hass.data.get(DATA_SETUP) if setup_tasks is not None and domain in setup_tasks: return await setup_tasks[domain] if config is None: config = {} if setup_tasks is None: setup_tasks = hass.data[DATA_SETUP] = {} task = setup_tasks[domain] = hass.async_add_job( _async_setup_component(hass, domain, config)) return await task
def _async_process_requirements(hass: core.HomeAssistant, name: str, requirements) -> bool: """Install the requirements for a component. This method is a coroutine. """ if hass.config.skip_pip: return True pip_lock = hass.data.get(DATA_PIP_LOCK) if pip_lock is None: pip_lock = hass.data[DATA_PIP_LOCK] = asyncio.Lock(loop=hass.loop) def pip_install(mod): """Install packages.""" if pkg_util.running_under_virtualenv(): return pkg_util.install_package( mod, constraints=os.path.join( os.path.dirname(__file__), CONSTRAINT_FILE)) return pkg_util.install_package( mod, target=hass.config.path('deps'), constraints=os.path.join( os.path.dirname(__file__), CONSTRAINT_FILE)) with (yield from pip_lock): for req in requirements: ret = yield from hass.async_add_job(pip_install, req) if not ret: _LOGGER.error("Not initializing %s because could not install " "dependency %s", name, req) async_notify_setup_error(hass, name) return False return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): _LOGGER.info('async_setup_entry():' + str(entry.entry_id)) if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) username = entry.data.get(CONF_USERNAME) password = entry.data.get(CONF_PASSWORD) default_temperature = int(entry.options.get(CONF_DEFAULT_TEMPERATURE, 21)) coordinator = RikaFirenetCoordinator(hass, username, password, default_temperature) try: await hass.async_add_executor_job(coordinator.setup) except KeyError: _LOGGER.error("Failed to login to firenet") return False except RuntimeError as exc: _LOGGER.error("Failed to setup rika firenet: %s", exc) return ConfigEntryNotReady except requests.exceptions.Timeout as ex: raise ConfigEntryNotReady from ex except requests.exceptions.HTTPError as ex: if ex.response.status_code > 400 and ex.response.status_code < 500: _LOGGER.error("Failed to login to rika firenet: %s", ex) return False raise ConfigEntryNotReady from ex await coordinator.async_refresh() if not coordinator.last_update_success: raise ConfigEntryNotReady hass.data[DOMAIN][entry.entry_id] = coordinator for platform in PLATFORMS: if entry.options.get(platform, True): coordinator.platforms.append(platform) hass.async_add_job( hass.config_entries.async_forward_entry_setup(entry, platform)) entry.add_update_listener(async_reload_entry) return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up this integration using UI.""" if hass.data.get(DOMAIN) is None: hass.data.setdefault(DOMAIN, {}) _LOGGER.info(STARTUP_MESSAGE) uuid = get_uuid(hass) if entry.source == "import": if YAML_DOMAIN not in hass.data: # pragma: no cover await hass.config_entries.async_remove(entry.entry_id) raise ConfigEntryNotReady config = hass.data[YAML_DOMAIN] apikey = config.get(CONF_APIKEY) verify_ssl = config.get(CONF_VERIFY_SSL) timeout = config.get(CONF_TIMEOUT) session = async_get_clientsession(hass, verify_ssl=verify_ssl) client = NarodmonApiClient(session, uuid, apikey, timeout) for index, device_config in enumerate(config.get(CONF_DEVICES)): latitude = device_config.get(CONF_LATITUDE, hass.config.latitude) longitude = device_config.get(CONF_LONGITUDE, hass.config.longitude) types = device_config.get(CONF_SENSORS, SENSOR_TYPES.keys()) scan_interval = device_config.get(CONF_SCAN_INTERVAL) coordinator = NarodmonDataUpdateCoordinator( hass, client, scan_interval, latitude, longitude, types ) await coordinator.async_refresh() if not coordinator.last_update_success: # pragma: no cover raise ConfigEntryNotReady hass.data[DOMAIN].setdefault(entry.entry_id, {}) hass.data[DOMAIN][entry.entry_id][index] = coordinator hass.async_add_job(hass.config_entries.async_forward_entry_setup(entry, SENSOR)) else: config = entry.data.copy() entry.add_update_listener(async_reload_entry) return True
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the HomematicIP Cloud component.""" hass.data[DOMAIN] = {} accesspoints = config.get(DOMAIN, []) for conf in accesspoints: if conf[CONF_ACCESSPOINT] not in configured_haps(hass): hass.async_add_job(hass.config_entries.flow.async_init( DOMAIN, context={'source': config_entries.SOURCE_IMPORT}, data={ HMIPC_HAPID: conf[CONF_ACCESSPOINT], HMIPC_AUTHTOKEN: conf[CONF_AUTHTOKEN], HMIPC_NAME: conf[CONF_NAME], } )) return True
def async_setup(hass: HomeAssistant, yaml_config: Dict[str, Any]): """Activate Google Actions component.""" config = yaml_config.get(DOMAIN, {}) agent_user_id = config.get(CONF_AGENT_USER_ID) api_key = config.get(CONF_API_KEY) if api_key is not None: descriptions = yield from hass.async_add_job( conf_util.load_yaml_config_file, os.path.join( os.path.dirname(__file__), 'services.yaml') ) hass.http.register_view(GoogleAssistantAuthView(hass, config)) hass.http.register_view(GoogleAssistantView(hass, config)) @asyncio.coroutine def request_sync_service_handler(call): """Handle request sync service calls.""" websession = async_get_clientsession(hass) try: with async_timeout.timeout(5, loop=hass.loop): res = yield from websession.post( REQUEST_SYNC_BASE_URL, params={'key': api_key}, json={'agent_user_id': agent_user_id}) _LOGGER.info("Submitted request_sync request to Google") res.raise_for_status() except aiohttp.ClientResponseError: body = yield from res.read() _LOGGER.error( 'request_sync request failed: %d %s', res.status, body) except (asyncio.TimeoutError, aiohttp.ClientError): _LOGGER.error("Could not contact Google for request_sync") # Register service only if api key is provided if api_key is not None: hass.services.async_register( DOMAIN, SERVICE_REQUEST_SYNC, request_sync_service_handler, descriptions.get(SERVICE_REQUEST_SYNC)) return True
def async_setup_component(hass: core.HomeAssistant, domain: str, config: Optional[Dict] = None) -> bool: """Set up a component and all its dependencies. This method is a coroutine. """ if domain in hass.config.components: return True setup_tasks = hass.data.get(DATA_SETUP) if setup_tasks is not None and domain in setup_tasks: return (yield from setup_tasks[domain]) if config is None: config = {} if setup_tasks is None: setup_tasks = hass.data[DATA_SETUP] = {} task = setup_tasks[domain] = hass.async_add_job( _async_setup_component(hass, domain, config)) return (yield from task)
def async_from_config_dict(config: Dict[str, Any], hass: core.HomeAssistant, config_dir: Optional[str]=None, enable_log: bool=True, verbose: bool=False, skip_pip: bool=False, log_rotate_days: Any=None) \ -> Optional[core.HomeAssistant]: """Try to configure Home Assistant from a config dict. Dynamically loads required components and its dependencies. This method is a coroutine. """ start = time() hass.async_track_tasks() core_config = config.get(core.DOMAIN, {}) try: yield from conf_util.async_process_ha_core_config(hass, core_config) except vol.Invalid as ex: conf_util.async_log_exception(ex, 'homeassistant', core_config, hass) return None yield from hass.loop.run_in_executor( None, conf_util.process_ha_config_upgrade, hass) if enable_log: async_enable_logging(hass, verbose, log_rotate_days) hass.config.skip_pip = skip_pip if skip_pip: _LOGGER.warning('Skipping pip installation of required modules. ' 'This may cause issues.') if not loader.PREPARED: yield from hass.loop.run_in_executor(None, loader.prepare, hass) # Merge packages conf_util.merge_packages_config( config, core_config.get(conf_util.CONF_PACKAGES, {})) # Make a copy because we are mutating it. # Use OrderedDict in case original one was one. # Convert values to dictionaries if they are None new_config = OrderedDict() for key, value in config.items(): new_config[key] = value or {} config = new_config # Filter out the repeating and common config section [homeassistant] components = set(key.split(' ')[0] for key in config.keys() if key != core.DOMAIN) # setup components # pylint: disable=not-an-iterable res = yield from core_components.async_setup(hass, config) if not res: _LOGGER.error('Home Assistant core failed to initialize. ' 'Further initialization aborted.') return hass yield from persistent_notification.async_setup(hass, config) _LOGGER.info('Home Assistant core initialized') # stage 1 for component in components: if component not in FIRST_INIT_COMPONENT: continue hass.async_add_job(async_setup_component(hass, component, config)) yield from hass.async_block_till_done() # stage 2 for component in components: if component in FIRST_INIT_COMPONENT: continue hass.async_add_job(async_setup_component(hass, component, config)) yield from hass.async_stop_track_tasks() stop = time() _LOGGER.info('Home Assistant initialized in %ss', round(stop-start, 2)) async_register_signal_handling(hass) return hass
def async_from_config_dict(config: Dict[str, Any], hass: core.HomeAssistant, config_dir: Optional[str]=None, enable_log: bool=True, verbose: bool=False, skip_pip: bool=False, log_rotate_days: Any=None, log_file: Any=None) \ -> Optional[core.HomeAssistant]: """Try to configure Home Assistant from a configuration dictionary. Dynamically loads required components and its dependencies. This method is a coroutine. """ start = time() if enable_log: async_enable_logging(hass, verbose, log_rotate_days, log_file) if sys.version_info[:2] < (3, 5): _LOGGER.warning( 'Python 3.4 support has been deprecated and will be removed in ' 'the beginning of 2018. Please upgrade Python or your operating ' 'system. More info: https://home-assistant.io/blog/2017/10/06/' 'deprecating-python-3.4-support/' ) core_config = config.get(core.DOMAIN, {}) try: yield from conf_util.async_process_ha_core_config(hass, core_config) except vol.Invalid as ex: conf_util.async_log_exception(ex, 'homeassistant', core_config, hass) return None yield from hass.async_add_job(conf_util.process_ha_config_upgrade, hass) hass.config.skip_pip = skip_pip if skip_pip: _LOGGER.warning("Skipping pip installation of required modules. " "This may cause issues") if not loader.PREPARED: yield from hass.async_add_job(loader.prepare, hass) # Merge packages conf_util.merge_packages_config( config, core_config.get(conf_util.CONF_PACKAGES, {})) # Make a copy because we are mutating it. # Use OrderedDict in case original one was one. # Convert values to dictionaries if they are None new_config = OrderedDict() for key, value in config.items(): new_config[key] = value or {} config = new_config # Filter out the repeating and common config section [homeassistant] components = set(key.split(' ')[0] for key in config.keys() if key != core.DOMAIN) # setup components # pylint: disable=not-an-iterable res = yield from core_components.async_setup(hass, config) if not res: _LOGGER.error("Home Assistant core failed to initialize. " "further initialization aborted") return hass yield from persistent_notification.async_setup(hass, config) _LOGGER.info("Home Assistant core initialized") # stage 1 for component in components: if component not in FIRST_INIT_COMPONENT: continue hass.async_add_job(async_setup_component(hass, component, config)) yield from hass.async_block_till_done() # stage 2 for component in components: if component in FIRST_INIT_COMPONENT: continue hass.async_add_job(async_setup_component(hass, component, config)) yield from hass.async_block_till_done() stop = time() _LOGGER.info("Home Assistant initialized in %.2fs", stop-start) async_register_signal_handling(hass) return hass
def async_from_config_dict(config: Dict[str, Any], hass: core.HomeAssistant, config_dir: Optional[str] = None, enable_log: bool = True, verbose: bool = False, skip_pip: bool = False, log_rotate_days: Any = None, log_file: Any = None) \ -> Optional[core.HomeAssistant]: """Try to configure Home Assistant from a configuration dictionary. Dynamically loads required components and its dependencies. This method is a coroutine. """ start = time() if enable_log: async_enable_logging(hass, verbose, log_rotate_days, log_file) core_config = config.get(core.DOMAIN, {}) try: yield from conf_util.async_process_ha_core_config(hass, core_config) except vol.Invalid as ex: conf_util.async_log_exception(ex, 'homeassistant', core_config, hass) return None yield from hass.async_add_job(conf_util.process_ha_config_upgrade, hass) hass.config.skip_pip = skip_pip if skip_pip: _LOGGER.warning("Skipping pip installation of required modules. " "This may cause issues") if not loader.PREPARED: yield from hass.async_add_job(loader.prepare, hass) # Make a copy because we are mutating it. config = OrderedDict(config) # Merge packages conf_util.merge_packages_config( config, core_config.get(conf_util.CONF_PACKAGES, {})) # Ensure we have no None values after merge for key, value in config.items(): if not value: config[key] = {} hass.config_entries = config_entries.ConfigEntries(hass, config) yield from hass.config_entries.async_load() # Filter out the repeating and common config section [homeassistant] components = set(key.split(' ')[0] for key in config.keys() if key != core.DOMAIN) components.update(hass.config_entries.async_domains()) # setup components # pylint: disable=not-an-iterable res = yield from core_components.async_setup(hass, config) if not res: _LOGGER.error("Home Assistant core failed to initialize. " "further initialization aborted") return hass yield from persistent_notification.async_setup(hass, config) _LOGGER.info("Home Assistant core initialized") # stage 1 for component in components: if component not in FIRST_INIT_COMPONENT: continue hass.async_add_job(async_setup_component(hass, component, config)) yield from hass.async_block_till_done() # stage 2 for component in components: if component in FIRST_INIT_COMPONENT: continue hass.async_add_job(async_setup_component(hass, component, config)) yield from hass.async_block_till_done() stop = time() _LOGGER.info("Home Assistant initialized in %.2fs", stop-start) async_register_signal_handling(hass) return hass
def async_dismiss(hass: HomeAssistant, notification_id: str) -> None: """Remove a notification.""" data = {ATTR_NOTIFICATION_ID: notification_id} hass.async_add_job(hass.services.async_call(DOMAIN, SERVICE_DISMISS, data))
def _async_setup_component(hass: core.HomeAssistant, domain: str, config) -> bool: """Set up a component for Home Assistant. This method is a coroutine. """ def log_error(msg, link=True): """Log helper.""" _LOGGER.error("Setup failed for %s: %s", domain, msg) async_notify_setup_error(hass, domain, link) component = loader.get_component(domain) if not component: log_error("Component not found.", False) return False # Validate no circular dependencies components = loader.load_order_component(domain) # OrderedSet is empty if component or dependencies could not be resolved if not components: log_error("Unable to resolve component or dependencies.") return False processed_config = \ conf_util.async_process_component_config(hass, config, domain) if processed_config is None: log_error("Invalid config.") return False try: yield from async_process_deps_reqs(hass, config, domain, component) except HomeAssistantError as err: log_error(str(err)) return False start = timer() _LOGGER.info("Setting up %s", domain) if hasattr(component, 'PLATFORM_SCHEMA'): # Entity components have their own warning warn_task = None else: warn_task = hass.loop.call_later( SLOW_SETUP_WARNING, _LOGGER.warning, "Setup of %s is taking over %s seconds.", domain, SLOW_SETUP_WARNING) try: if hasattr(component, 'async_setup'): result = yield from component.async_setup(hass, processed_config) else: result = yield from hass.async_add_job( component.setup, hass, processed_config) except Exception: # pylint: disable=broad-except _LOGGER.exception("Error during setup of component %s", domain) async_notify_setup_error(hass, domain, True) return False finally: end = timer() if warn_task: warn_task.cancel() _LOGGER.info("Setup of domain %s took %.1f seconds.", domain, end - start) if result is False: log_error("Component failed to initialize.") return False elif result is not True: log_error("Component did not return boolean if setup was successful. " "Disabling component.") loader.set_component(domain, None) return False for entry in hass.config_entries.async_entries(domain): yield from entry.async_setup(hass, component=component) hass.config.components.add(component.DOMAIN) # Cleanup if domain in hass.data[DATA_SETUP]: hass.data[DATA_SETUP].pop(domain) hass.bus.async_fire( EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: component.DOMAIN} ) return True