Add config flow for sun (#68295)

Co-authored-by: Franck Nijhof <git@frenck.dev>
This commit is contained in:
Erik Montnemery 2022-03-18 10:12:15 +01:00 committed by GitHub
parent bc862e97ed
commit 2fcced333d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 236 additions and 8 deletions

View file

@ -2,6 +2,7 @@
from datetime import timedelta
import logging
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import (
CONF_ELEVATION,
EVENT_CORE_CONFIG_UPDATE,
@ -18,12 +19,12 @@ from homeassistant.helpers.sun import (
from homeassistant.helpers.typing import ConfigType
from homeassistant.util import dt as dt_util
from .const import DOMAIN
# mypy: allow-untyped-calls, allow-untyped-defs, no-check-untyped-defs
_LOGGER = logging.getLogger(__name__)
DOMAIN = "sun"
ENTITY_ID = "sun.sun"
STATE_ABOVE_HORIZON = "above_horizon"
@ -80,7 +81,27 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"Elevation is now configured in Home Assistant core. "
"See https://www.home-assistant.io/docs/configuration/basic/"
)
Sun(hass)
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data=config,
)
)
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up from a config entry."""
hass.data[DOMAIN] = Sun(hass)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
sun = hass.data.pop(DOMAIN)
sun.remove_listeners()
hass.states.async_remove(sun.entity_id)
return True
@ -100,6 +121,9 @@ class Sun(Entity):
self.solar_elevation = self.solar_azimuth = None
self.rising = self.phase = None
self._next_change = None
self._config_listener = None
self._update_events_listener = None
self._update_sun_position_listener = None
@callback
def update_location(_event):
@ -108,10 +132,24 @@ class Sun(Entity):
return
self.location = location
self.elevation = elevation
if self._update_events_listener:
self._update_events_listener()
self.update_events()
update_location(None)
self.hass.bus.async_listen(EVENT_CORE_CONFIG_UPDATE, update_location)
self._config_listener = self.hass.bus.async_listen(
EVENT_CORE_CONFIG_UPDATE, update_location
)
@callback
def remove_listeners(self):
"""Remove listeners."""
if self._config_listener:
self._config_listener()
if self._update_events_listener:
self._update_events_listener()
if self._update_sun_position_listener:
self._update_sun_position_listener()
@property
def name(self):
@ -211,10 +249,12 @@ class Sun(Entity):
_LOGGER.debug(
"sun phase_update@%s: phase=%s", utc_point_in_time.isoformat(), self.phase
)
if self._update_sun_position_listener:
self._update_sun_position_listener()
self.update_sun_position()
# Set timer for the next solar event
event.async_track_point_in_utc_time(
self._update_events_listener = event.async_track_point_in_utc_time(
self.hass, self.update_events, self._next_change
)
_LOGGER.debug("next time: %s", self._next_change.isoformat())
@ -244,7 +284,8 @@ class Sun(Entity):
# if the next update is within 1.25 of the next
# position update just drop it
if utc_point_in_time + delta * 1.25 > self._next_change:
self._update_sun_position_listener = None
return
event.async_track_point_in_utc_time(
self._update_sun_position_listener = event.async_track_point_in_utc_time(
self.hass, self.update_sun_position, utc_point_in_time + delta
)

View file

@ -0,0 +1,31 @@
"""Config flow to configure the Sun integration."""
from __future__ import annotations
from typing import Any
from homeassistant.config_entries import ConfigFlow
from homeassistant.data_entry_flow import FlowResult
from .const import DEFAULT_NAME, DOMAIN
class SunConfigFlow(ConfigFlow, domain=DOMAIN):
"""Config flow for Sun."""
VERSION = 1
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle a flow initialized by the user."""
if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed")
if user_input is not None:
return self.async_create_entry(title=DEFAULT_NAME, data={})
return self.async_show_form(step_id="user")
async def async_step_import(self, user_input: dict[str, Any]) -> FlowResult:
"""Handle import from configuration.yaml."""
return await self.async_step_user(user_input)

View file

@ -0,0 +1,6 @@
"""Constants for the Sun integration."""
from typing import Final
DOMAIN: Final = "sun"
DEFAULT_NAME: Final = "Sun"

View file

@ -4,5 +4,6 @@
"documentation": "https://www.home-assistant.io/integrations/sun",
"codeowners": ["@Swamp-Ig"],
"quality_scale": "internal",
"iot_class": "calculated"
"iot_class": "calculated",
"config_flow": true
}

View file

@ -1,5 +1,15 @@
{
"title": "Sun",
"config": {
"step": {
"user": {
"description": "[%key:common::config_flow::description::confirm_setup%]"
}
},
"abort": {
"single_instance_allowed": "[%key:common::config_flow::abort::single_instance_allowed%]"
}
},
"state": {
"_": {
"above_horizon": "Above horizon",

View file

@ -323,6 +323,7 @@ FLOWS = [
"steamist",
"stookalert",
"subaru",
"sun",
"surepetcare",
"switch_as_x",
"switchbot",

View file

@ -0,0 +1,75 @@
"""Tests for the Sun config flow."""
from unittest.mock import patch
import pytest
from homeassistant.components.sun.const import DOMAIN
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import (
RESULT_TYPE_ABORT,
RESULT_TYPE_CREATE_ENTRY,
RESULT_TYPE_FORM,
)
from tests.common import MockConfigEntry
async def test_full_user_flow(hass: HomeAssistant) -> None:
"""Test the full user configuration flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result.get("type") == RESULT_TYPE_FORM
assert result.get("step_id") == SOURCE_USER
assert "flow_id" in result
with patch(
"homeassistant.components.sun.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={},
)
assert result.get("type") == RESULT_TYPE_CREATE_ENTRY
assert result.get("title") == "Sun"
assert result.get("data") == {}
assert result.get("options") == {}
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize("source", [SOURCE_USER, SOURCE_IMPORT])
async def test_single_instance_allowed(
hass: HomeAssistant,
source: str,
) -> None:
"""Test we abort if already setup."""
mock_config_entry = MockConfigEntry(domain=DOMAIN)
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": source}
)
assert result.get("type") == RESULT_TYPE_ABORT
assert result.get("reason") == "single_instance_allowed"
async def test_import_flow(
hass: HomeAssistant,
) -> None:
"""Test the import configuration flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={},
)
assert result.get("type") == RESULT_TYPE_CREATE_ENTRY
assert result.get("title") == "Sun"
assert result.get("data") == {}
assert result.get("options") == {}

View file

@ -10,6 +10,8 @@ import homeassistant.core as ha
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from tests.common import MockConfigEntry
async def test_setting_rising(hass, legacy_patchable_time):
"""Test retrieving sun setting and rising."""
@ -105,7 +107,7 @@ async def test_setting_rising(hass, legacy_patchable_time):
)
async def test_state_change(hass, legacy_patchable_time):
async def test_state_change(hass, legacy_patchable_time, caplog):
"""Test if the state changes at next setting/rising."""
now = datetime(2016, 6, 1, 8, 0, 0, tzinfo=dt_util.UTC)
with patch("homeassistant.helpers.condition.dt_util.utcnow", return_value=now):
@ -131,12 +133,34 @@ async def test_state_change(hass, legacy_patchable_time):
assert sun.STATE_ABOVE_HORIZON == hass.states.get(sun.ENTITY_ID).state
# Update core configuration
with patch("homeassistant.helpers.condition.dt_util.utcnow", return_value=now):
await hass.config.async_update(longitude=hass.config.longitude + 90)
await hass.async_block_till_done()
assert sun.STATE_ABOVE_HORIZON == hass.states.get(sun.ENTITY_ID).state
# Test listeners are not duplicated after a core configuration change
test_time = dt_util.parse_datetime(
hass.states.get(sun.ENTITY_ID).attributes[sun.STATE_ATTR_NEXT_DUSK]
)
assert test_time is not None
patched_time = test_time + timedelta(seconds=5)
caplog.clear()
with patch(
"homeassistant.helpers.condition.dt_util.utcnow", return_value=patched_time
):
hass.bus.async_fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: patched_time})
await hass.async_block_till_done()
await hass.async_block_till_done()
assert caplog.text.count("sun phase_update") == 1
# Called once by time listener, once from Sun.update_events
assert caplog.text.count("sun position_update") == 2
assert sun.STATE_BELOW_HORIZON == hass.states.get(sun.ENTITY_ID).state
async def test_norway_in_june(hass):
"""Test location in Norway where the sun doesn't set in summer."""
@ -194,3 +218,42 @@ async def test_state_change_count(hass):
await hass.async_block_till_done()
assert len(events) < 721
async def test_setup_and_remove_config_entry(
hass: ha.HomeAssistant, legacy_patchable_time
) -> None:
"""Test setting up and removing a config entry."""
# Setup the config entry
config_entry = MockConfigEntry(domain=sun.DOMAIN)
config_entry.add_to_hass(hass)
now = datetime(2016, 6, 1, 8, 0, 0, tzinfo=dt_util.UTC)
with patch("homeassistant.helpers.condition.dt_util.utcnow", return_value=now):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
# Check the platform is setup correctly
state = hass.states.get("sun.sun")
assert state is not None
test_time = dt_util.parse_datetime(
hass.states.get(sun.ENTITY_ID).attributes[sun.STATE_ATTR_NEXT_RISING]
)
assert test_time is not None
assert sun.STATE_BELOW_HORIZON == hass.states.get(sun.ENTITY_ID).state
# Remove the config entry
assert await hass.config_entries.async_remove(config_entry.entry_id)
await hass.async_block_till_done()
# Check the state is removed, and does not reappear
assert hass.states.get("sun.sun") is None
patched_time = test_time + timedelta(seconds=5)
with patch(
"homeassistant.helpers.condition.dt_util.utcnow", return_value=patched_time
):
hass.bus.async_fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: patched_time})
await hass.async_block_till_done()
assert hass.states.get("sun.sun") is None