Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
magnuselden authored and magnuselden committed Jul 21, 2023
1 parent 5806e20 commit 8e98651
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 24 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from dataclasses import dataclass, field

from datetime import date, timedelta

@dataclass
class NordPoolModel:
Expand All @@ -8,7 +8,7 @@ class NordPoolModel:
prices_tomorrow: list = field(default_factory=lambda: [])
state: float = 0
nordpool_entity: str = ""
average_data: list = field(default_factory=lambda: [])
average_data: dict = field(default_factory=lambda: {})
average_month: float = 0
average_weekly: float = 0
average_three_days: float = 0
Expand All @@ -18,6 +18,18 @@ class NordPoolModel:
dynamic_top_price_type: str = ""
dynamic_top_price: float|None = None

async def async_create_date_dict(self, numbers: dict[date,float]|list[float]) -> dict[date, float]:
if isinstance(numbers, dict):
return numbers
today = date.today()
delta = timedelta(days=len(numbers) - 1)
start_date = today - delta
ret = {}
for number in numbers:
ret[start_date] = number
start_date += timedelta(days=1)
return ret

async def fix_dst(self, val) -> list | None:
if val is None:
return None
Expand Down
35 changes: 19 additions & 16 deletions custom_components/peaqev/peaqservice/hub/nordpool/nordpool.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import asyncio
import logging
from datetime import datetime
from datetime import datetime, date
from statistics import mean

import homeassistant.helpers.template as template
Expand Down Expand Up @@ -59,7 +59,7 @@ def average_30(self) -> float:
return self.model.average_30

@property
def average_data(self) -> list:
def average_data(self) -> dict[date,float]:
return self.model.average_data

@property
Expand Down Expand Up @@ -156,7 +156,7 @@ async def async_update_set_prices(self, result: NordpoolDTO) -> bool:
async def async_update_dynamic_max_price(self):
if len(self.model.average_data) > 3:
_dynamic_max_price = await self._dynamic_top_price.async_get_max(
self.model.average_data
list(self.model.average_data.values())
)
if self.model.dynamic_top_price != _dynamic_max_price[0]:
self.model.dynamic_top_price_type = _dynamic_max_price[1].value
Expand Down Expand Up @@ -191,37 +191,40 @@ def _setup_nordpool(self):
f"Peaqev was unable to get a Nordpool-entity. Disabling Priceawareness until reboot of HA: {e}"
)

async def async_import_average_data(self, incoming: list):
if isinstance(incoming, list):
rounded_vals = [round(h, 3) for h in incoming]
if len(incoming):
self.model.average_data = rounded_vals
async def async_import_average_data(self, incoming: list|dict):
if len(incoming):
self.model.average_data = await self.model.async_create_date_dict(incoming)
await self.async_cap_average_data_length()
await self.async_update_nordpool()

async def async_add_average_data(self, new_val):
if isinstance(new_val, float):
rounded = round(new_val, 3)
if len(self.model.average_data) == 0:
self.model.average_data.append(rounded)
elif self.model.average_data[-1] != rounded:
self.model.average_data.append(rounded)
if datetime.now().date not in self.model.average_data.keys():
self.model.average_data[datetime.now().date] = rounded
# if len(self.model.average_data) == 0:
# self.model.average_data.append(rounded)
# elif self.model.average_data[-1] != rounded:
# self.model.average_data.append(rounded)
await self.async_cap_average_data_length()

async def async_cap_average_data_length(self):
while len(self.model.average_data) > AVERAGE_MAX_LEN:
del self.model.average_data[0]
min_key = min(self.model.average_data.keys())
del self.model.average_data[min_key]
#del self.model.average_data[0]

async def async_get_average(self, days: int) -> float:
try:
if len(self.model.average_data) > days:
ret = self.model.average_data[-days:]
avg_values = list(self.model.average_data.values())
ret = avg_values[-days:]
elif len(self.model.average_data) == 0:
return 0.0
else:
ret = self.model.average_data
ret = list(self.model.average_data.values())
return round(mean(ret), 2)
except Exception as e:
_LOGGER.debug(
f"Could not calculate average. indata: {self.model.average_data}, error: {e}"
f"Could not calculate average. indata: {list(self.model.average_data.values())}, error: {e}"
)
13 changes: 7 additions & 6 deletions custom_components/peaqev/sensors/money_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ def __init__(self, hub: HomeAssistantHub, entry_id):
self._max_price_based_on = None
self._average_data_current_month = None
self._charge_permittance = None
self._offsets = {}
self._average_nordpool_data = []
#self._offsets = {}
self._average_nordpool_data = {}

@property
def state(self):
Expand Down Expand Up @@ -101,8 +101,8 @@ def extra_state_attributes(self) -> dict:
"Current hour charge permittance": self._charge_permittance,
"Avg price per kWh": self._avg_cost,
"Max charge amount": self._max_charge,
"Nordpool average data": self._average_nordpool_data,
"All hours": self._all_hours,
"Nordpool average data": self._average_nordpool_data,
}
if self.hub.options.price.dynamic_top_price:
attr_dict["Max price based on"] = self._max_price_based_on
Expand All @@ -116,9 +116,10 @@ async def async_added_to_hass(self):
await self.hub.nordpool.async_import_average_data(
state.attributes.get("Nordpool average data", 50)
)
self._average_nordpool_data = list(
state.attributes.get("Nordpool average data", 50)
)
# self._average_nordpool_data = list(
# state.attributes.get("Nordpool average data", 50)
# )
self._average_nordpool_data = self.hub.nordpool.average_data
self._average_nordpool = (
f"{self.hub.nordpool.average_weekly} {self._currency}"
)
Expand Down

0 comments on commit 8e98651

Please sign in to comment.