|
2 | 2 | import datetime |
3 | 3 | import logging |
4 | 4 | from typing import Dict |
5 | | -from requests.exceptions import HTTPError |
6 | 5 |
|
7 | | -from helpermodules.utils.error_handling import ImportErrorContext |
8 | | -with ImportErrorContext(): |
9 | | - import pytz |
10 | | - |
11 | | -from dataclass_utils import asdict |
12 | | -from helpermodules import timecheck |
13 | | -from helpermodules.pub import Pub |
14 | 6 | from modules.common import req |
15 | 7 | from modules.common.abstract_device import DeviceDescriptor |
16 | 8 | from modules.common.component_state import TariffState |
17 | | -from modules.electricity_pricing.flexible_tariffs.rabot.config import RabotTariff, RabotToken |
| 9 | +from modules.electricity_pricing.flexible_tariffs.rabot.config import RabotTariff |
18 | 10 |
|
19 | 11 | log = logging.getLogger(__name__) |
20 | 12 |
|
21 | 13 |
|
22 | | -def validate_token(config: RabotTariff) -> None: |
23 | | - if config.configuration.token.expires_in: |
24 | | - expiration = config.configuration.token.created_at + config.configuration.token.expires_in |
25 | | - log.debug("No need to authenticate. Valid token already present.") |
26 | | - if timecheck.create_timestamp() > expiration: |
27 | | - log.debug("Access token expired. Refreshing token.") |
28 | | - _refresh_token(config) |
29 | | - else: |
30 | | - _refresh_token(config) |
31 | | - |
32 | | - |
33 | | -def _refresh_token(config: RabotTariff): |
34 | | - data = { |
35 | | - 'client_id': {config.configuration.client_id}, |
36 | | - 'client_secret': {config.configuration.client_secret}, |
37 | | - 'grant_type': 'client_credentials', |
38 | | - 'scope': 'openid offline_access api:hems', |
39 | | - } |
40 | | - response = req.get_http_session().post( |
41 | | - 'https://auth.rabot-charge.de/connect/token?client_id=&client_secret=&username=&password=&scope=*&' |
42 | | - + 'grant_type=client_credentials', data=data).json() |
43 | | - config.configuration.token = RabotToken(access_token=response["access_token"], |
44 | | - expires_in=response["expires_in"], |
45 | | - created_at=timecheck.create_timestamp()) |
46 | | - Pub().pub("openWB/set/optional/ep/flexible_tariff/provider", asdict(config)) |
47 | | - |
48 | | - |
49 | 14 | def fetch(config: RabotTariff) -> None: |
50 | | - def get_raw_prices(): |
51 | | - return req.get_http_session().get( |
52 | | - "https://api.rabot-charge.de/hems/v1/day-ahead-prices/limited", |
53 | | - headers={"Content-Type": "application/json", |
54 | | - "Authorization": f'Bearer {config.configuration.token.access_token}'}, |
55 | | - params={"from": start_date, "tz": timezone} |
56 | | - ).json()["records"] |
57 | | - |
58 | | - validate_token(config) |
59 | | - # ToDo: get rid of hard coded timezone! |
60 | | - # start_date von voller Stunde sonst liefert die API die nächste Stunde |
61 | | - start_date = datetime.datetime.fromtimestamp( |
62 | | - timecheck.create_unix_timestamp_current_full_hour()).astimezone( |
63 | | - pytz.timezone("Europe/Berlin")).isoformat(sep="T", timespec="seconds") |
64 | | - if datetime.datetime.today().astimezone(pytz.timezone("Europe/Berlin")).dst().total_seconds()/3600: |
65 | | - # Sommerzeit |
66 | | - timezone = "UTC+2:00" |
67 | | - else: |
68 | | - timezone = "UTC+1:00" |
69 | | - try: |
70 | | - raw_prices = get_raw_prices() |
71 | | - except HTTPError as error: |
72 | | - if error.response.status_code == 401: |
73 | | - _refresh_token(config) |
74 | | - raw_prices = get_raw_prices() |
75 | | - else: |
76 | | - raise error |
| 15 | + raw_prices = req.get_http_session().get( |
| 16 | + f"https://rabot.openwb.de/rabot-proxy.php/customers/{config.configuration.customer_number}" |
| 17 | + f"/contracts/{config.configuration.contract_number}/metrics", |
| 18 | + timeout=15 |
| 19 | + ).json()["data"]["records"] |
77 | 20 | prices: Dict[int, float] = {} |
78 | 21 | for data in raw_prices: |
79 | | - formatted_price = data["priceInCentPerKwh"]/100000 # Cent/kWh -> €/Wh |
80 | | - timestamp = datetime.datetime.fromisoformat(data["timestamp"]).astimezone( |
81 | | - pytz.timezone("Europe/Berlin")).timestamp() |
| 22 | + formatted_price = data["value"] / 100000 # ct/kWh -> €/Wh |
| 23 | + timestamp = datetime.datetime.strptime(data["moment"], "%Y-%m-%d %H:%M").timestamp() |
82 | 24 | prices.update({str(int(timestamp)): formatted_price}) |
83 | 25 | return prices |
84 | 26 |
|
85 | 27 |
|
86 | 28 | def create_electricity_tariff(config: RabotTariff): |
87 | | - validate_token(config) |
88 | | - |
89 | 29 | def updater(): |
90 | 30 | return TariffState(prices=fetch(config)) |
91 | 31 | return updater |
|
0 commit comments