Skip to content

Commit

Permalink
Remaster configuration schema (#193)
Browse files Browse the repository at this point in the history
  • Loading branch information
Limych committed May 18, 2024
1 parent 0be8617 commit 6edda71
Show file tree
Hide file tree
Showing 15 changed files with 98 additions and 146 deletions.
20 changes: 10 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,13 @@ for today and 2 days forward.
# Example configuration.yaml entry
gismeteo:
sweet_home:
sensors: {}

dacha:
name: Our Country House
latitude: ...
longitude: ...
sensors:
forecast_days: 2
add_sensors: yes
forecast_days: 2
```
See below detailed descriptions to configure component.
Expand Down Expand Up @@ -107,14 +106,15 @@ I put a lot of work into making this repo and component available and updated to
> _(float) (Optional) (Default: coordinates from the Home Assistant configuration)_\
> Longitude coordinate to monitor weather of (required if `latitude` is specified).
>
> **sensors:**\
> _(list) (Optional)_\
> Setup for list of forecast sensors to display in the frontend.
> **add_sensors:**\
> _(boolean) (Optional) (Default: false)_\
> Enable this option to add current weather and forecast sensors to the frontend.
>
> > **forecast_days:**\
> > _(positive int; 0–6) (Optional) (Default: do not create any sensors)_\
> > How many days ahead to make forecast sensors.\
> > **Note:** If you only need a forecast sensors for today, specify `0`.
> **forecast_days:**\
> _(positive int; 0–6) (Optional) (Default: do not create any sensors)_\
> How many days ahead to make forecast sensors.\
> **Note:** Forecast sensors will be created only if `add_sensors` option is enabled.\
> **Note:** If you only need a forecast sensors for today, specify `0`.

When `sensors` option are enabled, it creates 20 sensors. Each shows one aspect of current weather. Only few basic sensors are enabled by default. But you can enable any sensor through device settings.

Expand Down
1 change: 0 additions & 1 deletion config/configuration.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ logger:

gismeteo:
sweet_home:
sensors: {}

dacha:
name: Our Country House
Expand Down
44 changes: 13 additions & 31 deletions custom_components/gismeteo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,8 @@
CONF_API_KEY,
CONF_LATITUDE,
CONF_LONGITUDE,
CONF_MONITORED_CONDITIONS,
CONF_NAME,
CONF_SENSORS,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
Expand All @@ -33,10 +31,9 @@

from .api import ApiError, GismeteoApiClient
from .const import (
CONF_ADD_SENSORS,
CONF_CACHE_DIR,
CONF_FORECAST,
CONF_FORECAST_DAYS,
CONF_PLATFORM_FORMAT,
COORDINATOR,
DOMAIN,
DOMAIN_YAML,
Expand All @@ -51,27 +48,22 @@

forecast_days_int = vol.All(vol.Coerce(int), vol.Range(min=0, max=6))

SENSORS_SCHEMA = vol.Schema(
{
vol.Optional(CONF_FORECAST_DAYS): forecast_days_int,
vol.Optional(CONF_MONITORED_CONDITIONS): cv.deprecated,
vol.Optional(CONF_FORECAST): cv.deprecated,
}
)

LOCATION_SCHEMA = vol.Schema(
{
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_API_KEY): cv.string,
vol.Optional(CONF_LATITUDE): cv.latitude,
vol.Optional(CONF_LONGITUDE): cv.longitude,
vol.Optional(CONF_SENSORS): SENSORS_SCHEMA,
vol.Optional(CONF_SENSORS): cv.deprecated,
vol.Optional(CONF_ADD_SENSORS, default=False): cv.boolean,
vol.Optional(CONF_FORECAST_DAYS): forecast_days_int,
vol.Optional(CONF_CACHE_DIR): cv.string,
}
)

CONFIG_SCHEMA = vol.Schema(
{DOMAIN: cv.schema_with_slug_keys(LOCATION_SCHEMA)}, extra=vol.ALLOW_EXTRA
{DOMAIN: cv.schema_with_slug_keys(vol.Any(LOCATION_SCHEMA, None))},
extra=vol.ALLOW_EXTRA,
)


Expand Down Expand Up @@ -99,8 +91,12 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
return True


def _get_api_client(hass: HomeAssistant, config: ConfigType) -> GismeteoApiClient:
def _get_api_client(
hass: HomeAssistant, config: ConfigType | None
) -> GismeteoApiClient:
"""Prepare Gismeteo API client instance."""
if config is None:
config = {}
return GismeteoApiClient(
async_get_clientsession(hass),
latitude=config.get(CONF_LATITUDE, hass.config.latitude),
Expand Down Expand Up @@ -128,26 +124,12 @@ async def _async_get_coordinator(hass: HomeAssistant, unique_id, config: dict):
return coordinator


def _convert_yaml_config(config: ConfigType) -> ConfigType:
"""Convert YAML config to EntryFlow config."""
cfg = config.copy()

if CONF_SENSORS in cfg:
cfg.update(cfg[CONF_SENSORS])
cfg.pop(CONF_SENSORS)
cfg[CONF_PLATFORM_FORMAT.format(Platform.SENSOR)] = True

return cfg


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Gismeteo as config entry."""
if entry.source == SOURCE_IMPORT:
# Setup from configuration.yaml
for uid, cfg in hass.data[DOMAIN_YAML].items():
cfg = _convert_yaml_config(cfg)

coordinator = await _async_get_coordinator(hass, uid, cfg)
for uid, config in hass.data[DOMAIN_YAML].items():
coordinator = await _async_get_coordinator(hass, uid, config)
hass.data[DOMAIN][uid] = {
COORDINATOR: coordinator,
}
Expand Down
8 changes: 3 additions & 5 deletions custom_components/gismeteo/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@

from homeassistant import config_entries
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, Platform
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv

from . import _get_api_client, forecast_days_int # pylint: disable=unused-import
from .api import ApiError
from .const import ( # pylint: disable=unused-import
CONF_ADD_SENSORS,
CONF_FORECAST_DAYS,
CONF_PLATFORM_FORMAT,
DOMAIN,
)

Expand Down Expand Up @@ -132,9 +132,7 @@ async def async_step_user(self, user_input: dict | None = None):
data_schema=self.add_suggested_values_to_schema(
vol.Schema(
{
vol.Required(
CONF_PLATFORM_FORMAT.format(Platform.SENSOR)
): bool,
vol.Required(CONF_ADD_SENSORS, default=False): bool,
vol.Optional(CONF_FORECAST_DAYS): forecast_days_int,
}
),
Expand Down
7 changes: 1 addition & 6 deletions custom_components/gismeteo/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,18 +62,13 @@

# Configuration and options
CONF_CACHE_DIR: Final = "cache_dir"
CONF_FORECAST: Final = "forecast"
CONF_ADD_SENSORS: Final = "add_sensors"
CONF_FORECAST_DAYS: Final = "forecast_days"
CONF_PLATFORMS: Final = "platforms"
CONF_YAML: Final = "_yaml"
CONF_PLATFORM_FORMAT: Final = "_platform_{}"

# Defaults
DEFAULT_NAME: Final = "Gismeteo"

# Attributes
ATTR_LAST_UPDATED: Final = "last_updated"
#
ATTR_SUNRISE: Final = "sunrise"
ATTR_SUNSET: Final = "sunset"
#
Expand Down
20 changes: 10 additions & 10 deletions custom_components/gismeteo/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,16 @@
)
from homeassistant.components.weather import ATTR_FORECAST_CONDITION
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_NAME, Platform
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, StateType

from . import GismeteoDataUpdateCoordinator, _convert_yaml_config, deslugify
from . import GismeteoDataUpdateCoordinator, deslugify
from .const import (
ATTRIBUTION,
CONF_ADD_SENSORS,
CONF_FORECAST_DAYS,
CONF_PLATFORM_FORMAT,
COORDINATOR,
DOMAIN,
DOMAIN_YAML,
Expand Down Expand Up @@ -75,23 +75,23 @@ async def async_setup_entry(
entities = []
if config_entry.source == SOURCE_IMPORT:
# Setup from configuration.yaml
for uid, cfg in hass.data[DOMAIN_YAML].items():
cfg = _convert_yaml_config(cfg)

if cfg.get(CONF_PLATFORM_FORMAT.format(Platform.SENSOR), False) is False:
for uid, config in hass.data[DOMAIN_YAML].items():
if config is None:
config = {}
if not config.get(CONF_ADD_SENSORS):
continue # pragma: no cover

location_name = cfg.get(CONF_NAME, deslugify(uid))
location_name = config.get(CONF_NAME, deslugify(uid))
coordinator = hass.data[DOMAIN][uid][COORDINATOR]

entities.extend(_gen_entities(location_name, coordinator, cfg))
entities.extend(_gen_entities(location_name, coordinator, config))

else:
# Setup from config entry
config = config_entry.data.copy() # type: ConfigType
config.update(config_entry.options)

if config.get(CONF_PLATFORM_FORMAT.format(Platform.SENSOR), False) is False:
if not config.get(CONF_ADD_SENSORS):
return # pragma: no cover

location_name = config[CONF_NAME]
Expand Down
2 changes: 1 addition & 1 deletion custom_components/gismeteo/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@
"step": {
"user": {
"data": {
"_platform_sensor": "Sensor entities enabled",
"add_sensors": "Sensor entities enabled",
"forecast_days": "Forecast sensors to show (days)"
},
"title": "Gismeteo Options"
Expand Down
2 changes: 1 addition & 1 deletion custom_components/gismeteo/translations/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@
"step": {
"user": {
"data": {
"_platform_sensor": "Сенсоры включены",
"add_sensors": "Сенсоры включены",
"forecast_days": "Сенсоры прогноза на (дней)"
},
"title": "Настройки Gismeteo"
Expand Down
10 changes: 5 additions & 5 deletions custom_components/gismeteo/weather.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
)
from homeassistant.core import HomeAssistant, callback

from . import GismeteoDataUpdateCoordinator, _convert_yaml_config, deslugify
from . import GismeteoDataUpdateCoordinator, deslugify
from .const import ATTRIBUTION, COORDINATOR, DOMAIN, DOMAIN_YAML, ForecastMode
from .entity import GismeteoEntity

Expand All @@ -37,10 +37,10 @@ async def async_setup_entry(hass: HomeAssistant, config_entry, async_add_entitie
entities = []
if config_entry.source == SOURCE_IMPORT:
# Setup from configuration.yaml
for uid, cfg in hass.data[DOMAIN_YAML].items():
cfg = _convert_yaml_config(cfg)

location_name = cfg.get(CONF_NAME, deslugify(uid))
for uid, config in hass.data[DOMAIN_YAML].items():
if config is None:
config = {}
location_name = config.get(CONF_NAME, deslugify(uid))
coordinator = hass.data[DOMAIN][uid][COORDINATOR]

entities.append(GismeteoWeather(coordinator, location_name))
Expand Down
40 changes: 17 additions & 23 deletions tests/const.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,28 @@
"""Constants for tests."""

from custom_components.gismeteo.const import CONF_PLATFORM_FORMAT
from homeassistant.const import (
CONF_LATITUDE,
CONF_LONGITUDE,
CONF_NAME,
CONF_SENSORS,
Platform,
)
from custom_components.gismeteo.const import CONF_ADD_SENSORS
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME

FAKE_NAME = "Home"
FAKE_UNIQUE_ID = "test_id"
FAKE_LATITUDE = 55.55
FAKE_LONGITUDE = 122.12
TEST_NAME = "Home"
TEST_UNIQUE_ID = "test_id"
TEST_LATITUDE = 55.55
TEST_LONGITUDE = 122.12

FAKE_CONFIG = {
CONF_NAME: FAKE_NAME,
CONF_LATITUDE: FAKE_LATITUDE,
CONF_LONGITUDE: FAKE_LONGITUDE,
TEST_CONFIG = {
CONF_NAME: TEST_NAME,
CONF_LATITUDE: TEST_LATITUDE,
CONF_LONGITUDE: TEST_LONGITUDE,
}

FAKE_CONFIG_OPTIONS = {
CONF_PLATFORM_FORMAT.format(Platform.SENSOR): True,
TEST_CONFIG_OPTIONS = {
CONF_ADD_SENSORS: True,
}

FAKE_CONFIG_YAML = {
TEST_CONFIG_YAML = {
"home": {
CONF_NAME: FAKE_NAME,
CONF_LATITUDE: FAKE_LATITUDE,
CONF_LONGITUDE: FAKE_LONGITUDE,
CONF_SENSORS: {},
CONF_NAME: TEST_NAME,
CONF_LATITUDE: TEST_LATITUDE,
CONF_LONGITUDE: TEST_LONGITUDE,
CONF_ADD_SENSORS: True,
},
}
Loading

0 comments on commit 6edda71

Please sign in to comment.