core/homeassistant/components/flick_electric/sensor.py

73 lines
2.5 KiB
Python
Raw Normal View History

"""Support for Flick Electric Pricing data."""
from datetime import timedelta
2024-12-31 13:28:24 +00:00
from decimal import Decimal
import logging
2022-08-22 11:36:33 +00:00
from typing import Any
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import CURRENCY_CENT, UnitOfEnergy
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
2024-12-31 13:28:24 +00:00
from homeassistant.helpers.update_coordinator import CoordinatorEntity
2024-12-31 13:28:24 +00:00
from .const import ATTR_COMPONENTS, ATTR_END_AT, ATTR_START_AT
from .coordinator import FlickConfigEntry, FlickElectricDataCoordinator
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(minutes=5)
async def async_setup_entry(
2024-12-31 13:28:24 +00:00
hass: HomeAssistant,
entry: FlickConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Flick Sensor Setup."""
2024-12-31 13:28:24 +00:00
coordinator = entry.runtime_data
2024-12-31 13:28:24 +00:00
async_add_entities([FlickPricingSensor(coordinator)])
2024-12-31 13:28:24 +00:00
class FlickPricingSensor(CoordinatorEntity[FlickElectricDataCoordinator], SensorEntity):
"""Entity object for Flick Electric sensor."""
_attr_attribution = "Data provided by Flick Electric"
_attr_native_unit_of_measurement = f"{CURRENCY_CENT}/{UnitOfEnergy.KILO_WATT_HOUR}"
_attr_has_entity_name = True
_attr_translation_key = "power_price"
2024-12-31 13:28:24 +00:00
def __init__(self, coordinator: FlickElectricDataCoordinator) -> None:
"""Entity object for Flick Electric sensor."""
2024-12-31 13:28:24 +00:00
super().__init__(coordinator)
self._attr_unique_id = f"{coordinator.supply_node_ref}_pricing"
@property
2024-12-31 13:28:24 +00:00
def native_value(self) -> Decimal:
"""Return the state of the sensor."""
2024-12-31 13:28:24 +00:00
# The API should return a unit price with quantity of 1.0 when no start/end time is provided
if self.coordinator.data.quantity != 1:
_LOGGER.warning(
"Unexpected quantity for unit price: %s", self.coordinator.data
)
2025-01-09 09:09:04 +00:00
return self.coordinator.data.cost * 100
@property
2024-12-31 13:28:24 +00:00
def extra_state_attributes(self) -> dict[str, Any] | None:
"""Return the state attributes."""
2025-01-09 09:09:04 +00:00
components: dict[str, float] = {}
2024-12-31 13:28:24 +00:00
for component in self.coordinator.data.components:
if component.charge_setter not in ATTR_COMPONENTS:
_LOGGER.warning("Found unknown component: %s", component.charge_setter)
continue
2025-01-09 09:09:04 +00:00
components[component.charge_setter] = float(component.value * 100)
2024-12-31 13:28:24 +00:00
return {
ATTR_START_AT: self.coordinator.data.start_at,
ATTR_END_AT: self.coordinator.data.end_at,
**components,
}