pystromligning 0.2.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pystromligning
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Summary: Library for communicating with the Stromligning API
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -37,3 +37,32 @@ Use `set_electricity_price(None)` to clear the saved price.
37
37
 
38
38
  API documentation: https://stromligning.dk/api/docs/
39
39
 
40
+ ## Production prices
41
+
42
+ `update_production(start)` fetches sale prices for surplus production (for
43
+ example solar) from `/prices/production` for the grid supplier found by
44
+ `set_location()`, and stores them in `production_prices`. It uses the same
45
+ aggregation and forecast settings as `update()`. Each price is the spot price
46
+ excluding VAT, less Energinet's and the grid supplier's production tariffs; the
47
+ tariff deductions and their VAT are negative values.
48
+
49
+ `set_location()` also stores the electricity companies' production agreements
50
+ in `available_production_agreements`, apart from `available_companies`. After
51
+ `set_production_agreement(product_id)` the sale prices are also less that
52
+ company's deduction, given in `details.surcharge`. Use
53
+ `set_production_agreement(None)` to leave it out again.
54
+
55
+ ## User-Agent and API key
56
+
57
+ `Stromligning(dev=False, api_key=None, user_agent=None)`:
58
+
59
+ - `user_agent` identifies your application, for example `"MyApp/1.0"`. The
60
+ library appends its own name and version, so requests are sent with
61
+ `User-Agent: MyApp/1.0 pystromligning/<version>`. Without it the User-Agent is
62
+ `pystromligning/<version>`.
63
+ - `api_key` is optional and sent as `Authorization: Bearer <key>`. Create a key
64
+ at https://stromligning.dk/bruger/api-noegler. Requests with a key are rate
65
+ limited per key instead of per IP address. Use `set_api_key(None)` to clear it.
66
+ A rejected key (HTTP 401) raises `InvalidAPIKey`, a subclass of
67
+ `InvalidAPIResponse`. The key is never logged.
68
+
@@ -0,0 +1,48 @@
1
+ ![Buy Me A Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)
2
+
3
+ ## pyStromligning
4
+
5
+ This is a PyPI module for communicating with the Stromligning API, primarily developed for use with [Home Assistant](https://home-assistant.io), but I try to keep it as widely usable as possible.
6
+ ## Fixed-price products
7
+
8
+ `available_companies` includes each product's `productType` (`fixed` or `variable`).
9
+ For fixed-price products, call `set_electricity_price(price)` with the customer's
10
+ agreed electricity price in kr/kWh **excluding VAT** before `update()`. The price
11
+ is sent as the documented `electricityPrice` parameter. Zero is supported;
12
+ negative, non-finite and non-numeric values are rejected. A missing price raises
13
+ `FixedPriceRequired` before a network request is made.
14
+
15
+ The catalogue's current `fixedPrice` is not used as the customer's agreed price.
16
+ Variable products omit `electricityPrice`, even if a price was previously set.
17
+ Use `set_electricity_price(None)` to clear the saved price.
18
+
19
+ API documentation: https://stromligning.dk/api/docs/
20
+
21
+ ## Production prices
22
+
23
+ `update_production(start)` fetches sale prices for surplus production (for
24
+ example solar) from `/prices/production` for the grid supplier found by
25
+ `set_location()`, and stores them in `production_prices`. It uses the same
26
+ aggregation and forecast settings as `update()`. Each price is the spot price
27
+ excluding VAT, less Energinet's and the grid supplier's production tariffs; the
28
+ tariff deductions and their VAT are negative values.
29
+
30
+ `set_location()` also stores the electricity companies' production agreements
31
+ in `available_production_agreements`, apart from `available_companies`. After
32
+ `set_production_agreement(product_id)` the sale prices are also less that
33
+ company's deduction, given in `details.surcharge`. Use
34
+ `set_production_agreement(None)` to leave it out again.
35
+
36
+ ## User-Agent and API key
37
+
38
+ `Stromligning(dev=False, api_key=None, user_agent=None)`:
39
+
40
+ - `user_agent` identifies your application, for example `"MyApp/1.0"`. The
41
+ library appends its own name and version, so requests are sent with
42
+ `User-Agent: MyApp/1.0 pystromligning/<version>`. Without it the User-Agent is
43
+ `pystromligning/<version>`.
44
+ - `api_key` is optional and sent as `Authorization: Bearer <key>`. Create a key
45
+ at https://stromligning.dk/bruger/api-noegler. Requests with a key are rate
46
+ limited per key instead of per IP address. Use `set_api_key(None)` to clear it.
47
+ A rejected key (HTTP 401) raises `InvalidAPIKey`, a subclass of
48
+ `InvalidAPIResponse`. The key is never logged.
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "pystromligning"
3
- version = "0.2.0"
3
+ version = "0.4.0"
4
4
  description = "Library for communicating with the Stromligning API"
5
5
  authors = ["Malene Trab <malene@trab.dk>"]
6
6
  license = "MIT"
@@ -6,18 +6,39 @@ import logging
6
6
  import math
7
7
  import sys
8
8
  from datetime import datetime, timezone
9
+ from importlib.metadata import PackageNotFoundError, version
9
10
  from operator import itemgetter
10
11
 
11
12
  import requests
12
13
 
13
14
  from .const import API_URL, DEV_API_URL
14
- from .exceptions import FixedPriceRequired, InvalidAPIResponse, TooManyRequests
15
+ from .exceptions import (
16
+ FixedPriceRequired,
17
+ InvalidAPIKey,
18
+ InvalidAPIResponse,
19
+ TooManyRequests,
20
+ )
15
21
 
16
22
  if sys.version_info < (3, 11, 0):
17
23
  sys.exit("The pyWorxcloud module requires Python 3.11.0 or later")
18
24
 
19
25
  _LOGGER = logging.getLogger(__name__)
20
26
 
27
+ try:
28
+ LIBRARY_USER_AGENT = f"pystromligning/{version('pystromligning')}"
29
+ except PackageNotFoundError:
30
+ LIBRARY_USER_AGENT = "pystromligning"
31
+
32
+
33
+ def _midnight_utc() -> str:
34
+ """Return local midnight today as a UTC timestamp for the API."""
35
+ return (
36
+ datetime.now()
37
+ .replace(hour=0, minute=0, second=0, microsecond=0)
38
+ .astimezone(timezone.utc)
39
+ .isoformat()
40
+ ).replace("+00:00", ".000Z")
41
+
21
42
 
22
43
  class Aggregation(str):
23
44
  """Strømligning aggregation levels."""
@@ -44,21 +65,52 @@ class Stromligning:
44
65
  Results are electricity prices that takes into account the tariffs and other fees.
45
66
  """
46
67
 
47
- def __init__(self, dev: bool = False) -> None:
48
- """Initialize the :class:Stromligning class and set default attribute values."""
68
+ def __init__(
69
+ self,
70
+ dev: bool = False,
71
+ api_key: str | None = None,
72
+ user_agent: str | None = None,
73
+ ) -> None:
74
+ """Initialize the :class:Stromligning class and set default attribute values.
75
+
76
+ ``user_agent`` identifies the calling application, for example
77
+ ``"MyApp/1.0"``; the library's own name and version are appended.
78
+ ``api_key`` is sent as a bearer token when set.
79
+ """
49
80
  _LOGGER.debug("Initializing the pyStromligning library")
50
81
  self._location: dict = {}
51
82
 
52
83
  self.supplier: dict = {}
53
84
  self.available_companies: list = []
85
+ self.available_production_agreements: list = []
54
86
 
55
87
  self.prices: list = []
88
+ self.production_prices: list = []
56
89
  self.company: dict = {}
90
+ self.production_agreement: dict = {}
57
91
  self.aggregation: str = Aggregation.HOUR
58
92
  self.forecast: bool = False
59
93
  self.electricity_price: float | None = None
60
94
 
61
95
  self.dev_api: bool = dev
96
+ self._api_key: str | None = None
97
+ self.set_api_key(api_key)
98
+ self.user_agent: str = (
99
+ f"{user_agent} {LIBRARY_USER_AGENT}" if user_agent else LIBRARY_USER_AGENT
100
+ )
101
+
102
+ def set_api_key(self, api_key: str | None) -> None:
103
+ """Set or clear the API key. Empty or blank keys are treated as no key."""
104
+ if api_key is not None and not isinstance(api_key, str):
105
+ raise TypeError("API key must be a string")
106
+ self._api_key = api_key.strip() if api_key and api_key.strip() else None
107
+
108
+ def _headers(self) -> dict:
109
+ """Return request headers; the API key is never logged."""
110
+ headers = {"User-Agent": self.user_agent}
111
+ if self._api_key:
112
+ headers["Authorization"] = f"Bearer {self._api_key}"
113
+ return headers
62
114
 
63
115
  def set_forecast(self, forecast: bool) -> None:
64
116
  """Set if forecast prices should be used."""
@@ -93,6 +145,14 @@ class Stromligning:
93
145
  else:
94
146
  self.company = {}
95
147
 
148
+ def set_production_agreement(self, product_id: str | None) -> None:
149
+ """Set or clear the agreement that buys the surplus production."""
150
+ self.production_agreement = {}
151
+ for agreement in self.available_production_agreements:
152
+ if agreement["id"] == product_id:
153
+ self.production_agreement = agreement
154
+ break
155
+
96
156
  def _get_supplier(self) -> dict:
97
157
  """Get the supplier for the provided location."""
98
158
  return (
@@ -102,9 +162,13 @@ class Stromligning:
102
162
  )[0]
103
163
 
104
164
  def _get_companies(self) -> list:
105
- """Get a list of available electricity companies for the location."""
165
+ """Get a list of available electricity companies for the location.
166
+
167
+ Production agreements, which buy surplus production, are kept apart in
168
+ ``available_production_agreements``.
169
+ """
106
170
  companies = self._get_response(
107
- f"/companies?region={self.supplier['priceArea']}"
171
+ f"/companies?region={self.supplier['priceArea']}&includeProduction=true"
108
172
  )
109
173
  company_list: list = []
110
174
  for company in companies:
@@ -118,17 +182,22 @@ class Stromligning:
118
182
  }
119
183
  )
120
184
 
121
- return sorted(company_list, key=itemgetter("name"))
185
+ company_list.sort(key=itemgetter("name"))
186
+ self.available_production_agreements = [
187
+ product
188
+ for product in company_list
189
+ if product["productType"] == "production"
190
+ ]
191
+ return [
192
+ product
193
+ for product in company_list
194
+ if product["productType"] != "production"
195
+ ]
122
196
 
123
197
  def update(self, start: str | None = None) -> None:
124
198
  """Get current available prices."""
125
199
  if start is None:
126
- start = (
127
- datetime.now()
128
- .replace(hour=0, minute=0, second=0, microsecond=0)
129
- .astimezone(timezone.utc)
130
- .isoformat()
131
- ).replace("+00:00", ".000Z")
200
+ start = _midnight_utc()
132
201
 
133
202
  aggregation = ""
134
203
  if self.aggregation != Aggregation.MIN15:
@@ -163,21 +232,56 @@ class Stromligning:
163
232
 
164
233
  self.prices = price_list
165
234
 
235
+ def update_production(self, start: str | None = None) -> None:
236
+ """Get sale prices for surplus production at the selected grid supplier.
237
+
238
+ Prices are spot prices excluding VAT, less the production tariffs from
239
+ Energinet and the grid supplier. Tariff deductions are negative values.
240
+ With a production agreement set, the electricity company's deduction
241
+ is taken off as well.
242
+ """
243
+ if start is None:
244
+ start = _midnight_utc()
245
+
246
+ aggregation = ""
247
+ if self.aggregation != Aggregation.MIN15:
248
+ aggregation = "&aggregation=" + self.aggregation
249
+
250
+ url = (
251
+ f"/prices/production?supplierId={self.supplier['id']}"
252
+ f"&from={start}{aggregation}"
253
+ f"&forecast={str(self.forecast).lower()}"
254
+ )
255
+
256
+ if self.production_agreement:
257
+ url += f"&productId={self.production_agreement['id']}"
258
+
259
+ _LOGGER.debug("Fetching production prices")
260
+
261
+ price_list: list = []
262
+ for price in sorted(
263
+ (self._get_response(url))["prices"],
264
+ key=itemgetter("date"),
265
+ ):
266
+ if price not in price_list:
267
+ price_list.append(price)
268
+
269
+ self.production_prices = price_list
270
+
166
271
  def _get_response(self, path: str) -> dict:
167
272
  """Make the request to the API."""
168
273
 
169
- if not self.dev_api:
170
- response = requests.get(
171
- f"{API_URL}{path}",
172
- timeout=60,
173
- )
174
- else:
175
- response = requests.get(
176
- f"{DEV_API_URL}{path}",
177
- timeout=60,
178
- )
274
+ response = requests.get(
275
+ f"{DEV_API_URL if self.dev_api else API_URL}{path}",
276
+ headers=self._headers(),
277
+ timeout=60,
278
+ )
179
279
 
180
280
  if response.status_code != 200:
281
+ if response.status_code == 401:
282
+ raise InvalidAPIKey(
283
+ "The API key was rejected (invalid, deactivated or expired)"
284
+ )
181
285
  if response.status_code == 429:
182
286
  raise TooManyRequests(
183
287
  "Too many requests from this IP, please try again after 15 minutes"
@@ -5,6 +5,10 @@ class InvalidAPIResponse(Exception):
5
5
  """Invalid response received from the API."""
6
6
 
7
7
 
8
+ class InvalidAPIKey(InvalidAPIResponse):
9
+ """The API key was rejected because it is invalid, deactivated or expired."""
10
+
11
+
8
12
  class TooManyRequests(Exception):
9
13
  """Too many requests, try again in 15 minutes."""
10
14
 
@@ -1,19 +0,0 @@
1
- ![Buy Me A Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)
2
-
3
- ## pyStromligning
4
-
5
- This is a PyPI module for communicating with the Stromligning API, primarily developed for use with [Home Assistant](https://home-assistant.io), but I try to keep it as widely usable as possible.
6
- ## Fixed-price products
7
-
8
- `available_companies` includes each product's `productType` (`fixed` or `variable`).
9
- For fixed-price products, call `set_electricity_price(price)` with the customer's
10
- agreed electricity price in kr/kWh **excluding VAT** before `update()`. The price
11
- is sent as the documented `electricityPrice` parameter. Zero is supported;
12
- negative, non-finite and non-numeric values are rejected. A missing price raises
13
- `FixedPriceRequired` before a network request is made.
14
-
15
- The catalogue's current `fixedPrice` is not used as the customer's agreed price.
16
- Variable products omit `electricityPrice`, even if a price was previously set.
17
- Use `set_electricity_price(None)` to clear the saved price.
18
-
19
- API documentation: https://stromligning.dk/api/docs/
File without changes