Skip to content

Commit

Permalink
Strip down sensors before adding new ones
Browse files Browse the repository at this point in the history
  • Loading branch information
Sindre Broch committed May 16, 2022
1 parent 4ee2a5b commit 60e3d19
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 161 deletions.
49 changes: 5 additions & 44 deletions custom_components/elvia/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,15 @@

from .api import ElviaApiClient
from .const import DATE_FORMAT, DOMAIN, LOGGER
from .models import GridTariffCollection, TariffType, PriceInfo, PriceLevel, VariablePrice
from .models import GridTariffCollection, TariffType

class ElviaDataUpdateCoordinator(DataUpdateCoordinator):
"""Class to manage fetching from Elvia data API."""

nextFetch: datetime

data: GridTariffCollection
hourlyPriceInfo: PriceInfo
fixedPriceLevel: PriceLevel
variablePrice: VariablePrice


def __init__(
self,
hass: HomeAssistant,
Expand All @@ -38,7 +35,7 @@ def __init__(

self._attr_device_info = DeviceInfo(
name=self.device_info.title,
manufacturer=self.device_info.company,
manufacturer=self.device_info.companyName,
model=self.device_info.tariffKey,
identifiers={(DOMAIN, self.api._metering_point_id)},
configuration_url="https://www.elvia.no/logg-inn/",
Expand All @@ -54,44 +51,8 @@ def __init__(
async def _async_update_data(self) -> GridTariffCollection:
"""Update data via library."""

now = datetime.now()

if self.nextFetch is None or self.nextFetch < now:
return self.data

try:
meteringpoint = await self.api.meteringpoint()

for hourlyPriceInfo in meteringpoint.gridTariff.tariffPrice.priceInfo:

start = datetime.strptime(hourlyPriceInfo.startTime[0:19], DATE_FORMAT)
end = datetime.strptime(hourlyPriceInfo.expiredAt[0:19], DATE_FORMAT)

if (now < start) and (now > end):
continue

self.hourlyPriceInfo = hourlyPriceInfo

for fixedPrice in hourlyPriceInfo.fixedPrices: # TODO handle multiple?
for priceLevel in fixedPrice.priceLevels: # TODO handle multiple?
self.fixedPriceLevel = priceLevel

self.variablePrice = hourlyPriceInfo.variablePrice
self.nextFetch = now + timedelta(hours=1) # TODO be more specific to refresh at new hour

return meteringpoint
return await self.api.meteringpoint()
except (Error, ClientConnectorError) as error:
LOGGER.error("Update error %s", error)
raise UpdateFailed(error) from error

## priceinfo -- list
# startTime: str
# expiredAt: str
# hoursShortName: str
# season: str
# publicHoliday: bool
# fixedPrices: List[FixedPrices]
# variablePrice: VariablePrice

## fixedprices
# priceLevel: List[PriceLevel]
121 changes: 4 additions & 117 deletions custom_components/elvia/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,71 +14,10 @@
from .const import DOMAIN, LOGGER
from .coordinator import ElviaDataUpdateCoordinator

FIXED_PRICE_SENSORS: tuple[SensorEntityDescription, ...] = (
SENSORS: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key="fixed_price_level",
name="Price level fixed",
icon="mdi:currency-usd",
),
)
FIXED_PRICE_PRICE_SENSORS: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key="fixed_price_total",
name="Price fixed total",
icon="mdi:currency-usd",
device_class=SensorDeviceClass.MONETARY,
state_class=SensorStateClass.MEASUREMENT,
),
SensorEntityDescription(
key="fixed_price_fixed",
name="Price fixed",
icon="mdi:currency-usd",
device_class=SensorDeviceClass.MONETARY,
state_class=SensorStateClass.MEASUREMENT,
),
SensorEntityDescription(
key="fixed_price_taxes",
name="Price fixed taxes",
icon="mdi:currency-usd",
device_class=SensorDeviceClass.MONETARY,
state_class=SensorStateClass.MEASUREMENT,
),
)

VARIABLE_PRICE_SENSORS: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key="variable_price_power",
name="Power variable",
icon="mdi:currency-usd",
device_class=SensorDeviceClass.POWER,
),
SensorEntityDescription(
key="variable_price_level",
name="Price level variable",
icon="mdi:currency-usd",
),
)
VARIABLE_PRICE_PRICE_SENSORS: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key="variable_price_total",
name="Price variable total",
icon="mdi:currency-usd",
device_class=SensorDeviceClass.MONETARY,
state_class=SensorStateClass.MEASUREMENT,
),
SensorEntityDescription(
key="variable_price_taxes",
name="Price variable taxes",
icon="mdi:currency-usd",
device_class=SensorDeviceClass.MONETARY,
state_class=SensorStateClass.MEASUREMENT,
),
SensorEntityDescription(
key="variable_price_energy",
name="Price variable energy",
icon="mdi:currency-usd",
device_class=SensorDeviceClass.MONETARY,
state_class=SensorStateClass.MEASUREMENT,
key="test",
name="Test sensor",
),
)

Expand All @@ -90,12 +29,8 @@ async def async_setup_entry(
"""Add sensor entities from a config_entry."""

coordinator: ElviaDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]

async_add_entities(ElviaFixedPriceSensor(coordinator, description) for description in FIXED_PRICE_SENSORS)
async_add_entities(ElviaFixedPricePriceSensor(coordinator, description) for description in FIXED_PRICE_PRICE_SENSORS)
async_add_entities(ElviaVariablePriceSensor(coordinator, description) for description in VARIABLE_PRICE_SENSORS)
async_add_entities(ElviaVariablePricePriceSensor(coordinator, description) for description in VARIABLE_PRICE_PRICE_SENSORS)

async_add_entities(ElviaSensor(coordinator, description) for description in SENSORS)

class ElviaSensor(CoordinatorEntity, SensorEntity):
"""Define a Elvia entity."""
Expand Down Expand Up @@ -132,51 +67,3 @@ def _handle_coordinator_update(self) -> None:

self.update_from_data()
super()._handle_coordinator_update()

class ElviaVariablePriceSensor(ElviaSensor):

def update_from_data(self) -> None:
key = self.entity_description.key
variablePrice = self.coordinator.variablePrice
attribute = key.replace("variable_price_", "")

self.sensor_data = variablePrice.__getattribute__(attribute)

class ElviaVariablePricePriceSensor(ElviaSensor):

def update_from_data(self) -> None:
key = self.entity_description.key
variablePrice = self.coordinator.variablePrice
attribute = key.replace("variable_price_", "")

self.sensor_data = float(variablePrice.__getattribute__(attribute))

@property
def native_unit_of_measurement(self) -> str or None:
"""Return the unit of measurement of the sensor, if any."""
return self.coordinator.variablePrice.uom

class ElviaFixedPriceSensor(ElviaSensor):

def update_from_data(self) -> None:
key = self.entity_description.key
priceLevel = self.coordinator.fixedPriceLevel
attribute = key.replace("fixed_price_", "")

self.sensor_data = priceLevel.__getattribute__(attribute)

class ElviaFixedPricePriceSensor(ElviaSensor):

def update_from_data(self) -> None:

key = self.entity_description.key
priceLevel = self.coordinator.fixedPriceLevel
attribute = key.replace("fixed_price_", "")

self.sensor_data = float(priceLevel.__getattribute__(attribute))

@property
def native_unit_of_measurement(self) -> str or None:
"""Return the unit of measurement of the sensor, if any."""

return self.coordinator.fixedPriceLevel.uom

0 comments on commit 60e3d19

Please sign in to comment.