Skip to content

Commit

Permalink
Require core config detection to be triggerd manually (home-assistant…
Browse files Browse the repository at this point in the history
…#24019)

* Detect core config

* Remove elevation

* Lint

* Lint

* Fix type
  • Loading branch information
balloob authored and chmielowiec committed May 28, 2019
1 parent 0ed533d commit 565e51a
Show file tree
Hide file tree
Showing 12 changed files with 188 additions and 323 deletions.
69 changes: 57 additions & 12 deletions homeassistant/components/config/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,18 @@
from homeassistant.components.http import HomeAssistantView
from homeassistant.config import async_check_ha_config_file
from homeassistant.components import websocket_api
from homeassistant.const import (
CONF_UNIT_SYSTEM_METRIC, CONF_UNIT_SYSTEM_IMPERIAL
)
from homeassistant.helpers import config_validation as cv
from homeassistant.util import location


async def async_setup(hass):
"""Set up the Hassbian config."""
hass.http.register_view(CheckConfigView)
hass.components.websocket_api.async_register_command(websocket_core_update)
websocket_api.async_register_command(hass, websocket_update_config)
websocket_api.async_register_command(hass, websocket_detect_config)
return True


Expand All @@ -35,18 +41,57 @@ async def post(self, request):
@websocket_api.require_admin
@websocket_api.async_response
@websocket_api.websocket_command({
vol.Required('type'): 'config/core/update',
vol.Optional('latitude'): vol.Coerce(float),
vol.Optional('longitude'): vol.Coerce(float),
vol.Optional('elevation'): vol.Coerce(int),
vol.Optional('unit_system'): vol.Coerce(str),
vol.Optional('location_name'): vol.Coerce(str),
vol.Optional('time_zone'): vol.Coerce(str),
'type': 'config/core/update',
vol.Optional('latitude'): cv.latitude,
vol.Optional('longitude'): cv.longitude,
vol.Optional('elevation'): int,
vol.Optional('unit_system'): cv.unit_system,
vol.Optional('location_name'): str,
vol.Optional('time_zone'): cv.time_zone,
})
async def websocket_core_update(hass, connection, msg):
"""Handle request for account info."""
async def websocket_update_config(hass, connection, msg):
"""Handle update core config command."""
data = dict(msg)
data.pop('id')
data.pop('type')
await hass.config.update(**data)
connection.send_result(msg['id'])

try:
await hass.config.update(**data)
connection.send_result(msg['id'])
except ValueError as err:
connection.send_error(
msg['id'], 'invalid_info', str(err)
)


@websocket_api.require_admin
@websocket_api.async_response
@websocket_api.websocket_command({
'type': 'config/core/detect',
})
async def websocket_detect_config(hass, connection, msg):
"""Detect core config."""
session = hass.helpers.aiohttp_client.async_get_clientsession()
location_info = await location.async_detect_location_info(session)

info = {}

if location_info is None:
connection.send_result(msg['id'], info)
return

if location_info.use_metric:
info['unit_system'] = CONF_UNIT_SYSTEM_METRIC
else:
info['unit_system'] = CONF_UNIT_SYSTEM_IMPERIAL

if location_info.latitude:
info['latitude'] = location_info.latitude

if location_info.longitude:
info['longitude'] = location_info.longitude

if location_info.time_zone:
info['time_zone'] = location_info.time_zone

connection.send_result(msg['id'], info)
10 changes: 7 additions & 3 deletions homeassistant/components/onboarding/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
from homeassistant.loader import bind_hass
from homeassistant.helpers.storage import Store

from .const import DOMAIN, STEP_USER, STEPS, STEP_INTEGRATION
from .const import (
DOMAIN, STEP_USER, STEPS, STEP_INTEGRATION, STEP_CORE_CONFIG)

STORAGE_KEY = DOMAIN
STORAGE_VERSION = 2
STORAGE_VERSION = 3


class OnboadingStorage(Store):
Expand All @@ -15,7 +16,10 @@ class OnboadingStorage(Store):
async def _async_migrate_func(self, old_version, old_data):
"""Migrate to the new version."""
# From version 1 -> 2, we automatically mark the integration step done
old_data['done'].append(STEP_INTEGRATION)
if old_version < 2:
old_data['done'].append(STEP_INTEGRATION)
if old_version < 3:
old_data['done'].append(STEP_CORE_CONFIG)
return old_data


Expand Down
2 changes: 2 additions & 0 deletions homeassistant/components/onboarding/const.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
"""Constants for the onboarding component."""
DOMAIN = 'onboarding'
STEP_USER = 'user'
STEP_CORE_CONFIG = 'core_config'
STEP_INTEGRATION = 'integration'

STEPS = [
STEP_USER,
STEP_CORE_CONFIG,
STEP_INTEGRATION,
]

Expand Down
27 changes: 25 additions & 2 deletions homeassistant/components/onboarding/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@
from homeassistant.components.http.view import HomeAssistantView
from homeassistant.core import callback

from .const import DOMAIN, STEP_USER, STEPS, DEFAULT_AREAS, STEP_INTEGRATION
from .const import (
DOMAIN, STEP_USER, STEPS, DEFAULT_AREAS, STEP_INTEGRATION,
STEP_CORE_CONFIG)


async def async_setup(hass, data, store):
"""Set up the onboarding view."""
hass.http.register_view(OnboardingView(data, store))
hass.http.register_view(UserOnboardingView(data, store))
hass.http.register_view(CoreConfigOnboardingView(data, store))
hass.http.register_view(IntegrationOnboardingView(data, store))


Expand Down Expand Up @@ -128,6 +131,26 @@ async def post(self, request, data):
})


class CoreConfigOnboardingView(_BaseOnboardingView):
"""View to finish core config onboarding step."""

url = '/api/onboarding/core_config'
name = 'api:onboarding:core_config'
step = STEP_CORE_CONFIG

async def post(self, request):
"""Handle finishing core config step."""
hass = request.app['hass']

async with self._lock:
if self._async_is_done():
return self.json_message('Core config step already done', 403)

await self._async_mark_done(hass)

return self.json({})


class IntegrationOnboardingView(_BaseOnboardingView):
"""View to finish integration onboarding step."""

Expand All @@ -139,7 +162,7 @@ class IntegrationOnboardingView(_BaseOnboardingView):
vol.Required('client_id'): str,
}))
async def post(self, request, data):
"""Handle user creation, area creation."""
"""Handle token creation."""
hass = request.app['hass']
user = request['hass_user']

Expand Down
125 changes: 8 additions & 117 deletions homeassistant/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,20 @@
from homeassistant.const import (
ATTR_FRIENDLY_NAME, ATTR_HIDDEN, ATTR_ASSUMED_STATE,
CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, CONF_PACKAGES, CONF_UNIT_SYSTEM,
CONF_TIME_ZONE, CONF_ELEVATION, CONF_UNIT_SYSTEM_METRIC,
CONF_TIME_ZONE, CONF_ELEVATION,
CONF_UNIT_SYSTEM_IMPERIAL, CONF_TEMPERATURE_UNIT, TEMP_CELSIUS,
__version__, CONF_CUSTOMIZE, CONF_CUSTOMIZE_DOMAIN, CONF_CUSTOMIZE_GLOB,
CONF_WHITELIST_EXTERNAL_DIRS, CONF_AUTH_PROVIDERS, CONF_AUTH_MFA_MODULES,
CONF_TYPE, CONF_ID)
from homeassistant.core import (
DOMAIN as CONF_CORE, SOURCE_DISCOVERED, SOURCE_YAML, HomeAssistant,
DOMAIN as CONF_CORE, SOURCE_YAML, HomeAssistant,
callback)
from homeassistant.exceptions import HomeAssistantError
from homeassistant.loader import (
Integration, async_get_integration, IntegrationNotFound
)
from homeassistant.util.yaml import load_yaml, SECRET_YAML
import homeassistant.helpers.config_validation as cv
from homeassistant.util import location as loc_util
from homeassistant.util.unit_system import IMPERIAL_SYSTEM, METRIC_SYSTEM
from homeassistant.helpers.entity_values import EntityValues
from homeassistant.helpers import config_per_platform, extract_domain_configs
Expand All @@ -52,22 +51,6 @@
('ios.conf', '.ios.conf'),
)

DEFAULT_CORE_CONFIG = (
# Tuples (attribute, default, auto detect property, description)
(CONF_NAME, 'Home', None, 'Name of the location where Home Assistant is '
'running'),
(CONF_LATITUDE, 0, 'latitude', 'Location required to calculate the time'
' the sun rises and sets'),
(CONF_LONGITUDE, 0, 'longitude', None),
(CONF_ELEVATION, 0, None, 'Impacts weather/sunrise data'
' (altitude above sea level in meters)'),
(CONF_UNIT_SYSTEM, CONF_UNIT_SYSTEM_METRIC, None,
'{} for Metric, {} for Imperial'.format(CONF_UNIT_SYSTEM_METRIC,
CONF_UNIT_SYSTEM_IMPERIAL)),
(CONF_TIME_ZONE, 'UTC', 'time_zone', 'Pick yours from here: http://en.wiki'
'pedia.org/wiki/List_of_tz_database_time_zones'),
(CONF_CUSTOMIZE, '!include customize.yaml', None, 'Customization file'),
) # type: Tuple[Tuple[str, Any, Any, Optional[str]], ...]
DEFAULT_CONFIG = """
# Configure a default setup of Home Assistant (frontend, api, etc)
default_config:
Expand Down Expand Up @@ -207,8 +190,7 @@ def get_default_config_dir() -> str:
return os.path.join(data_dir, CONFIG_DIR_NAME) # type: ignore


async def async_ensure_config_exists(hass: HomeAssistant, config_dir: str,
detect_location: bool = True)\
async def async_ensure_config_exists(hass: HomeAssistant, config_dir: str) \
-> Optional[str]:
"""Ensure a configuration file exists in given configuration directory.
Expand All @@ -220,49 +202,22 @@ async def async_ensure_config_exists(hass: HomeAssistant, config_dir: str,
if config_path is None:
print("Unable to find configuration. Creating default one in",
config_dir)
config_path = await async_create_default_config(
hass, config_dir, detect_location)
config_path = await async_create_default_config(hass, config_dir)

return config_path


async def async_create_default_config(
hass: HomeAssistant, config_dir: str, detect_location: bool = True
) -> Optional[str]:
async def async_create_default_config(hass: HomeAssistant, config_dir: str) \
-> Optional[str]:
"""Create a default configuration file in given configuration directory.
Return path to new config file if success, None if failed.
This method needs to run in an executor.
"""
info = {attr: default for attr, default, _, _ in DEFAULT_CORE_CONFIG}

if detect_location:
session = hass.helpers.aiohttp_client.async_get_clientsession()
location_info = await loc_util.async_detect_location_info(session)
else:
location_info = None

if location_info:
if location_info.use_metric:
info[CONF_UNIT_SYSTEM] = CONF_UNIT_SYSTEM_METRIC
else:
info[CONF_UNIT_SYSTEM] = CONF_UNIT_SYSTEM_IMPERIAL

for attr, default, prop, _ in DEFAULT_CORE_CONFIG:
if prop is None:
continue
info[attr] = getattr(location_info, prop) or default

if location_info.latitude and location_info.longitude:
info[CONF_ELEVATION] = await loc_util.async_get_elevation(
session, location_info.latitude, location_info.longitude)

return await hass.async_add_executor_job(
_write_default_config, config_dir, info
)
return await hass.async_add_executor_job(_write_default_config, config_dir)


def _write_default_config(config_dir: str, info: Dict)\
def _write_default_config(config_dir: str)\
-> Optional[str]:
"""Write the default config."""
from homeassistant.components.config.group import (
Expand All @@ -271,30 +226,18 @@ def _write_default_config(config_dir: str, info: Dict)\
CONFIG_PATH as AUTOMATION_CONFIG_PATH)
from homeassistant.components.config.script import (
CONFIG_PATH as SCRIPT_CONFIG_PATH)
from homeassistant.components.config.customize import (
CONFIG_PATH as CUSTOMIZE_CONFIG_PATH)

config_path = os.path.join(config_dir, YAML_CONFIG_FILE)
secret_path = os.path.join(config_dir, SECRET_YAML)
version_path = os.path.join(config_dir, VERSION_FILE)
group_yaml_path = os.path.join(config_dir, GROUP_CONFIG_PATH)
automation_yaml_path = os.path.join(config_dir, AUTOMATION_CONFIG_PATH)
script_yaml_path = os.path.join(config_dir, SCRIPT_CONFIG_PATH)
customize_yaml_path = os.path.join(config_dir, CUSTOMIZE_CONFIG_PATH)

# Writing files with YAML does not create the most human readable results
# So we're hard coding a YAML template.
try:
with open(config_path, 'wt') as config_file:
config_file.write("homeassistant:\n")

for attr, _, _, description in DEFAULT_CORE_CONFIG:
if info[attr] is None:
continue
elif description:
config_file.write(" # {}\n".format(description))
config_file.write(" {}: {}\n".format(attr, info[attr]))

config_file.write(DEFAULT_CONFIG)

with open(secret_path, 'wt') as secret_file:
Expand All @@ -312,9 +255,6 @@ def _write_default_config(config_dir: str, info: Dict)\
with open(script_yaml_path, 'wt'):
pass

with open(customize_yaml_path, 'wt'):
pass

return config_path

except IOError:
Expand Down Expand Up @@ -576,55 +516,6 @@ async def async_process_ha_core_config(
"with '%s: %s'", CONF_TEMPERATURE_UNIT, unit,
CONF_UNIT_SYSTEM, hac.units.name)

# Shortcut if no auto-detection necessary
if None not in (hac.latitude, hac.longitude, hac.units,
hac.time_zone, hac.elevation):
return

discovered = [] # type: List[Tuple[str, Any]]

# If we miss some of the needed values, auto detect them
if None in (hac.latitude, hac.longitude, hac.units,
hac.time_zone):
hac.config_source = SOURCE_DISCOVERED
info = await loc_util.async_detect_location_info(
hass.helpers.aiohttp_client.async_get_clientsession()
)

if info is None:
_LOGGER.error("Could not detect location information")
return

if hac.latitude is None and hac.longitude is None:
hac.latitude, hac.longitude = (info.latitude, info.longitude)
discovered.append(('latitude', hac.latitude))
discovered.append(('longitude', hac.longitude))

if hac.units is None:
hac.units = METRIC_SYSTEM if info.use_metric else IMPERIAL_SYSTEM
discovered.append((CONF_UNIT_SYSTEM, hac.units.name))

if hac.location_name is None:
hac.location_name = info.city
discovered.append(('name', info.city))

if hac.time_zone is None:
hac.set_time_zone(info.time_zone)
discovered.append(('time_zone', info.time_zone))

if hac.elevation is None and hac.latitude is not None and \
hac.longitude is not None:
elevation = await loc_util.async_get_elevation(
hass.helpers.aiohttp_client.async_get_clientsession(),
hac.latitude, hac.longitude)
hac.elevation = elevation
discovered.append(('elevation', elevation))

if discovered:
_LOGGER.warning(
"Incomplete core configuration. Auto detected %s",
", ".join('{}: {}'.format(key, val) for key, val in discovered))


def _log_pkg_error(
package: str, component: str, config: Dict, message: str) -> None:
Expand Down
Loading

0 comments on commit 565e51a

Please sign in to comment.