innergrid 0.2.0__tar.gz → 0.3.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: innergrid
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Asynchronous Python client for the energy and building data that Innergrid publishes over MQTT.
5
5
  Keywords: async,client,energy,mqtt,innergrid
6
6
  Author: Robbin Janssen
@@ -17,6 +17,7 @@ Classifier: Programming Language :: Python :: 3.13
17
17
  Classifier: Programming Language :: Python :: 3.14
18
18
  Classifier: Programming Language :: Python :: 3
19
19
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Dist: aiohttp>=3.9.0
20
21
  Requires-Dist: aiomqtt>=2.0.0
21
22
  Maintainer: Robbin Janssen
22
23
  Maintainer-email: Robbin Janssen <robbinjanssen@gmail.com>
@@ -74,6 +75,27 @@ broker rejects the login and `InnergridConnectionError` when the connection
74
75
  fails or is lost. `wait_for_data()` raises `InnergridTimeoutError` when no
75
76
  data arrives in time.
76
77
 
78
+ ## REST API
79
+
80
+ The edge server also has a REST API, with what MQTT lacks: the names of the
81
+ spaces, and changing the session of a charge point. `InnergridApi` logs in
82
+ with an e-mail address and password of a user of the edge server, and logs in
83
+ again when the API rejects the token.
84
+
85
+ ```python
86
+ from innergrid import ChargeStrategy, InnergridApi
87
+
88
+ async with InnergridApi("http://192.0.2.10:31679/hook/api", email, password) as api:
89
+ spaces = await api.spaces()
90
+ await api.set_charge_point_session(
91
+ "19463", charge_strategy=ChargeStrategy.DIRECT_CHARGING, target_energy=30
92
+ )
93
+ ```
94
+
95
+ `set_charge_point_session` changes only the values that are given: the
96
+ charging strategy, the target energy (kWh), the departure time, the user and
97
+ whether the session is claimed.
98
+
77
99
  ## Topics
78
100
 
79
101
  | Topic | Model |
@@ -44,6 +44,27 @@ broker rejects the login and `InnergridConnectionError` when the connection
44
44
  fails or is lost. `wait_for_data()` raises `InnergridTimeoutError` when no
45
45
  data arrives in time.
46
46
 
47
+ ## REST API
48
+
49
+ The edge server also has a REST API, with what MQTT lacks: the names of the
50
+ spaces, and changing the session of a charge point. `InnergridApi` logs in
51
+ with an e-mail address and password of a user of the edge server, and logs in
52
+ again when the API rejects the token.
53
+
54
+ ```python
55
+ from innergrid import ChargeStrategy, InnergridApi
56
+
57
+ async with InnergridApi("http://192.0.2.10:31679/hook/api", email, password) as api:
58
+ spaces = await api.spaces()
59
+ await api.set_charge_point_session(
60
+ "19463", charge_strategy=ChargeStrategy.DIRECT_CHARGING, target_energy=30
61
+ )
62
+ ```
63
+
64
+ `set_charge_point_session` changes only the values that are given: the
65
+ charging strategy, the target energy (kWh), the departure time, the user and
66
+ whether the session is claimed.
67
+
47
68
  ## Topics
48
69
 
49
70
  | Topic | Model |
@@ -1,5 +1,6 @@
1
1
  """Asynchronous Python client for the energy data that Innergrid publishes."""
2
2
 
3
+ from .api import ChargeStrategy, InnergridApi, SpaceInfo
3
4
  from .const import CONNECTED_STATUSES, DEFAULT_PORT, Kind
4
5
  from .exceptions import (
5
6
  InnergridAuthError,
@@ -40,10 +41,12 @@ __all__ = [
40
41
  "Category",
41
42
  "ChargePoint",
42
43
  "ChargePointEvent",
44
+ "ChargeStrategy",
43
45
  "Circuit",
44
46
  "ElectricityMeter",
45
47
  "EnergyManager",
46
48
  "Innergrid",
49
+ "InnergridApi",
47
50
  "InnergridAuthError",
48
51
  "InnergridConnectionError",
49
52
  "InnergridError",
@@ -56,6 +59,7 @@ __all__ = [
56
59
  "Site",
57
60
  "SiteMeter",
58
61
  "Space",
62
+ "SpaceInfo",
59
63
  "SystemStatus",
60
64
  "Update",
61
65
  "parse_data",
@@ -0,0 +1,262 @@
1
+ """Asynchronous client for the REST API of the Loqio edge server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from dataclasses import dataclass
7
+ from datetime import UTC, datetime
8
+ from enum import StrEnum
9
+ from typing import TYPE_CHECKING, Any, Self
10
+
11
+ from aiohttp import ClientError, ClientResponseError, ClientSession, hdrs
12
+
13
+ from .exceptions import (
14
+ InnergridAuthError,
15
+ InnergridConnectionError,
16
+ InnergridError,
17
+ InnergridTimeoutError,
18
+ )
19
+ from .models import ChargePoint
20
+
21
+ if TYPE_CHECKING:
22
+ from types import TracebackType
23
+
24
+
25
+ class ChargeStrategy(StrEnum):
26
+ """The charging strategy of a charge point session."""
27
+
28
+ SMART_CHARGING = "SMART_CHARGING"
29
+ """Charge towards the target energy by the departure time."""
30
+ DIRECT_CHARGING = "DIRECT_CHARGING"
31
+ """Charge at maximum power."""
32
+ SOLAR_CHARGING = "SOLAR_CHARGING"
33
+ """Charge with surplus (solar) power."""
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class SpaceInfo:
38
+ """A space of the building, such as a room or a floor."""
39
+
40
+ id: str
41
+ name: str
42
+ type: str | None
43
+ parent_id: str | None
44
+
45
+ @classmethod
46
+ def from_dict(cls, data: dict[str, Any]) -> Self:
47
+ """Parse a space of GET /spaces."""
48
+ parent = data.get("parentId")
49
+ return cls(
50
+ id=str(data["id"]),
51
+ name=str(data.get("name") or data["id"]).strip(),
52
+ type=data.get("type"),
53
+ parent_id=None if parent is None else str(parent),
54
+ )
55
+
56
+
57
+ class InnergridApi:
58
+ """The REST API of a Loqio edge server.
59
+
60
+ Logs in with an e-mail address and password, and logs in again when the
61
+ API rejects the token. Most data is also published over MQTT; the REST API
62
+ adds what MQTT lacks, such as the names of the spaces, and lets the
63
+ charge point sessions be changed.
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ url: str,
69
+ email: str,
70
+ password: str,
71
+ *,
72
+ session: ClientSession | None = None,
73
+ request_timeout: float = 10.0,
74
+ ) -> None:
75
+ """Initialise the client.
76
+
77
+ Args:
78
+ ----
79
+ url: The base URL of the API, for example
80
+ http://10.50.20.150:31679/hook/api.
81
+ email: The e-mail address of a user of the edge server.
82
+ password: The password of the user.
83
+ session: The aiohttp session to use, or a new one is created.
84
+ request_timeout: Seconds to wait for a response.
85
+
86
+ """
87
+ self.url = url.rstrip("/")
88
+ self.email = email
89
+ self.password = password
90
+ self.request_timeout = request_timeout
91
+ self._session = session
92
+ self._close_session = False
93
+ self._token: str | None = None
94
+
95
+ async def _request(
96
+ self,
97
+ method: str,
98
+ path: str,
99
+ *,
100
+ body: dict[str, Any] | None = None,
101
+ token: str | None = None,
102
+ ) -> Any:
103
+ """Send a request and return the JSON of the response.
104
+
105
+ Raises
106
+ ------
107
+ ClientResponseError: The API returned an HTTP error.
108
+ InnergridTimeoutError: The API did not respond in time.
109
+ InnergridConnectionError: The API could not be reached.
110
+
111
+ """
112
+ if self._session is None:
113
+ self._session = ClientSession()
114
+ self._close_session = True
115
+ headers = {"Accept": "application/json"}
116
+ if token is not None:
117
+ headers["Authorization"] = f"Bearer {token}"
118
+ try:
119
+ async with asyncio.timeout(self.request_timeout):
120
+ response = await self._session.request(
121
+ method, f"{self.url}{path}", json=body, headers=headers
122
+ )
123
+ response.raise_for_status()
124
+ return await response.json(content_type=None)
125
+ except ClientResponseError:
126
+ raise
127
+ except TimeoutError as err:
128
+ msg = f"Timeout while connecting to {self.url}"
129
+ raise InnergridTimeoutError(msg) from err
130
+ except (ClientError, ValueError) as err:
131
+ msg = f"Error while connecting to {self.url}: {err}"
132
+ raise InnergridConnectionError(msg) from err
133
+
134
+ async def login(self) -> None:
135
+ """Log in and keep the token.
136
+
137
+ Raises
138
+ ------
139
+ InnergridAuthError: The e-mail address or password is wrong.
140
+ InnergridConnectionError: The API could not be reached.
141
+
142
+ """
143
+ try:
144
+ result = await self._request(
145
+ hdrs.METH_POST,
146
+ "/login",
147
+ body={"email": self.email, "password": self.password},
148
+ )
149
+ except ClientResponseError as err:
150
+ if err.status in (401, 403):
151
+ msg = "The edge server rejected the e-mail address or password"
152
+ raise InnergridAuthError(msg) from err
153
+ msg = f"Login failed: HTTP {err.status}"
154
+ raise InnergridConnectionError(msg) from err
155
+ if not isinstance(result, dict) or not result.get("token"):
156
+ msg = "The edge server returned no token"
157
+ raise InnergridError(msg)
158
+ self._token = result["token"]
159
+
160
+ async def request(
161
+ self, method: str, path: str, *, body: dict[str, Any] | None = None
162
+ ) -> Any:
163
+ """Send an authenticated request, logging in (again) when needed.
164
+
165
+ Raises
166
+ ------
167
+ InnergridAuthError: The login was rejected.
168
+ InnergridConnectionError: The API could not be reached or
169
+ returned an error.
170
+
171
+ """
172
+ for attempt in (1, 2):
173
+ if self._token is None:
174
+ await self.login()
175
+ try:
176
+ return await self._request(method, path, body=body, token=self._token)
177
+ except ClientResponseError as err:
178
+ if err.status == 401 and attempt == 1:
179
+ # The token expired or was revoked; log in again once.
180
+ self._token = None
181
+ continue
182
+ msg = f"{method} {path} failed: HTTP {err.status} {err.message}"
183
+ raise InnergridConnectionError(msg) from err
184
+ msg = "The edge server rejected the token after logging in again"
185
+ raise InnergridAuthError(msg)
186
+
187
+ async def spaces(self) -> list[SpaceInfo]:
188
+ """Return the spaces of the building, parents before their children."""
189
+ result = await self.request(hdrs.METH_GET, "/spaces")
190
+ items = result if isinstance(result, list) else []
191
+ return [SpaceInfo.from_dict(item) for item in items if isinstance(item, dict)]
192
+
193
+ async def set_charge_point_session( # noqa: PLR0913 # pylint: disable=too-many-arguments
194
+ self,
195
+ charge_point_id: str,
196
+ *,
197
+ charge_strategy: ChargeStrategy | None = None,
198
+ target_energy: int | None = None,
199
+ departure_at: datetime | None = None,
200
+ username: str | None = None,
201
+ claimed: bool | None = None,
202
+ ) -> ChargePoint:
203
+ """Change the session of a charge point; only the given values change.
204
+
205
+ Args:
206
+ ----
207
+ charge_point_id: The ID of the charge point.
208
+ charge_strategy: The charging strategy.
209
+ target_energy: The energy to charge in the session, in kWh.
210
+ departure_at: The planned departure time.
211
+ username: The user of the session.
212
+ claimed: Whether a user claimed the session.
213
+
214
+ Returns:
215
+ -------
216
+ The charge point with the updated session; its other values are
217
+ not known (None).
218
+
219
+ """
220
+ body: dict[str, Any] = {}
221
+ if charge_strategy is not None:
222
+ body["chargeStrategy"] = ChargeStrategy(charge_strategy).value
223
+ if target_energy is not None:
224
+ body["energyChargeTarget"] = int(target_energy)
225
+ if departure_at is not None:
226
+ if departure_at.tzinfo is None:
227
+ msg = "The departure time needs a time zone"
228
+ raise ValueError(msg)
229
+ utc = departure_at.astimezone(UTC).replace(microsecond=0)
230
+ body["departureTime"] = utc.isoformat().replace("+00:00", "Z")
231
+ if username is not None:
232
+ body["username"] = username
233
+ if claimed is not None:
234
+ body["isClaimed"] = claimed
235
+ if not body:
236
+ msg = "Nothing to change"
237
+ raise ValueError(msg)
238
+ session = await self.request(
239
+ hdrs.METH_POST, f"/chargepoints/{charge_point_id}", body=body
240
+ )
241
+ return ChargePoint.from_dict(
242
+ {"session": session if isinstance(session, dict) else {}},
243
+ str(charge_point_id),
244
+ )
245
+
246
+ async def close(self) -> None:
247
+ """Close the session, when the client created it."""
248
+ if self._session is not None and self._close_session:
249
+ await self._session.close()
250
+
251
+ async def __aenter__(self) -> Self:
252
+ """Return the client for use as a context manager."""
253
+ return self
254
+
255
+ async def __aexit__(
256
+ self,
257
+ exc_type: type[BaseException] | None,
258
+ exc_value: BaseException | None,
259
+ traceback: TracebackType | None,
260
+ ) -> None:
261
+ """Close the session."""
262
+ await self.close()
@@ -362,6 +362,7 @@ class ChargePoint:
362
362
  charging_state: str | None
363
363
  charge_strategy: str | None
364
364
  username: str | None
365
+ claimed: bool | None
365
366
  started_at: datetime | None
366
367
  finished_at: datetime | None
367
368
  departure_at: datetime | None
@@ -414,6 +415,7 @@ class ChargePoint:
414
415
  charging_state=_text(get_path(data, "session.chargingState")),
415
416
  charge_strategy=_text(get_path(data, "session.chargeStrategy")),
416
417
  username=_text(get_path(data, "session.username")),
418
+ claimed=_bool(get_path(data, "session.isClaimed")),
417
419
  started_at=_timestamp(get_path(data, "session.startedAt")),
418
420
  finished_at=_timestamp(get_path(data, "session.finishedAt")),
419
421
  departure_at=_timestamp(get_path(data, "session.departureAt")),
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "innergrid"
3
- version = "0.2.0"
3
+ version = "0.3.0"
4
4
  description = "Asynchronous Python client for the energy and building data that Innergrid publishes over MQTT."
5
5
  license = "MIT"
6
6
  license-files = ["LICENSE"]
@@ -25,7 +25,10 @@ classifiers = [
25
25
  "Topic :: Software Development :: Libraries :: Python Modules",
26
26
  ]
27
27
  requires-python = ">=3.11"
28
- dependencies = ["aiomqtt>=2.0.0"]
28
+ dependencies = [
29
+ "aiohttp>=3.9.0",
30
+ "aiomqtt>=2.0.0",
31
+ ]
29
32
 
30
33
  [[project.authors]]
31
34
  name = "Robbin Janssen"
@@ -44,6 +47,7 @@ Changelog = "https://github.com/robbinjanssen/python-innergrid/releases"
44
47
 
45
48
  [dependency-groups]
46
49
  dev = [
50
+ "aresponses==3.0.0",
47
51
  "codespell==2.4.3",
48
52
  "covdefaults==2.3.0",
49
53
  "coverage[toml]==7.16.2",
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "innergrid"
3
3
  # The version is set from the release tag by the release workflow.
4
- version = "0.2.0"
4
+ version = "0.3.0"
5
5
  description = "Asynchronous Python client for the energy and building data that Innergrid publishes over MQTT."
6
6
  authors = [{ name = "Robbin Janssen", email = "robbinjanssen@gmail.com" }]
7
7
  maintainers = [{ name = "Robbin Janssen", email = "robbinjanssen@gmail.com" }]
@@ -23,6 +23,7 @@ classifiers = [
23
23
  ]
24
24
  requires-python = ">=3.11"
25
25
  dependencies = [
26
+ "aiohttp>=3.9.0",
26
27
  "aiomqtt>=2.0.0",
27
28
  ]
28
29
 
@@ -35,6 +36,7 @@ Changelog = "https://github.com/robbinjanssen/python-innergrid/releases"
35
36
 
36
37
  [dependency-groups]
37
38
  dev = [
39
+ "aresponses==3.0.0",
38
40
  "codespell==2.4.3",
39
41
  "covdefaults==2.3.0",
40
42
  "coverage[toml]==7.16.2",
File without changes
File without changes
File without changes