mirror of
https://github.com/home-assistant/core.git
synced 2025-05-20 05:49:15 +00:00

* Backend support for importing waypoints from owntracks as HA zones * Added test for Owntracks waypoints import * Backend support for importing waypoints from owntracks as HA zones * Added test for Owntracks waypoints import * Removed redundant assignment to CONF_WAYPOINT_IMPORT_USER * Fixed zone test break and code style issues * Fixed style issues * Fixed variable scope issues for entities * Fixed E302 * Do not install pip packages in tests * EventBus: return function to unlisten * Convert automation to entities with services * Refactored zone creation based on code review feedback, enhanced configuration * Added unit test to enhance waypoint_whitelist coverage * Fix JSON encoder issue in recorder * Fix tests docstring * * Improved zone naming in waypoint import * Added more test coverage for owntracks and zone * Back to 0.28.0.dev0 * Code review feedback from @pavoni * Added bitfield of features for flux_led since we are supporting effects * Host should be optional for apcupsd component (#3072) * Use voluptuous for file (#3049) * Zwave climate Bugfix: if some setpoints have different units, we should fetch the o… (#3078) * Bugfix: if some setpoints have different units, we should fetch the one that are active. * Move order of population for first time detection * Default to config if None unit_of_measurement * unit fix (#3083) * humidity slider (#3088) * If device was off target temp was null. Default to Heating setpoint (#3091) * Fix linting * Upgrade pyuserinput to 0.1.11 (#3068) * Upgrade pyowm to 2.4.0 (#3067) * improve isfile validation check (#3101) * Refactor notification titles to allow for them to be None, this also includes a change in Telegram to only include the title if it's present, and to use a Markdown parse mode for messages (#3100) * Fix broken test * rfxtrx sensor clean up * Bitcoin sensor use warning instead of error (#3103) * Use voluptuous for HDMI CEC & CONF_DEVICES constants (#3107) * Update voluptuous for nest (#3109) * Update configuration check * Extend platform * Fix for BLE device tracker (#3019) * Bug fix tracked devices * Added scan_duration configuration parameter * fix homematic climate implementation (#3114) * Allow 'None' MAC to be loaded from known_devices (#3102) * Use voluptuous for xmpp (#3127) * Use voluptuous for twitter (#3126) * Use voluptuous for Fritzbox and DDWRT (#3122) * Use Voluptuous for BT Home Hub (#3121) * Use voluptuous for syslog (#3120) * Use voluptuous for Aruba (#3119) * Use constants, update configuration check, and ordering (Pilight) (#3118) * Use contants, update configuration check, and ordering * Fix pylint issue * Migrate to voluptuous (#3113) * Fix typo (#3108) * Migrate to voluptuous (#3106) * Update voluptuous (#3104) * Climate and cover bugfix (#3097) * Avoid None comparison for zwave cover. * Just rely on unit from config for unit_of_measurement * Explicit return None * Mqtt (#11) * Explicit return None * Missing service and wrong service name defined * Mqtt state was inverted, and never triggering * Migrate to voluptuous (#3096) * Migrate to voluptuous (#3084) * Fixed Homematic cover (#3116) * Migrate to voluptuous (#3069) 🐬 * Migrate to voluptuous (#3066) 🐬 * snapcast update (#3012) * snapcast update * snapcast update * validate config * use conf constants * orvibo updates (#3006) 🐬 * Update frontend * move units to temperature for climate zwave. wrong state was sent to mqtt cove * Use voluptuous for instapush (#3132) * Use voluptuous for Octoprint (#3111) * Migrate to voluptuous * Fix pylint issues * Add missing docstrings (fix PEP257 issues) (#3098) * Add missing docstrings (fix PEP257 issues) * Finish sentence * Updated braviatv's braviarc version to 0.3.4 (#2997) * Updated braviarc version to 0.3.4 * Updated braviarc version to requirements_all.txt * Use voluptuous for Acer projector switch (#3077) 🐬 * Use voluptuous for twilio (#3134) * Use voluptuous for webostv (#3135) * Use voluptuous for Command line platforms (#2968) * Migrate to voluptuous * Fix pylint issues * Remove FIXME * Split setup test * Test with bootstrap * Remove lon and lat * Fix pylint issues * Add coinmarketcap sensor (#3064) * Migrate to voluptuous (#3142) 🐬 * Back out insteon hub and fan changes (#3062) * Move details to docs (#3146) * Update frontend * Use constants (#3148) * Update ordering (#3149) * Migrate to voluptuous (#3092) * Display the error instead of the traceback (notify.slack) (#3079) * Display the error instead of the traceback * Remove name for check * Automatic ODB device tracker & device tracker attributes (#3035) * Migrate to voluptuous (#3173) * Add voluptuous for tomato and SNMP (#3172) * Improve voluptuous and login errors for Asus device tracker (#3170) * Add exclude option to nmap device tracker (#2983) * Add exclude option to nmap device tracker Adds an optional exclude paramater to nmap device tracker. Devices specified in the exclude list will never be scanned by nmap. This can help to reduce log spam. ex: ``` device_tracker: - platform: nmap_tracker hosts: 10.0.0.1/24 home_interval: 1 interval_seconds: 12 consider_home: 120 track_new_devices: yes exclude: - 10.0.0.2 - 10.0.0.1 ``` * Handle optional exclude * Style fixed * Added Xbox Live component (#3013) * Added Xbox Live component * Added Xbox Live sensor to coveralls * Added init success checks * Added entity id * Adding link_names to post.message call (#3167) If you do not turn link_names on, Slack will not highlight @channel and @username messages. * Allow https (fixes #3150) (#3155) * Use constants (#3156) * Bugfix: ctach Runtime errors (#3153) "RuntimeError: Disable scan failed" has been seen in a live installation * Migrate to voluptuous (#3166) 🐬 * Migrate to voluptuous (#3164) 🐬 * Migrate to voluptuous (#3163) 🐬 * Migrate to voluptuous (#3162) 🐬 and 🍪 for fixing quotes! * Exclude www_static from pydocstyle linting (#3175) 🐬 * Migrate to voluptuous (#3174) * Migrate to voluptuous (#3171) * Use voluptuous for mFi switch (#3168) * Migrate to voluptuous * Take change configuration into account * Migrate to voluptuous (#3144) 🐬 * Add the occupancy sensor_class (#3176) Such a complicated PR * Update frontend * Use voluptuous for Unifi, Ubus (#3125) * Using alert with Hue maintains prior state (#3147) * When using flash with hue, dont change the on/off state of the light so that it will naturally return to its previous state once flash is complete * ATTR_FLASH not ATTR_EFFECT * MQTT fan platform (#3095) * Add fan.mqtt, allow brightness to be passed and mapped to a fan speed for compatibility with emulated_hue * Pylint/Flake8 fixes * Remove brightness * Add more features, like custom oscillation/speed payloads and setting the speed list * Flake8 fixes * flake8/pylint fixes * Use constants * block fan.mqtt from coverage * Fix oscillating comment * Add Sphinx API doc generation (#3029) * add's sphinx project to docs/ dir * include core/helpers autodocs for API reference * Allow reloading automation without restarting HA (#3002) * Migrate to voluptuous (#3182) 🐬 * Migrate to voluptuous (#3179) 🐬 * Added scale and offset to the Temper component (#2853) 🐬 * Use voluptuous for BT and Owntracks device trackers (#3187) 🐬 * Correct binary_sensor.ecobee docs URL * Use voluptuous for Hikvisioncam switch (#3184) * Migrate to voluptuous * Use vol.Optional * Use voluptuous for Edimax (#3178) 🐬 * Use voluptuous for Bravia TV (#3165) 🐬 * Added support to 'effect: random' to Osram Lightify lights (#3192) * Added support to 'effect: random' to Osram Lightify lights * removed extra line not required * Use voluptuous for message_bird, sendgrid (#3136) * Try out the RTD theme * Doc updates * Update voluptuous for existing notify platforms (#3133) * Update voluptuous for exists notify platforms * fix constants * Simple trend sensor. (#3073) * First cut of trend sensor. * Tidy. * Migrate to voluptuous (#3193) * Migrate to voluptuous (#3194) 🐬 * Migrate to voluptuous (#3197) * Migrate to voluptuous (#3198) 🐬 * Use extend of PLATFORM_SCHEMA (#3199) * Migrate to voluptuous (#3202) 🐬 * Updated to use the occupancy sensor_class (#3204) 🐬 * Migrate to voluptuous (#3206) * Migrate to voluptuous (#3207) * Migrate to voluptuous (#3208) 🐬 * Migrate to voluptuous (#3209) 🐬 * Migrate to voluptuous (#3214) * Use voluptuous for SqueezeBox (#3212) * Migrate to voluptuous * Remove name * Migrate to voluptuous and upgrade uber_rides to 0.2.5 (#3181) * Migrate to voluptuous (#3200) 🐬 * Use Voluptuous for Luci and Netgear device trackers (#3123) * Use Voluptuous for Luci and NEtgear device trackers * str_schema shortcut * Undo str_schema * change update handling with variable for breack CCU2 (#3215) * Update ordering (#3216) * Docs update * Flake8/pylint * Add new docs requirements * Update email validation (#3228) 🐬 * Fix email validation (fixes #3138) (#3227) * Upgrade slacker to 0.9.25 (#3224) * Upgrade psutil to 4.3.1 (#3223) * Upgrade gps3 to 0.33.3 (#3222) * Upgrade Werkzeug to 0.11.11 (#3220) * Upgrade sendgrid to 3.4.0 (#3226) * Bluetooth: keep looking for new devices (#3201) * keep looking for new devices * Update bluetooth_tracker.py * change default value for tracking new devices * remove commented code * dlink switch added device state attributes and support for legacy firmware (#3211) * Use voluptuous for free mobile (#3236) * Use voluptuous for nma (#3241) * Improve 1-Wire device family detection and error checking. Use volupt… (#3233) * Improve 1-Wire device family detection and error checking. Use voluptuous * Fix detection of gpio connected devices * Replace rollershutter and garage door with cover, add fan (#3242) * Use voluptuous for Alarm.com (#3229) * Use voluptuous for gntp (#3237) * Use voluptuous for pushbullet, pushetta and pushover (#3240) * Migrate to voluptuous (#3230) 🐬 * Fix mFi sensors in uninitialized state (#3246) If mFi sensors are identified but not fully assigned they can have no tag value, and mficlient throws a ValueError to signal this. This patch handles that case by considering such devices to always be STATE_OFF. * Use voluptuous for PulseAudio Loopback (#3160) * Migrate to voluptuous * Fix conf var * Use voluptuous for Verisure (#3169) * Migrate to voluptuous * Update type and add missing config variable * thread safe modbus (#3188) * Upgraded fitbit to version 0.2.3 which fixed oauthlib.oauth2.rfc6749.errors.TokenExpiredError: (token_expired) (#3244) * update ffmpeg version to 0.10 add get image to camera (#3235) * Migrate to voluptuous (#3234) * fix bugfix with unique_id (#3217) * Zwave climate fix and wink cover. (#3205) * Fixes setpoint get was done outside loop * zxt_120 * Wink not migrated to cover * Clarifying debug * too long line * Only add 1 device entity * Owntracks voluptuous fix (#3191) * Zwave set temperature fix (#3221) * If device was off set target temp would not work. * Changed to use a workaround just for Horstmann HRT4-ZW Zwave Thermostat * Wrong Horseman id * style changes * Change PR to suggestion on gitter (#3243) * Reload groups (#3203) * Allow reloading groups without restart * Test to make sure automation listeners are removed. * Remove unused imports for group tests * Simplify group config validation * Add prepare_reload function to entity component * Migrate group to use entity_component.prepare_reload * Migrate automation to use entity_component.prepare_reload * Clean up group.get_entity_ids * Use cv.boolean for group config validation * fix remove listener (#3196) * Add linux battery sensor (#3238) * protect service data for changes in calls (#3249) * protect service data for changes in calls * change handling * move MappingProxyType to service call * Fix issue #3250 (#3253) * Minor Ecobee changes (#3131) * Update configuration check, ordering, and constants * Make API key optional * issue #3250 * Add voluptuous to ecobee (#3257) * Use constants and update ordering (#3261) * Add support for complex template structures to data_template (#3255) * Improve yaml fault tolerance and handle check_config border cases (#3159) * Use voluptuous for nx584 alarm (#3231) * Migrate to voluptuous * Fix pylint issue * fastdotcom from pypi (#3269) * Use constants and update ordering (#3268) 🐬 * Use constants and update ordering (#3267) 🐬 * Add additional template for custom date formats (#3262) I can live with a few visual line breaks 🐬 * Use constants and update ordering (#3266) * Updated braviatv's braviarc version to 0.3.5 (#3271) * Use voluptuous for Device Sun Light Trigger (#3105) * Migrate to voluptuous * Use default * Point to master till archive is back (#3285) * Pi-Hole statistics sensor (#3158) * Add Pi-Hole sensor * Update docstrings and remove print() * Use None for payload * Added stuff for support range setting (#3189) * cleanup Homematic code (#3291) * cleanup old code * cleanup round 2 * remove unwanted platforms * Update frontend * Hotfix for #3100 (#3302) * Fix TP-Link Archer C7 long passwords (#3225) * Fix tplink C7 long passwords Fixes an issue where passwords longer than 15 chars could not log in to Archer C7 routers. * Truncate in correct place * Add comment about TP-Link C7 pass truncation * Fix lint error * Truncate comment at 79 chars not 80 * modbus write registers service (#3252) * Fix bloomsky platform discovery (#3303) * Remove dev tag
413 lines
14 KiB
Python
413 lines
14 KiB
Python
"""Provides methods to bootstrap a home assistant instance."""
|
|
|
|
import logging
|
|
import logging.handlers
|
|
import os
|
|
import sys
|
|
from collections import defaultdict
|
|
from threading import RLock
|
|
|
|
from types import ModuleType
|
|
from typing import Any, Optional, Dict
|
|
|
|
import voluptuous as vol
|
|
from voluptuous.humanize import humanize_error
|
|
|
|
import homeassistant.components as core_components
|
|
from homeassistant.components import persistent_notification
|
|
import homeassistant.config as conf_util
|
|
import homeassistant.core as core
|
|
import homeassistant.loader as loader
|
|
import homeassistant.util.package as pkg_util
|
|
from homeassistant.util.yaml import clear_secret_cache
|
|
from homeassistant.const import EVENT_COMPONENT_LOADED, PLATFORM_FORMAT
|
|
from homeassistant.exceptions import HomeAssistantError
|
|
from homeassistant.helpers import (
|
|
event_decorators, service, config_per_platform, extract_domain_configs)
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
_SETUP_LOCK = RLock()
|
|
_CURRENT_SETUP = []
|
|
|
|
ATTR_COMPONENT = 'component'
|
|
|
|
ERROR_LOG_FILENAME = 'home-assistant.log'
|
|
|
|
|
|
def setup_component(hass: core.HomeAssistant, domain: str,
|
|
config: Optional[Dict]=None) -> bool:
|
|
"""Setup a component and all its dependencies."""
|
|
if domain in hass.config.components:
|
|
return True
|
|
|
|
_ensure_loader_prepared(hass)
|
|
|
|
if config is None:
|
|
config = defaultdict(dict)
|
|
|
|
components = loader.load_order_component(domain)
|
|
|
|
# OrderedSet is empty if component or dependencies could not be resolved
|
|
if not components:
|
|
return False
|
|
|
|
for component in components:
|
|
if not _setup_component(hass, component, config):
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
def _handle_requirements(hass: core.HomeAssistant, component,
|
|
name: str) -> bool:
|
|
"""Install the requirements for a component."""
|
|
if hass.config.skip_pip or not hasattr(component, 'REQUIREMENTS'):
|
|
return True
|
|
|
|
for req in component.REQUIREMENTS:
|
|
if not pkg_util.install_package(req, target=hass.config.path('deps')):
|
|
_LOGGER.error('Not initializing %s because could not install '
|
|
'dependency %s', name, req)
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
def _setup_component(hass: core.HomeAssistant, domain: str, config) -> bool:
|
|
"""Setup a component for Home Assistant."""
|
|
# pylint: disable=too-many-return-statements,too-many-branches
|
|
# pylint: disable=too-many-statements
|
|
if domain in hass.config.components:
|
|
return True
|
|
|
|
with _SETUP_LOCK:
|
|
# It might have been loaded while waiting for lock
|
|
if domain in hass.config.components:
|
|
return True
|
|
|
|
if domain in _CURRENT_SETUP:
|
|
_LOGGER.error('Attempt made to setup %s during setup of %s',
|
|
domain, domain)
|
|
return False
|
|
|
|
config = prepare_setup_component(hass, config, domain)
|
|
|
|
if config is None:
|
|
return False
|
|
|
|
component = loader.get_component(domain)
|
|
_CURRENT_SETUP.append(domain)
|
|
|
|
try:
|
|
result = component.setup(hass, config)
|
|
if result is False:
|
|
_LOGGER.error('component %s failed to initialize', domain)
|
|
return False
|
|
elif result is not True:
|
|
_LOGGER.error('component %s did not return boolean if setup '
|
|
'was successful. Disabling component.', domain)
|
|
loader.set_component(domain, None)
|
|
return False
|
|
except Exception: # pylint: disable=broad-except
|
|
_LOGGER.exception('Error during setup of component %s', domain)
|
|
return False
|
|
finally:
|
|
_CURRENT_SETUP.remove(domain)
|
|
|
|
hass.config.components.append(component.DOMAIN)
|
|
|
|
# Assumption: if a component does not depend on groups
|
|
# it communicates with devices
|
|
if 'group' not in getattr(component, 'DEPENDENCIES', []):
|
|
hass.pool.add_worker()
|
|
|
|
hass.bus.fire(
|
|
EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: component.DOMAIN})
|
|
|
|
return True
|
|
|
|
|
|
def prepare_setup_component(hass: core.HomeAssistant, config: dict,
|
|
domain: str):
|
|
"""Prepare setup of a component and return processed config."""
|
|
# pylint: disable=too-many-return-statements
|
|
component = loader.get_component(domain)
|
|
missing_deps = [dep for dep in getattr(component, 'DEPENDENCIES', [])
|
|
if dep not in hass.config.components]
|
|
|
|
if missing_deps:
|
|
_LOGGER.error(
|
|
'Not initializing %s because not all dependencies loaded: %s',
|
|
domain, ", ".join(missing_deps))
|
|
return None
|
|
|
|
if hasattr(component, 'CONFIG_SCHEMA'):
|
|
try:
|
|
config = component.CONFIG_SCHEMA(config)
|
|
except vol.MultipleInvalid as ex:
|
|
log_exception(ex, domain, config)
|
|
return None
|
|
|
|
elif hasattr(component, 'PLATFORM_SCHEMA'):
|
|
platforms = []
|
|
for p_name, p_config in config_per_platform(config, domain):
|
|
# Validate component specific platform schema
|
|
try:
|
|
p_validated = component.PLATFORM_SCHEMA(p_config)
|
|
except vol.MultipleInvalid as ex:
|
|
log_exception(ex, domain, p_config)
|
|
return None
|
|
|
|
# Not all platform components follow same pattern for platforms
|
|
# So if p_name is None we are not going to validate platform
|
|
# (the automation component is one of them)
|
|
if p_name is None:
|
|
platforms.append(p_validated)
|
|
continue
|
|
|
|
platform = prepare_setup_platform(hass, config, domain,
|
|
p_name)
|
|
|
|
if platform is None:
|
|
return None
|
|
|
|
# Validate platform specific schema
|
|
if hasattr(platform, 'PLATFORM_SCHEMA'):
|
|
try:
|
|
p_validated = platform.PLATFORM_SCHEMA(p_validated)
|
|
except vol.MultipleInvalid as ex:
|
|
log_exception(ex, '{}.{}'.format(domain, p_name),
|
|
p_validated)
|
|
return None
|
|
|
|
platforms.append(p_validated)
|
|
|
|
# Create a copy of the configuration with all config for current
|
|
# component removed and add validated config back in.
|
|
filter_keys = extract_domain_configs(config, domain)
|
|
config = {key: value for key, value in config.items()
|
|
if key not in filter_keys}
|
|
config[domain] = platforms
|
|
|
|
if not _handle_requirements(hass, component, domain):
|
|
return None
|
|
|
|
return config
|
|
|
|
|
|
def prepare_setup_platform(hass: core.HomeAssistant, config, domain: str,
|
|
platform_name: str) -> Optional[ModuleType]:
|
|
"""Load a platform and makes sure dependencies are setup."""
|
|
_ensure_loader_prepared(hass)
|
|
|
|
platform_path = PLATFORM_FORMAT.format(domain, platform_name)
|
|
|
|
platform = loader.get_platform(domain, platform_name)
|
|
|
|
# Not found
|
|
if platform is None:
|
|
_LOGGER.error('Unable to find platform %s', platform_path)
|
|
return None
|
|
|
|
# Already loaded
|
|
elif platform_path in hass.config.components:
|
|
return platform
|
|
|
|
# Load dependencies
|
|
for component in getattr(platform, 'DEPENDENCIES', []):
|
|
if not setup_component(hass, component, config):
|
|
_LOGGER.error(
|
|
'Unable to prepare setup for platform %s because '
|
|
'dependency %s could not be initialized', platform_path,
|
|
component)
|
|
return None
|
|
|
|
if not _handle_requirements(hass, platform, platform_path):
|
|
return None
|
|
|
|
return platform
|
|
|
|
|
|
# pylint: disable=too-many-branches, too-many-statements, too-many-arguments
|
|
def from_config_dict(config: Dict[str, Any],
|
|
hass: Optional[core.HomeAssistant]=None,
|
|
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.
|
|
"""
|
|
if hass is None:
|
|
hass = core.HomeAssistant()
|
|
if config_dir is not None:
|
|
config_dir = os.path.abspath(config_dir)
|
|
hass.config.config_dir = config_dir
|
|
mount_local_lib_path(config_dir)
|
|
|
|
core_config = config.get(core.DOMAIN, {})
|
|
|
|
try:
|
|
conf_util.process_ha_core_config(hass, core_config)
|
|
except vol.Invalid as ex:
|
|
log_exception(ex, 'homeassistant', core_config)
|
|
return None
|
|
|
|
conf_util.process_ha_config_upgrade(hass)
|
|
|
|
if enable_log:
|
|
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.')
|
|
|
|
_ensure_loader_prepared(hass)
|
|
|
|
# Make a copy because we are mutating it.
|
|
# Convert it to defaultdict so components can always have config dict
|
|
# Convert values to dictionaries if they are None
|
|
config = defaultdict(
|
|
dict, {key: value or {} for key, value in config.items()})
|
|
|
|
# Filter out the repeating and common config section [homeassistant]
|
|
components = set(key.split(' ')[0] for key in config.keys()
|
|
if key != core.DOMAIN)
|
|
|
|
if not core_components.setup(hass, config):
|
|
_LOGGER.error('Home Assistant core failed to initialize. '
|
|
'Further initialization aborted.')
|
|
return hass
|
|
|
|
persistent_notification.setup(hass, config)
|
|
|
|
_LOGGER.info('Home Assistant core initialized')
|
|
|
|
# Give event decorators access to HASS
|
|
event_decorators.HASS = hass
|
|
service.HASS = hass
|
|
|
|
# Setup the components
|
|
for domain in loader.load_order_components(components):
|
|
_setup_component(hass, domain, config)
|
|
|
|
return hass
|
|
|
|
|
|
def from_config_file(config_path: str,
|
|
hass: Optional[core.HomeAssistant]=None,
|
|
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 if given,
|
|
instantiates a new Home Assistant object if 'hass' is not given.
|
|
"""
|
|
if hass is None:
|
|
hass = core.HomeAssistant()
|
|
|
|
# Set config dir to directory holding config file
|
|
config_dir = os.path.abspath(os.path.dirname(config_path))
|
|
hass.config.config_dir = config_dir
|
|
mount_local_lib_path(config_dir)
|
|
|
|
enable_logging(hass, verbose, log_rotate_days)
|
|
|
|
try:
|
|
config_dict = conf_util.load_yaml_config_file(config_path)
|
|
except HomeAssistantError:
|
|
return None
|
|
finally:
|
|
clear_secret_cache()
|
|
|
|
return from_config_dict(config_dict, hass, enable_log=False,
|
|
skip_pip=skip_pip)
|
|
|
|
|
|
def enable_logging(hass: core.HomeAssistant, verbose: bool=False,
|
|
log_rotate_days=None) -> None:
|
|
"""Setup the logging."""
|
|
logging.basicConfig(level=logging.INFO)
|
|
fmt = ("%(log_color)s%(asctime)s %(levelname)s (%(threadName)s) "
|
|
"[%(name)s] %(message)s%(reset)s")
|
|
try:
|
|
from colorlog import ColoredFormatter
|
|
logging.getLogger().handlers[0].setFormatter(ColoredFormatter(
|
|
fmt,
|
|
datefmt='%y-%m-%d %H:%M:%S',
|
|
reset=True,
|
|
log_colors={
|
|
'DEBUG': 'cyan',
|
|
'INFO': 'green',
|
|
'WARNING': 'yellow',
|
|
'ERROR': 'red',
|
|
'CRITICAL': 'red',
|
|
}
|
|
))
|
|
except ImportError:
|
|
pass
|
|
|
|
# Log errors to a file if we have write access to file or config dir
|
|
err_log_path = hass.config.path(ERROR_LOG_FILENAME)
|
|
err_path_exists = os.path.isfile(err_log_path)
|
|
|
|
# Check if we can write to the error log if it exists or that
|
|
# we can create files in the containing directory if not.
|
|
if (err_path_exists and os.access(err_log_path, os.W_OK)) or \
|
|
(not err_path_exists and os.access(hass.config.config_dir, os.W_OK)):
|
|
|
|
if log_rotate_days:
|
|
err_handler = logging.handlers.TimedRotatingFileHandler(
|
|
err_log_path, when='midnight', backupCount=log_rotate_days)
|
|
else:
|
|
err_handler = logging.FileHandler(
|
|
err_log_path, mode='w', delay=True)
|
|
|
|
err_handler.setLevel(logging.INFO if verbose else logging.WARNING)
|
|
err_handler.setFormatter(
|
|
logging.Formatter('%(asctime)s %(name)s: %(message)s',
|
|
datefmt='%y-%m-%d %H:%M:%S'))
|
|
logger = logging.getLogger('')
|
|
logger.addHandler(err_handler)
|
|
logger.setLevel(logging.INFO)
|
|
|
|
else:
|
|
_LOGGER.error(
|
|
'Unable to setup error log %s (access denied)', err_log_path)
|
|
|
|
|
|
def _ensure_loader_prepared(hass: core.HomeAssistant) -> None:
|
|
"""Ensure Home Assistant loader is prepared."""
|
|
if not loader.PREPARED:
|
|
loader.prepare(hass)
|
|
|
|
|
|
def log_exception(ex, domain, config):
|
|
"""Generate log exception for config validation."""
|
|
message = 'Invalid config for [{}]: '.format(domain)
|
|
if 'extra keys not allowed' in ex.error_message:
|
|
message += '[{}] is an invalid option for [{}]. Check: {}->{}.'\
|
|
.format(ex.path[-1], domain, domain,
|
|
'->'.join('%s' % m for m in ex.path))
|
|
else:
|
|
message += humanize_error(config, ex)
|
|
|
|
if hasattr(config, '__line__'):
|
|
message += " (See {}:{})".format(config.__config_file__,
|
|
config.__line__ or '?')
|
|
|
|
_LOGGER.error(message)
|
|
|
|
|
|
def mount_local_lib_path(config_dir: str) -> str:
|
|
"""Add local library to Python Path."""
|
|
deps_dir = os.path.join(config_dir, 'deps')
|
|
if deps_dir not in sys.path:
|
|
sys.path.insert(0, os.path.join(config_dir, 'deps'))
|
|
return deps_dir
|