mirror of
https://github.com/home-assistant/core.git
synced 2025-04-25 01:38:02 +00:00
Move co2signal coordinator to its own file (#100541)
* Move co2signal coordinator to its own file * Fix import
This commit is contained in:
parent
45c0dc6854
commit
dc2afb71ae
@ -1,25 +1,14 @@
|
||||
"""The CO2 Signal integration."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
from typing import Any, cast
|
||||
|
||||
import CO2Signal
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, Platform
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryAuthFailed
|
||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
||||
|
||||
from .const import CONF_COUNTRY_CODE, DOMAIN
|
||||
from .exceptions import APIRatelimitExceeded, CO2Error, InvalidAuth, UnknownError
|
||||
from .models import CO2SignalResponse
|
||||
from .const import DOMAIN
|
||||
from .coordinator import CO2SignalCoordinator
|
||||
|
||||
PLATFORMS = [Platform.SENSOR]
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
@ -35,71 +24,3 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Unload a config entry."""
|
||||
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
|
||||
|
||||
class CO2SignalCoordinator(DataUpdateCoordinator[CO2SignalResponse]):
|
||||
"""Data update coordinator."""
|
||||
|
||||
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
|
||||
"""Initialize the coordinator."""
|
||||
super().__init__(
|
||||
hass, _LOGGER, name=DOMAIN, update_interval=timedelta(minutes=15)
|
||||
)
|
||||
self._entry = entry
|
||||
|
||||
@property
|
||||
def entry_id(self) -> str:
|
||||
"""Return entry ID."""
|
||||
return self._entry.entry_id
|
||||
|
||||
async def _async_update_data(self) -> CO2SignalResponse:
|
||||
"""Fetch the latest data from the source."""
|
||||
try:
|
||||
data = await self.hass.async_add_executor_job(
|
||||
get_data, self.hass, self._entry.data
|
||||
)
|
||||
except InvalidAuth as err:
|
||||
raise ConfigEntryAuthFailed from err
|
||||
except CO2Error as err:
|
||||
raise UpdateFailed(str(err)) from err
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def get_data(hass: HomeAssistant, config: Mapping[str, Any]) -> CO2SignalResponse:
|
||||
"""Get data from the API."""
|
||||
if CONF_COUNTRY_CODE in config:
|
||||
latitude = None
|
||||
longitude = None
|
||||
else:
|
||||
latitude = config.get(CONF_LATITUDE, hass.config.latitude)
|
||||
longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
|
||||
|
||||
try:
|
||||
data = CO2Signal.get_latest(
|
||||
config[CONF_API_KEY],
|
||||
config.get(CONF_COUNTRY_CODE),
|
||||
latitude,
|
||||
longitude,
|
||||
wait=False,
|
||||
)
|
||||
|
||||
except ValueError as err:
|
||||
err_str = str(err)
|
||||
|
||||
if "Invalid authentication credentials" in err_str:
|
||||
raise InvalidAuth from err
|
||||
if "API rate limit exceeded." in err_str:
|
||||
raise APIRatelimitExceeded from err
|
||||
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
raise UnknownError from err
|
||||
|
||||
if "error" in data:
|
||||
raise UnknownError(data["error"])
|
||||
|
||||
if data.get("status") != "ok":
|
||||
_LOGGER.exception("Unexpected response: %s", data)
|
||||
raise UnknownError
|
||||
|
||||
return cast(CO2SignalResponse, data)
|
||||
|
@ -10,8 +10,8 @@ from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE
|
||||
from homeassistant.data_entry_flow import FlowResult
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
from . import get_data
|
||||
from .const import CONF_COUNTRY_CODE, DOMAIN
|
||||
from .coordinator import get_data
|
||||
from .exceptions import APIRatelimitExceeded, InvalidAuth
|
||||
from .util import get_extra_name
|
||||
|
||||
|
90
homeassistant/components/co2signal/coordinator.py
Normal file
90
homeassistant/components/co2signal/coordinator.py
Normal file
@ -0,0 +1,90 @@
|
||||
"""DataUpdateCoordinator for the co2signal integration."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
from typing import Any, cast
|
||||
|
||||
import CO2Signal
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryAuthFailed
|
||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
||||
|
||||
from .const import CONF_COUNTRY_CODE, DOMAIN
|
||||
from .exceptions import APIRatelimitExceeded, CO2Error, InvalidAuth, UnknownError
|
||||
from .models import CO2SignalResponse
|
||||
|
||||
PLATFORMS = [Platform.SENSOR]
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CO2SignalCoordinator(DataUpdateCoordinator[CO2SignalResponse]):
|
||||
"""Data update coordinator."""
|
||||
|
||||
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
|
||||
"""Initialize the coordinator."""
|
||||
super().__init__(
|
||||
hass, _LOGGER, name=DOMAIN, update_interval=timedelta(minutes=15)
|
||||
)
|
||||
self._entry = entry
|
||||
|
||||
@property
|
||||
def entry_id(self) -> str:
|
||||
"""Return entry ID."""
|
||||
return self._entry.entry_id
|
||||
|
||||
async def _async_update_data(self) -> CO2SignalResponse:
|
||||
"""Fetch the latest data from the source."""
|
||||
try:
|
||||
data = await self.hass.async_add_executor_job(
|
||||
get_data, self.hass, self._entry.data
|
||||
)
|
||||
except InvalidAuth as err:
|
||||
raise ConfigEntryAuthFailed from err
|
||||
except CO2Error as err:
|
||||
raise UpdateFailed(str(err)) from err
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def get_data(hass: HomeAssistant, config: Mapping[str, Any]) -> CO2SignalResponse:
|
||||
"""Get data from the API."""
|
||||
if CONF_COUNTRY_CODE in config:
|
||||
latitude = None
|
||||
longitude = None
|
||||
else:
|
||||
latitude = config.get(CONF_LATITUDE, hass.config.latitude)
|
||||
longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
|
||||
|
||||
try:
|
||||
data = CO2Signal.get_latest(
|
||||
config[CONF_API_KEY],
|
||||
config.get(CONF_COUNTRY_CODE),
|
||||
latitude,
|
||||
longitude,
|
||||
wait=False,
|
||||
)
|
||||
|
||||
except ValueError as err:
|
||||
err_str = str(err)
|
||||
|
||||
if "Invalid authentication credentials" in err_str:
|
||||
raise InvalidAuth from err
|
||||
if "API rate limit exceeded." in err_str:
|
||||
raise APIRatelimitExceeded from err
|
||||
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
raise UnknownError from err
|
||||
|
||||
if "error" in data:
|
||||
raise UnknownError(data["error"])
|
||||
|
||||
if data.get("status") != "ok":
|
||||
_LOGGER.exception("Unexpected response: %s", data)
|
||||
raise UnknownError
|
||||
|
||||
return cast(CO2SignalResponse, data)
|
@ -8,7 +8,8 @@ from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from . import DOMAIN, CO2SignalCoordinator
|
||||
from .const import DOMAIN
|
||||
from .coordinator import CO2SignalCoordinator
|
||||
|
||||
TO_REDACT = {CONF_API_KEY}
|
||||
|
||||
|
@ -17,8 +17,8 @@ from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
|
||||
from . import CO2SignalCoordinator
|
||||
from .const import ATTRIBUTION, DOMAIN
|
||||
from .coordinator import CO2SignalCoordinator
|
||||
|
||||
SCAN_INTERVAL = timedelta(minutes=3)
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user