Skip to content

Commit 14e14f6

Browse files
committed
Change validation type from float to int - move flexible tariff next query time calculation
1 parent 6110806 commit 14e14f6

4 files changed

Lines changed: 34 additions & 32 deletions

File tree

packages/control/optional_data.py

Lines changed: 1 addition & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,10 @@
11
from dataclasses import dataclass, field
2-
from datetime import datetime, timedelta
3-
import random
42
from typing import Dict, Optional, Protocol
53

64
from dataclass_utils.factories import empty_dict_factory
75
from helpermodules.constants import NO_ERROR
8-
from helpermodules.pub import Pub
96
from modules.display_themes.cards.config import CardsDisplayTheme
107

11-
# Stunden für tägliche Tarifaktualisierung, manche Anbieter aktualisieren mehrfach täglich
12-
TARIFF_UPDATE_HOURS = [2, 8, 14, 20]
13-
148

159
@dataclass
1610
class PricingGet:
@@ -56,7 +50,7 @@ def get_grid_fee_factory() -> GridFee:
5650

5751
@dataclass
5852
class ElectricityPricingGet:
59-
next_query_time: Optional[float] = field(default=None, metadata={"topic": "ep/next_query_time"})
53+
next_query_time: Optional[int] = field(default=None, metadata={"topic": "ep/next_query_time"})
6054
_prices: Dict = field(default_factory=empty_dict_factory, metadata={"topic": "ep/prices"})
6155

6256
@property
@@ -66,23 +60,6 @@ def prices(self) -> Dict:
6660
@prices.setter
6761
def prices(self, value: Dict):
6862
self._prices = value
69-
if value:
70-
now = datetime.now()
71-
current_hour = now.hour
72-
next_hour = None
73-
for hour in TARIFF_UPDATE_HOURS:
74-
if hour > current_hour:
75-
next_hour = hour
76-
break
77-
# Wenn keine Stunde heute gefunden, nimm die erste Stunde vom nächsten Tag
78-
if next_hour is None:
79-
next_hour = TARIFF_UPDATE_HOURS[0]
80-
next_query_time = (now + timedelta(days=1)).replace(hour=next_hour, minute=0, second=0, microsecond=0)
81-
else:
82-
next_query_time = now.replace(hour=next_hour, minute=0, second=0, microsecond=0)
83-
# reduce serverload on their site by trying early and randomizing query time
84-
next_query_time += timedelta(minutes=random.randint(1, 7) * -5)
85-
Pub().pub("openWB/set/optional/ep/get/next_query_time", next_query_time.timestamp())
8663

8764

8865
def electricity_pricing_get_factory() -> ElectricityPricingGet:

packages/helpermodules/setdata.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -861,7 +861,7 @@ def process_optional_topic(self, msg: mqtt.MQTTMessage):
861861
elif "openWB/set/optional/ep/get/prices" in msg.topic:
862862
self._validate_value(msg, "json")
863863
elif "openWB/set/optional/ep/get/next_query_time" in msg.topic:
864-
self._validate_value(msg, float)
864+
self._validate_value(msg, int)
865865
elif "openWB/set/optional/ep/configured" in msg.topic:
866866
self._validate_value(msg, bool)
867867
elif "module_update_completed" in msg.topic:

packages/modules/common/configurable_tariff.py

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,22 @@
1+
from datetime import datetime, timedelta
2+
import random
13
from typing import TypeVar, Generic, Callable
24
from helpermodules import timecheck
35
import logging
6+
from helpermodules.pub import Pub
47
from modules.common import store
58
from modules.common.component_context import SingleComponentUpdateContext
69
from modules.common.component_state import TariffState
710
from modules.common.component_type import ComponentType
811
from modules.common.fault_state import ComponentInfo, FaultState
912

1013

14+
# Stunden für tägliche Tarifaktualisierung, manche Anbieter aktualisieren mehrfach täglich
15+
TARIFF_UPDATE_HOURS = [2, 8, 14, 20]
1116
T_TARIFF_CONFIG = TypeVar("T_TARIFF_CONFIG")
1217
TARIFF_UPDATE_HOUR = 14 # latest expected time for daily tariff update
1318
ONE_HOUR_SECONDS: int = 3600
19+
1420
log = logging.getLogger(__name__)
1521

1622

@@ -28,17 +34,36 @@ def __init__(self,
2834

2935
def update(self) -> None:
3036
if hasattr(self, "_component_updater"):
31-
with SingleComponentUpdateContext(self.fault_state):
32-
tariff_state, timeslot_length_seconds = self.__update_et_provider_data()
33-
self.__store_and_publish_updated_data(tariff_state)
34-
self.__log_and_publish_progress(timeslot_length_seconds, tariff_state)
37+
try:
38+
with SingleComponentUpdateContext(self.fault_state):
39+
tariff_state, timeslot_length_seconds = self.__update_et_provider_data()
40+
self.__store_and_publish_updated_data(tariff_state)
41+
self.__log_and_publish_progress(timeslot_length_seconds, tariff_state)
42+
except Exception as e:
43+
log.exception(f"Fehler beim Aktualisieren der Tarifdaten {e}")
44+
self.fault_state.warning("Error updating tariff data, retry in 5 minutes")
3545

3646
def __update_et_provider_data(self) -> tuple[TariffState, int]:
37-
tariff_state = self._component_updater()
47+
tariff_state = self.__call_component_updater()
3848
timeslot_length_seconds = self.__calculate_price_timeslot_length(tariff_state)
3949
tariff_state = self._remove_outdated_prices(tariff_state, timeslot_length_seconds)
4050
return tariff_state, timeslot_length_seconds
4151

52+
def __calculate_next_query_time(self) -> float:
53+
now = datetime.now()
54+
current_hour = now.hour
55+
next_hour = min([hour for hour in TARIFF_UPDATE_HOURS
56+
if hour > current_hour], default=TARIFF_UPDATE_HOURS[0])
57+
# reduce serverload on their site by trying early and randomizing query time minutes and seconds
58+
next_query_time = (now.replace(hour=next_hour, minute=0, second=0, microsecond=0) +
59+
timedelta(days=1, minutes=random.randint(1, 35) * -1, seconds=random.randint(0, 5) * 10))
60+
Pub().pub("openWB/set/optional/ep/get/next_query_time", int(next_query_time.timestamp()))
61+
62+
def __call_component_updater(self) -> TariffState:
63+
tariff_state = self._component_updater()
64+
self.__calculate_next_query_time()
65+
return tariff_state
66+
4267
def __log_and_publish_progress(self, timeslot_length_seconds, tariff_state):
4368
def publish_info(message_extension: str) -> None:
4469
self.fault_state.no_error(

packages/modules/common/store/_tariff.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,8 @@ def sum_prices(self):
5858
grid_fee_prices = data.data.optional_data.data.electricity_pricing.grid_fee.get.prices
5959
if len(grid_fee_prices) == 0 and data.data.optional_data.grid_fee_module is not None:
6060
raise ValueError("Keine Preise für konfigurierten Netzentgelttarif vorhanden.")
61-
flexible_tariff_prices = {float(k): v for k, v in flexible_tariff_prices.items()}
62-
grid_fee_prices = {float(k): v for k, v in grid_fee_prices.items()}
61+
flexible_tariff_prices = {int(float(k)): v for k, v in flexible_tariff_prices.items()}
62+
grid_fee_prices = {int(float(k)): v for k, v in grid_fee_prices.items()}
6363
if len(flexible_tariff_prices) == 0 and len(grid_fee_prices) > 0:
6464
return grid_fee_prices
6565
if len(grid_fee_prices) == 0 and len(flexible_tariff_prices) > 0:

0 commit comments

Comments
 (0)