aioengieromania 0.1.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.
@@ -0,0 +1,9 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ dist/
4
+ build/
5
+ .venv/
6
+ .pytest_cache/
7
+ .ruff_cache/
8
+ .coverage
9
+ uv.lock
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 coffeerunhobby
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,58 @@
1
+ Metadata-Version: 2.5
2
+ Name: aioengieromania
3
+ Version: 0.1.0
4
+ Summary: Async client for MyENGIE România accounts: places, meters, invoices, payments and self-readings.
5
+ Project-URL: Source, https://github.com/coffeerunhobby/aioengieromania
6
+ Project-URL: Issues, https://github.com/coffeerunhobby/aioengieromania/issues
7
+ Author: coffeerunhobby
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Framework :: AsyncIO
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.12
20
+ Requires-Dist: aiohttp>=3.9
21
+ Description-Content-Type: text/markdown
22
+
23
+ # aioengieromania
24
+
25
+ Async Python client for MyENGIE România accounts (the API behind the MyENGIE mobile
26
+ app). It powers the [ENGIE România](https://github.com/coffeerunhobby/ha-engie) Home
27
+ Assistant integration.
28
+
29
+ Unofficial; not affiliated with or endorsed by ENGIE.
30
+
31
+ ## Usage
32
+
33
+ ```python
34
+ import aiohttp
35
+ from aioengieromania import EngieClient
36
+
37
+ async with aiohttp.ClientSession() as session:
38
+ client = EngieClient("user@example.com", "password", device_id="<a stable uuid>", session=session)
39
+ for place in await client.async_get_places():
40
+ point = await client.async_get_point(place)
41
+ print(place.address, point.amount_due, [m.last_index for m in point.meters])
42
+ ```
43
+
44
+ `device_id` identifies your client to ENGIE the way the app's device id does; keep it
45
+ stable per installation. Payments are per client rather than per place:
46
+ `await client.async_get_payments(place.pa)`.
47
+
48
+ `async_submit_index(point, meter, index)` reports a self-read meter index. ENGIE only
49
+ accepts it inside the meter's self-reading window (`meter.self_read_open(today)`);
50
+ a refusal raises `EngieRejectedError` carrying ENGIE's reason.
51
+
52
+ Errors: `EngieAuthError` (credentials rejected), `EngieConnectionError` (unreachable or
53
+ timed out), `EngieRejectedError` (a submission was refused), all subclasses of
54
+ `EngieError`.
55
+
56
+ ## License
57
+
58
+ MIT
@@ -0,0 +1,36 @@
1
+ # aioengieromania
2
+
3
+ Async Python client for MyENGIE România accounts (the API behind the MyENGIE mobile
4
+ app). It powers the [ENGIE România](https://github.com/coffeerunhobby/ha-engie) Home
5
+ Assistant integration.
6
+
7
+ Unofficial; not affiliated with or endorsed by ENGIE.
8
+
9
+ ## Usage
10
+
11
+ ```python
12
+ import aiohttp
13
+ from aioengieromania import EngieClient
14
+
15
+ async with aiohttp.ClientSession() as session:
16
+ client = EngieClient("user@example.com", "password", device_id="<a stable uuid>", session=session)
17
+ for place in await client.async_get_places():
18
+ point = await client.async_get_point(place)
19
+ print(place.address, point.amount_due, [m.last_index for m in point.meters])
20
+ ```
21
+
22
+ `device_id` identifies your client to ENGIE the way the app's device id does; keep it
23
+ stable per installation. Payments are per client rather than per place:
24
+ `await client.async_get_payments(place.pa)`.
25
+
26
+ `async_submit_index(point, meter, index)` reports a self-read meter index. ENGIE only
27
+ accepts it inside the meter's self-reading window (`meter.self_read_open(today)`);
28
+ a refusal raises `EngieRejectedError` carrying ENGIE's reason.
29
+
30
+ Errors: `EngieAuthError` (credentials rejected), `EngieConnectionError` (unreachable or
31
+ timed out), `EngieRejectedError` (a submission was refused), all subclasses of
32
+ `EngieError`.
33
+
34
+ ## License
35
+
36
+ MIT
@@ -0,0 +1,49 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "aioengieromania"
7
+ version = "0.1.0"
8
+ description = "Async client for MyENGIE România accounts: places, meters, invoices, payments and self-readings."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "coffeerunhobby" }]
13
+ requires-python = ">=3.12"
14
+ dependencies = ["aiohttp>=3.9"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Framework :: AsyncIO",
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Programming Language :: Python :: 3.14",
24
+ "Typing :: Typed",
25
+ ]
26
+
27
+ [project.urls]
28
+ Source = "https://github.com/coffeerunhobby/aioengieromania"
29
+ Issues = "https://github.com/coffeerunhobby/aioengieromania/issues"
30
+
31
+ [dependency-groups]
32
+ test = ["pytest>=8", "pytest-asyncio>=0.24", "pytest-cov"]
33
+
34
+ [tool.hatch.build.targets.sdist]
35
+ include = ["src", "tests", "README.md", "LICENSE"]
36
+
37
+ [tool.pytest.ini_options]
38
+ asyncio_mode = "auto"
39
+ testpaths = ["tests"]
40
+
41
+ [tool.ruff]
42
+ line-length = 110
43
+ target-version = "py312"
44
+
45
+ [tool.ruff.lint]
46
+ select = ["E", "F", "W", "I", "B", "UP", "S", "ASYNC"]
47
+
48
+ [tool.ruff.lint.per-file-ignores]
49
+ "tests/*" = ["S101", "S105", "S106"]
@@ -0,0 +1,24 @@
1
+ """Async client for MyENGIE România accounts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .client import EngieClient
6
+ from .const import DIVISION_ELECTRICITY, DIVISION_GAS
7
+ from .exceptions import EngieAuthError, EngieConnectionError, EngieError, EngieRejectedError
8
+ from .models import Invoice, Meter, MonthlyConsumption, Payment, Place, PointData
9
+
10
+ __all__ = [
11
+ "DIVISION_ELECTRICITY",
12
+ "DIVISION_GAS",
13
+ "EngieAuthError",
14
+ "EngieClient",
15
+ "EngieConnectionError",
16
+ "EngieError",
17
+ "EngieRejectedError",
18
+ "Invoice",
19
+ "Meter",
20
+ "MonthlyConsumption",
21
+ "Payment",
22
+ "Place",
23
+ "PointData",
24
+ ]
@@ -0,0 +1,291 @@
1
+ """Async client for the MyENGIE România mobile-app API (gwss.engie.ro).
2
+
3
+ A form POST to ``/v1/login`` returns a bearer token that authorises every other
4
+ call; the token is renewed transparently when the gateway answers 401 or 403.
5
+ Every request carries the mobile app's device headers, which the gateway
6
+ requires. The caller owns the :class:`aiohttp.ClientSession`; when none is
7
+ given, the client creates one and closes it in :meth:`EngieClient.close`.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from datetime import date, timedelta
13
+ from typing import Any
14
+
15
+ import aiohttp
16
+
17
+ from .const import (
18
+ BALANCE_PATH,
19
+ BASE_URL,
20
+ CONSUMPTION_LOOKBACK_DAYS,
21
+ CONSUMPTION_PATH,
22
+ DEVICE_HEADERS,
23
+ DIVISIONS_PATH,
24
+ INDEX_PATH,
25
+ INVOICE_LOOKBACK_DAYS,
26
+ INVOICES_PATH,
27
+ LOGIN_PATH,
28
+ PAYMENT_LOOKBACK_DAYS,
29
+ PAYMENTS_PATH,
30
+ PLACES_PATH,
31
+ REQUEST_TIMEOUT,
32
+ SUBMIT_INDEX_PATH,
33
+ )
34
+ from .exceptions import EngieAuthError, EngieConnectionError, EngieError, EngieRejectedError
35
+ from .models import Invoice, Meter, Payment, Place, PointData
36
+ from .parser import (
37
+ apply_index,
38
+ parse_balance,
39
+ parse_consumption,
40
+ parse_divisions,
41
+ parse_invoices,
42
+ parse_payments,
43
+ parse_places,
44
+ )
45
+
46
+
47
+ def _window(days: int) -> dict[str, str]:
48
+ today = date.today()
49
+ return {"startDate": (today - timedelta(days=days)).isoformat(), "endDate": today.isoformat()}
50
+
51
+
52
+ def rejection_reason(body: Any) -> str:
53
+ """ENGIE's validation messages from an ``error: true`` envelope, briefly."""
54
+ found: list[str] = []
55
+
56
+ def collect(value: Any) -> None:
57
+ if isinstance(value, str) and value.strip():
58
+ found.append(value.strip())
59
+ elif isinstance(value, list):
60
+ for item in value:
61
+ collect(item)
62
+ elif isinstance(value, dict):
63
+ for item in value.values():
64
+ collect(item)
65
+
66
+ if isinstance(body, dict):
67
+ collect(body.get("errors"))
68
+ if not found:
69
+ collect(body.get("description"))
70
+ reason = "; ".join(dict.fromkeys(found))[:200]
71
+ return reason or "no reason given"
72
+
73
+
74
+ def index_form(
75
+ poc: str, pa: str, division: str, installation: str, serial: str | None, index: int
76
+ ) -> dict[str, str]:
77
+ """The form fields the app sends to report a meter index."""
78
+ form = {
79
+ "poc_number": poc,
80
+ "pa": pa,
81
+ "installation_number": installation,
82
+ "division": division,
83
+ "index": str(index),
84
+ }
85
+ if serial:
86
+ form["serie_contor"] = serial
87
+ return form
88
+
89
+
90
+ class EngieClient:
91
+ """Talks to the MyENGIE API and returns this library's models."""
92
+
93
+ def __init__(
94
+ self,
95
+ username: str,
96
+ password: str,
97
+ device_id: str,
98
+ session: aiohttp.ClientSession | None = None,
99
+ *,
100
+ request_timeout: float = REQUEST_TIMEOUT,
101
+ base_url: str = BASE_URL,
102
+ ) -> None:
103
+ self._base_url = base_url.rstrip("/")
104
+ self._username = username
105
+ self._password = password
106
+ self._headers = {**DEVICE_HEADERS, "Device-Id": device_id}
107
+ self._timeout = aiohttp.ClientTimeout(total=request_timeout)
108
+ self._session = session
109
+ self._owns_session = session is None
110
+ self._token: str | None = None
111
+
112
+ def _get_session(self) -> aiohttp.ClientSession:
113
+ if self._session is None:
114
+ self._session = aiohttp.ClientSession()
115
+ return self._session
116
+
117
+ async def close(self) -> None:
118
+ """Close the session if this client created it."""
119
+ if self._owns_session and self._session is not None and not self._session.closed:
120
+ await self._session.close()
121
+
122
+ # ── Auth ────────────────────────────────────────────────────────────────
123
+ async def async_login(self) -> None:
124
+ """Authenticate and keep the bearer token."""
125
+ form = {"username": self._username, "password": self._password}
126
+ try:
127
+ async with self._get_session().post(
128
+ self._base_url + LOGIN_PATH, data=form, headers=self._headers, timeout=self._timeout
129
+ ) as resp:
130
+ if resp.status >= 500:
131
+ raise EngieConnectionError(f"MyENGIE login failed: HTTP {resp.status}")
132
+ body = await self._decode(resp)
133
+ status = resp.status
134
+ except aiohttp.ClientError as err:
135
+ raise EngieConnectionError(str(err)) from err
136
+ except TimeoutError as err:
137
+ raise EngieConnectionError("MyENGIE did not answer the login in time") from err
138
+
139
+ data = body.get("data") if isinstance(body, dict) else None
140
+ token = data.get("token") if isinstance(data, dict) else None
141
+ if status in (400, 401, 403, 422) or (isinstance(body, dict) and body.get("error")):
142
+ raise EngieAuthError("Invalid e-mail or password")
143
+ if not token:
144
+ raise EngieAuthError("MyENGIE login returned no token")
145
+ self._token = str(token)
146
+
147
+ @staticmethod
148
+ async def _decode(resp: aiohttp.ClientResponse) -> Any:
149
+ """Decode JSON; the gateway serves an HTML page during maintenance."""
150
+ try:
151
+ return await resp.json(content_type=None)
152
+ except (aiohttp.ContentTypeError, ValueError):
153
+ raise EngieConnectionError(
154
+ f"MyENGIE returned a non-JSON response (HTTP {resp.status})"
155
+ ) from None
156
+
157
+ # ── Core request helper ─────────────────────────────────────────────────
158
+ async def _request(
159
+ self,
160
+ method: str,
161
+ path: str,
162
+ params: dict[str, Any] | None = None,
163
+ payload: dict[str, Any] | None = None,
164
+ form: dict[str, str] | None = None,
165
+ ) -> Any:
166
+ """Issue an authenticated request, logging in again once on 401/403.
167
+
168
+ ``form`` sends a urlencoded body instead of JSON; such requests are
169
+ submissions, so a refusal raises :class:`EngieRejectedError` with ENGIE's
170
+ reason rather than a bare status.
171
+ """
172
+ if self._token is None:
173
+ await self.async_login()
174
+ for attempt in (1, 2):
175
+ try:
176
+ async with self._get_session().request(
177
+ method,
178
+ self._base_url + path,
179
+ params={k: v for k, v in (params or {}).items() if v is not None},
180
+ json=payload,
181
+ data=form,
182
+ headers={**self._headers, "Authorization": f"Bearer {self._token}"},
183
+ timeout=self._timeout,
184
+ ) as resp:
185
+ if resp.status in (401, 403) and attempt == 1:
186
+ self._token = None
187
+ await self.async_login()
188
+ continue
189
+ if resp.status in (401, 403):
190
+ raise EngieAuthError("Session rejected by MyENGIE")
191
+ if form is not None and resp.status < 500:
192
+ body = await self._decode(resp)
193
+ if resp.status >= 400 or (isinstance(body, dict) and body.get("error")):
194
+ raise EngieRejectedError(rejection_reason(body))
195
+ return body
196
+ if resp.status == 404:
197
+ return None
198
+ if resp.status >= 400:
199
+ # The path is not named: it carries account and place numbers.
200
+ raise EngieError(f"MyENGIE API error: HTTP {resp.status}")
201
+ return await self._decode(resp)
202
+ except aiohttp.ClientError as err:
203
+ raise EngieConnectionError(str(err)) from err
204
+ except TimeoutError as err:
205
+ raise EngieConnectionError("MyENGIE did not answer in time") from err
206
+ raise EngieAuthError("Could not authenticate with MyENGIE")
207
+
208
+ # ── Endpoints ───────────────────────────────────────────────────────────
209
+ async def async_get_places(self) -> list[Place]:
210
+ """Places of consumption on the account — the entry point for everything else."""
211
+ return parse_places(await self._request("GET", PLACES_PATH))
212
+
213
+ async def async_get_meters(self, poc: str, pa: str) -> list[Meter]:
214
+ """Metered services at a place, with their last index and self-reading window."""
215
+ meters = parse_divisions(
216
+ await self._request("GET", DIVISIONS_PATH.format(poc=poc), {"pa": pa})
217
+ )
218
+ for meter in meters:
219
+ apply_index(
220
+ [meter],
221
+ await self._request(
222
+ "GET",
223
+ INDEX_PATH.format(poc=poc),
224
+ {
225
+ "division": meter.division,
226
+ "pa": pa,
227
+ "installation_number": meter.installation_number,
228
+ "serie_contor": meter.serial,
229
+ },
230
+ ),
231
+ )
232
+ return meters
233
+
234
+ async def async_get_consumption_payload(self, poc: str, pa: str) -> Any:
235
+ """Billed monthly consumption, raw; see :func:`parse_consumption`."""
236
+ return await self._request(
237
+ "GET",
238
+ CONSUMPTION_PATH.format(poc=poc),
239
+ {**_window(CONSUMPTION_LOOKBACK_DAYS), "pa": pa},
240
+ )
241
+
242
+ async def async_get_invoices(self, poc: str, pa: str) -> list[Invoice]:
243
+ return parse_invoices(
244
+ await self._request(
245
+ "GET", INVOICES_PATH.format(poc=poc), {**_window(INVOICE_LOOKBACK_DAYS), "pa": pa}
246
+ )
247
+ )
248
+
249
+ async def async_get_payments(self, pa: str) -> list[Payment]:
250
+ """Payments, per client (``pa``) rather than per place."""
251
+ return parse_payments(
252
+ await self._request("GET", PAYMENTS_PATH.format(pa=pa), _window(PAYMENT_LOOKBACK_DAYS))
253
+ )
254
+
255
+ async def async_get_balance(
256
+ self, contract_accounts: list[str]
257
+ ) -> tuple[float | None, dict[str, float]]:
258
+ """(total, per-division) balance; negative means credit."""
259
+ return parse_balance(
260
+ await self._request(
261
+ "POST",
262
+ BALANCE_PATH,
263
+ payload={"contract_account": [int(c) for c in contract_accounts]},
264
+ )
265
+ )
266
+
267
+ async def async_get_point(self, place: Place) -> PointData:
268
+ """Everything for one place of consumption except payments (shared per client)."""
269
+ point = PointData(poc=place.poc, pa=place.pa, address=place.address)
270
+ point.meters = await self.async_get_meters(place.poc, place.pa)
271
+ consumption = await self.async_get_consumption_payload(place.poc, place.pa)
272
+ point.consumption = {
273
+ m.division: parse_consumption(consumption, m.division) for m in point.meters
274
+ }
275
+ point.invoices = await self.async_get_invoices(place.poc, place.pa)
276
+ accounts = place.contract_accounts or sorted(
277
+ {m.contract_account for m in point.meters if m.contract_account}
278
+ )
279
+ if accounts:
280
+ point.balance, point.balance_by_division = await self.async_get_balance(accounts)
281
+ return point
282
+
283
+ async def async_submit_index(self, point: PointData, meter: Meter, index: int) -> None:
284
+ """Report a self-read meter index. Raises EngieRejectedError when refused."""
285
+ await self._request(
286
+ "POST",
287
+ SUBMIT_INDEX_PATH,
288
+ form=index_form(
289
+ point.poc, point.pa, meter.division, meter.installation_number, meter.serial, index
290
+ ),
291
+ )
@@ -0,0 +1,48 @@
1
+ """Endpoints and device headers of the MyENGIE România mobile-app API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Final
6
+
7
+ # The mobile app's JSON gateway. A form POST to /v1/login returns a bearer token;
8
+ # every request must also carry the app's device headers or the gateway refuses it.
9
+ BASE_URL: Final = "https://gwss.engie.ro/myservices"
10
+ LOGIN_PATH: Final = "/v1/login"
11
+ PLACES_PATH: Final = "/v1/placesofconsumption"
12
+ DIVISIONS_PATH: Final = "/v1/placesofconsumption/divisions/{poc}"
13
+ INDEX_PATH: Final = "/v1/index/{poc}"
14
+ # Self-reading submission: a form POST (not JSON), answered 200 even on rejection.
15
+ SUBMIT_INDEX_PATH: Final = "/v1/index"
16
+ CONSUMPTION_PATH: Final = "/v1/index/consumption/{poc}"
17
+ INVOICES_PATH: Final = "/v1/invoices/history/{poc}"
18
+ PAYMENTS_PATH: Final = "/v1/invoices/payment/history/{pa}"
19
+ # "ballance" is ENGIE's own spelling in the endpoint path.
20
+ BALANCE_PATH: Final = "/v1/invoices/ballance-details"
21
+
22
+ # The server rejects invoice-history windows longer than twelve months.
23
+ INVOICE_LOOKBACK_DAYS: Final = 364
24
+ PAYMENT_LOOKBACK_DAYS: Final = 730
25
+ CONSUMPTION_LOOKBACK_DAYS: Final = 1095
26
+
27
+ REQUEST_TIMEOUT: Final = 30
28
+
29
+ APP_VERSION: Final = "2.1.11"
30
+ APP_BUILD: Final = "177"
31
+ DEVICE_HEADERS: Final = {
32
+ "source": "android",
33
+ "App-Version": APP_VERSION,
34
+ "App-Build": APP_BUILD,
35
+ "OS-Version": "14",
36
+ "OS-Platform": "android",
37
+ "Device-Type": "phone",
38
+ "Device-Manufacturer": "Google",
39
+ "Device-Model": "Pixel 8",
40
+ "Screen-Height": "2400",
41
+ "Screen-Width": "1080",
42
+ "User-Agent": f"MyEngie/{APP_VERSION} (Android; ro.engie.agentia; build {APP_BUILD})",
43
+ "Accept": "application/json",
44
+ }
45
+
46
+ # ENGIE's division codes.
47
+ DIVISION_GAS: Final = "gaz"
48
+ DIVISION_ELECTRICITY: Final = "elec"
@@ -0,0 +1,19 @@
1
+ """Exceptions raised by the MyENGIE client."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class EngieError(Exception):
7
+ """Base ENGIE exception."""
8
+
9
+
10
+ class EngieAuthError(EngieError):
11
+ """Credentials rejected, or the session could not be renewed."""
12
+
13
+
14
+ class EngieConnectionError(EngieError):
15
+ """The API could not be reached or did not answer in time."""
16
+
17
+
18
+ class EngieRejectedError(EngieError):
19
+ """ENGIE refused a submission; the message is ENGIE's own reason."""