2023-11-13 19:48:33 +00:00
|
|
|
"""Helper functions for the CO2 Signal integration."""
|
2024-01-02 19:41:39 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2023-11-26 19:45:45 +00:00
|
|
|
from collections.abc import Mapping
|
2023-11-13 19:48:33 +00:00
|
|
|
from typing import Any
|
|
|
|
|
|
|
|
from aioelectricitymaps import ElectricityMaps
|
|
|
|
from aioelectricitymaps.models import CarbonIntensityResponse
|
|
|
|
|
2023-12-13 15:50:46 +00:00
|
|
|
from homeassistant.const import CONF_COUNTRY_CODE, CONF_LATITUDE, CONF_LONGITUDE
|
2023-11-13 19:48:33 +00:00
|
|
|
from homeassistant.core import HomeAssistant
|
|
|
|
|
|
|
|
|
|
|
|
async def fetch_latest_carbon_intensity(
|
|
|
|
hass: HomeAssistant,
|
|
|
|
em: ElectricityMaps,
|
2023-11-26 19:45:45 +00:00
|
|
|
config: Mapping[str, Any],
|
2023-11-13 19:48:33 +00:00
|
|
|
) -> CarbonIntensityResponse:
|
|
|
|
"""Fetch the latest carbon intensity based on country code or location coordinates."""
|
|
|
|
if CONF_COUNTRY_CODE in config:
|
2024-01-03 07:52:41 +00:00
|
|
|
return await em.latest_carbon_intensity_by_country_code(
|
2023-11-13 19:48:33 +00:00
|
|
|
code=config[CONF_COUNTRY_CODE]
|
|
|
|
)
|
|
|
|
|
2024-01-03 07:52:41 +00:00
|
|
|
return await em.latest_carbon_intensity_by_coordinates(
|
2023-11-13 19:48:33 +00:00
|
|
|
lat=config.get(CONF_LATITUDE, hass.config.latitude),
|
|
|
|
lon=config.get(CONF_LONGITUDE, hass.config.longitude),
|
|
|
|
)
|