united-utilities 0.2.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.
- united_utilities-0.2.0/LICENSE +21 -0
- united_utilities-0.2.0/PKG-INFO +123 -0
- united_utilities-0.2.0/README.md +90 -0
- united_utilities-0.2.0/pyproject.toml +79 -0
- united_utilities-0.2.0/setup.cfg +4 -0
- united_utilities-0.2.0/src/united_utilities/__init__.py +36 -0
- united_utilities-0.2.0/src/united_utilities/_parsing.py +30 -0
- united_utilities-0.2.0/src/united_utilities/client.py +195 -0
- united_utilities-0.2.0/src/united_utilities/const.py +14 -0
- united_utilities-0.2.0/src/united_utilities/exceptions.py +37 -0
- united_utilities-0.2.0/src/united_utilities/models.py +195 -0
- united_utilities-0.2.0/src/united_utilities/py.typed +0 -0
- united_utilities-0.2.0/src/united_utilities.egg-info/PKG-INFO +123 -0
- united_utilities-0.2.0/src/united_utilities.egg-info/SOURCES.txt +17 -0
- united_utilities-0.2.0/src/united_utilities.egg-info/dependency_links.txt +1 -0
- united_utilities-0.2.0/src/united_utilities.egg-info/requires.txt +9 -0
- united_utilities-0.2.0/src/united_utilities.egg-info/top_level.txt +1 -0
- united_utilities-0.2.0/tests/test_client.py +227 -0
- united_utilities-0.2.0/tests/test_parsing.py +31 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kieran Roper
|
|
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,123 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: united-utilities
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Async Python client for the United Utilities mobile API (unofficial, reverse-engineered)
|
|
5
|
+
Author: Kieran Roper
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/KRoperUK/united-utilities-py
|
|
8
|
+
Project-URL: Repository, https://github.com/KRoperUK/united-utilities-py
|
|
9
|
+
Project-URL: Issues, https://github.com/KRoperUK/united-utilities-py/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/KRoperUK/united-utilities-py/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: united-utilities,water,utility,asyncio,homeassistant
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Framework :: AsyncIO
|
|
19
|
+
Classifier: Topic :: Home Automation
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.12
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: aiohttp>=3.9
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
27
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
|
|
28
|
+
Requires-Dist: pytest-cov>=5; extra == "dev"
|
|
29
|
+
Requires-Dist: aresponses>=3.0; extra == "dev"
|
|
30
|
+
Requires-Dist: ruff>=0.8; extra == "dev"
|
|
31
|
+
Requires-Dist: mypy>=1.13; extra == "dev"
|
|
32
|
+
Dynamic: license-file
|
|
33
|
+
|
|
34
|
+
# united-utilities-py
|
|
35
|
+
|
|
36
|
+
Async Python client for the **United Utilities** "Your Water" mobile API,
|
|
37
|
+
reverse-engineered from the app (build 102). Pairs with a Home Assistant
|
|
38
|
+
integration (`united-utilities-hass`).
|
|
39
|
+
|
|
40
|
+
> Unofficial. Uses a private app API that United Utilities can change or
|
|
41
|
+
> withdraw at any time. For personal use with your own account.
|
|
42
|
+
|
|
43
|
+
## Why the mobile API (not the website)
|
|
44
|
+
|
|
45
|
+
The `myaccount.unitedutilities.com` website is gated behind Google reCAPTCHA
|
|
46
|
+
Enterprise and Jscrambler, so a scripted login needs a real browser. The mobile
|
|
47
|
+
app talks to a separate gateway (`prd-mobile-apigateway.unitedutilities.com`)
|
|
48
|
+
with a far simpler scheme: a static app `apiKey` header plus a `customerId` +
|
|
49
|
+
numeric `PIN` login that returns a session token. No captcha.
|
|
50
|
+
|
|
51
|
+
## Credentials
|
|
52
|
+
|
|
53
|
+
The mobile API does **not** use your website email/password. It needs:
|
|
54
|
+
|
|
55
|
+
- **`customerId`** — a numeric id assigned when you register in the app.
|
|
56
|
+
- **`pin`** — the numeric PIN you set in the app.
|
|
57
|
+
- **`accountNumber`** — your water account number (for account-scoped calls).
|
|
58
|
+
|
|
59
|
+
The easiest way to find `customerId` is to capture the app's `api/account/login`
|
|
60
|
+
request once; the body is `customerId=…&pin=…&platform=…` (form-encoded). The
|
|
61
|
+
app pins its TLS certificate, so an intercepting proxy breaks the app's *data*
|
|
62
|
+
calls even though the login call goes through — that's expected.
|
|
63
|
+
|
|
64
|
+
> ⚠️ **Login has a 3-strike lockout.** A wrong PIN decrements
|
|
65
|
+
> `attemptsRemaining`; at zero the account locks. This client never retries
|
|
66
|
+
> `login()`. Do not loop on `AuthError`.
|
|
67
|
+
|
|
68
|
+
## Install
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
pip install united-utilities
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Usage
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
import asyncio
|
|
78
|
+
from united_utilities import UnitedUtilitiesClient
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
async def main() -> None:
|
|
82
|
+
async with UnitedUtilitiesClient("24000000", "000000", "4000000000") as uu:
|
|
83
|
+
await uu.login()
|
|
84
|
+
details = await uu.account_details()
|
|
85
|
+
meter = await uu.meter_readings()
|
|
86
|
+
print("balance:", details.account_balance)
|
|
87
|
+
if meter.latest:
|
|
88
|
+
print("last read:", meter.latest.value, "on", meter.latest.date)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
asyncio.run(main())
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
In Home Assistant, pass the shared session:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
|
98
|
+
|
|
99
|
+
client = UnitedUtilitiesClient(customer_id, pin, account_number,
|
|
100
|
+
session=async_get_clientsession(hass))
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Endpoints covered
|
|
104
|
+
|
|
105
|
+
| Method | Returns |
|
|
106
|
+
| --- | --- |
|
|
107
|
+
| `login()` / `logout()` | session token lifecycle |
|
|
108
|
+
| `account_details()` | balance, next payment, meter flag, payment plan, bill count |
|
|
109
|
+
| `meter_readings()` | meter details + reading history (`.latest`) |
|
|
110
|
+
| `statement()` | itemised bills & payments |
|
|
111
|
+
| `payment_info()` | current balance, minimum payment |
|
|
112
|
+
| `preferences()` | notification preferences |
|
|
113
|
+
| `notifications()` | customer notifications |
|
|
114
|
+
|
|
115
|
+
## Development
|
|
116
|
+
|
|
117
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md). Response shapes were confirmed against
|
|
118
|
+
live production responses; tests run on synthetic fixtures (no real account
|
|
119
|
+
data) with `aresponses`.
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
MIT
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# united-utilities-py
|
|
2
|
+
|
|
3
|
+
Async Python client for the **United Utilities** "Your Water" mobile API,
|
|
4
|
+
reverse-engineered from the app (build 102). Pairs with a Home Assistant
|
|
5
|
+
integration (`united-utilities-hass`).
|
|
6
|
+
|
|
7
|
+
> Unofficial. Uses a private app API that United Utilities can change or
|
|
8
|
+
> withdraw at any time. For personal use with your own account.
|
|
9
|
+
|
|
10
|
+
## Why the mobile API (not the website)
|
|
11
|
+
|
|
12
|
+
The `myaccount.unitedutilities.com` website is gated behind Google reCAPTCHA
|
|
13
|
+
Enterprise and Jscrambler, so a scripted login needs a real browser. The mobile
|
|
14
|
+
app talks to a separate gateway (`prd-mobile-apigateway.unitedutilities.com`)
|
|
15
|
+
with a far simpler scheme: a static app `apiKey` header plus a `customerId` +
|
|
16
|
+
numeric `PIN` login that returns a session token. No captcha.
|
|
17
|
+
|
|
18
|
+
## Credentials
|
|
19
|
+
|
|
20
|
+
The mobile API does **not** use your website email/password. It needs:
|
|
21
|
+
|
|
22
|
+
- **`customerId`** — a numeric id assigned when you register in the app.
|
|
23
|
+
- **`pin`** — the numeric PIN you set in the app.
|
|
24
|
+
- **`accountNumber`** — your water account number (for account-scoped calls).
|
|
25
|
+
|
|
26
|
+
The easiest way to find `customerId` is to capture the app's `api/account/login`
|
|
27
|
+
request once; the body is `customerId=…&pin=…&platform=…` (form-encoded). The
|
|
28
|
+
app pins its TLS certificate, so an intercepting proxy breaks the app's *data*
|
|
29
|
+
calls even though the login call goes through — that's expected.
|
|
30
|
+
|
|
31
|
+
> ⚠️ **Login has a 3-strike lockout.** A wrong PIN decrements
|
|
32
|
+
> `attemptsRemaining`; at zero the account locks. This client never retries
|
|
33
|
+
> `login()`. Do not loop on `AuthError`.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
pip install united-utilities
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Usage
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import asyncio
|
|
45
|
+
from united_utilities import UnitedUtilitiesClient
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
async def main() -> None:
|
|
49
|
+
async with UnitedUtilitiesClient("24000000", "000000", "4000000000") as uu:
|
|
50
|
+
await uu.login()
|
|
51
|
+
details = await uu.account_details()
|
|
52
|
+
meter = await uu.meter_readings()
|
|
53
|
+
print("balance:", details.account_balance)
|
|
54
|
+
if meter.latest:
|
|
55
|
+
print("last read:", meter.latest.value, "on", meter.latest.date)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
asyncio.run(main())
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
In Home Assistant, pass the shared session:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
|
65
|
+
|
|
66
|
+
client = UnitedUtilitiesClient(customer_id, pin, account_number,
|
|
67
|
+
session=async_get_clientsession(hass))
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Endpoints covered
|
|
71
|
+
|
|
72
|
+
| Method | Returns |
|
|
73
|
+
| --- | --- |
|
|
74
|
+
| `login()` / `logout()` | session token lifecycle |
|
|
75
|
+
| `account_details()` | balance, next payment, meter flag, payment plan, bill count |
|
|
76
|
+
| `meter_readings()` | meter details + reading history (`.latest`) |
|
|
77
|
+
| `statement()` | itemised bills & payments |
|
|
78
|
+
| `payment_info()` | current balance, minimum payment |
|
|
79
|
+
| `preferences()` | notification preferences |
|
|
80
|
+
| `notifications()` | customer notifications |
|
|
81
|
+
|
|
82
|
+
## Development
|
|
83
|
+
|
|
84
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md). Response shapes were confirmed against
|
|
85
|
+
live production responses; tests run on synthetic fixtures (no real account
|
|
86
|
+
data) with `aresponses`.
|
|
87
|
+
|
|
88
|
+
## License
|
|
89
|
+
|
|
90
|
+
MIT
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "united-utilities"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "Async Python client for the United Utilities mobile API (unofficial, reverse-engineered)"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [{ name = "Kieran Roper" }]
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
keywords = ["united-utilities", "water", "utility", "asyncio", "homeassistant"]
|
|
10
|
+
# 3.12 is the floor. Deliberately below the consuming integration's floor so the
|
|
11
|
+
# library stays usable standalone and on older Home Assistant releases.
|
|
12
|
+
requires-python = ">=3.12"
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 4 - Beta",
|
|
15
|
+
"Intended Audience :: Developers",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.12",
|
|
19
|
+
"Programming Language :: Python :: 3.13",
|
|
20
|
+
"Framework :: AsyncIO",
|
|
21
|
+
"Topic :: Home Automation",
|
|
22
|
+
"Typing :: Typed",
|
|
23
|
+
]
|
|
24
|
+
dependencies = ["aiohttp>=3.9"]
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
dev = [
|
|
28
|
+
"pytest>=8",
|
|
29
|
+
"pytest-asyncio>=0.24",
|
|
30
|
+
"pytest-cov>=5",
|
|
31
|
+
"aresponses>=3.0",
|
|
32
|
+
"ruff>=0.8",
|
|
33
|
+
"mypy>=1.13",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[project.urls]
|
|
37
|
+
Homepage = "https://github.com/KRoperUK/united-utilities-py"
|
|
38
|
+
Repository = "https://github.com/KRoperUK/united-utilities-py"
|
|
39
|
+
Issues = "https://github.com/KRoperUK/united-utilities-py/issues"
|
|
40
|
+
Changelog = "https://github.com/KRoperUK/united-utilities-py/blob/main/CHANGELOG.md"
|
|
41
|
+
|
|
42
|
+
[build-system]
|
|
43
|
+
requires = ["setuptools>=68"]
|
|
44
|
+
build-backend = "setuptools.build_meta"
|
|
45
|
+
|
|
46
|
+
[tool.setuptools.packages.find]
|
|
47
|
+
where = ["src"]
|
|
48
|
+
|
|
49
|
+
[tool.setuptools.package-data]
|
|
50
|
+
united_utilities = ["py.typed"]
|
|
51
|
+
|
|
52
|
+
[tool.ruff]
|
|
53
|
+
target-version = "py312"
|
|
54
|
+
line-length = 120
|
|
55
|
+
src = ["src", "tests"]
|
|
56
|
+
|
|
57
|
+
[tool.ruff.lint]
|
|
58
|
+
select = ["E", "W", "F", "I", "UP", "B", "SIM"]
|
|
59
|
+
ignore = ["E501"]
|
|
60
|
+
|
|
61
|
+
[tool.mypy]
|
|
62
|
+
python_version = "3.12"
|
|
63
|
+
strict = true
|
|
64
|
+
files = ["src/united_utilities", "tests"]
|
|
65
|
+
ignore_missing_imports = true
|
|
66
|
+
|
|
67
|
+
[tool.pytest.ini_options]
|
|
68
|
+
testpaths = ["tests"]
|
|
69
|
+
asyncio_mode = "auto"
|
|
70
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
71
|
+
addopts = "-v --tb=short"
|
|
72
|
+
|
|
73
|
+
[tool.coverage.run]
|
|
74
|
+
source = ["src/united_utilities"]
|
|
75
|
+
omit = ["tests/*"]
|
|
76
|
+
|
|
77
|
+
[tool.coverage.report]
|
|
78
|
+
show_missing = true
|
|
79
|
+
fail_under = 80
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Async client for the reverse-engineered United Utilities mobile API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .client import UnitedUtilitiesClient
|
|
6
|
+
from .const import API_KEY, BASE_URL
|
|
7
|
+
from .exceptions import AuthError, ClientError, NotLoggedInError
|
|
8
|
+
from .models import (
|
|
9
|
+
AccountDetails,
|
|
10
|
+
AccountHistoryItem,
|
|
11
|
+
BillingPeriod,
|
|
12
|
+
MeterDetails,
|
|
13
|
+
MeterReading,
|
|
14
|
+
MeterReadings,
|
|
15
|
+
PaymentInfo,
|
|
16
|
+
Preferences,
|
|
17
|
+
StatementItem,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"API_KEY",
|
|
22
|
+
"BASE_URL",
|
|
23
|
+
"AccountDetails",
|
|
24
|
+
"AccountHistoryItem",
|
|
25
|
+
"AuthError",
|
|
26
|
+
"BillingPeriod",
|
|
27
|
+
"ClientError",
|
|
28
|
+
"MeterDetails",
|
|
29
|
+
"MeterReading",
|
|
30
|
+
"MeterReadings",
|
|
31
|
+
"NotLoggedInError",
|
|
32
|
+
"PaymentInfo",
|
|
33
|
+
"Preferences",
|
|
34
|
+
"StatementItem",
|
|
35
|
+
"UnitedUtilitiesClient",
|
|
36
|
+
]
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Helpers for the quirky shapes the UU API returns.
|
|
2
|
+
|
|
3
|
+
Dates arrive as ``DDMMYYYY`` strings (e.g. ``"21112026"``), sometimes null or
|
|
4
|
+
empty. Numeric meter readings arrive as strings.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from datetime import date
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def parse_date(value: str | None) -> date | None:
|
|
13
|
+
"""Parse a ``DDMMYYYY`` string. Returns None for empty/invalid input."""
|
|
14
|
+
if not value or len(value) != 8 or not value.isdigit():
|
|
15
|
+
return None
|
|
16
|
+
day, month, year = int(value[0:2]), int(value[2:4]), int(value[4:8])
|
|
17
|
+
try:
|
|
18
|
+
return date(year, month, day)
|
|
19
|
+
except ValueError:
|
|
20
|
+
return None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def parse_int(value: str | int | None) -> int | None:
|
|
24
|
+
"""Parse an int that may arrive as a string or be absent."""
|
|
25
|
+
if value is None or value == "":
|
|
26
|
+
return None
|
|
27
|
+
try:
|
|
28
|
+
return int(value)
|
|
29
|
+
except (TypeError, ValueError):
|
|
30
|
+
return None
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Async client for the United Utilities mobile API.
|
|
2
|
+
|
|
3
|
+
Reverse-engineered from the "United Utilities: Your Water" app (build 102).
|
|
4
|
+
Auth is a static app ``apiKey`` header plus a ``customerId`` + numeric ``pin``
|
|
5
|
+
login that returns a short ``sessionToken``; every other call carries that
|
|
6
|
+
token in a ``token`` header.
|
|
7
|
+
|
|
8
|
+
WARNING: the login has a 3-strike lockout. A wrong PIN decrements
|
|
9
|
+
``attemptsRemaining`` and the account locks at zero, so this client never
|
|
10
|
+
retries ``login()``. Do not loop on :class:`AuthError`.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import contextlib
|
|
16
|
+
import json as _json
|
|
17
|
+
import logging
|
|
18
|
+
from types import TracebackType
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from aiohttp import ClientError as AiohttpClientError
|
|
22
|
+
from aiohttp import ClientSession
|
|
23
|
+
|
|
24
|
+
from .const import API_KEY, BASE_URL, USER_AGENT
|
|
25
|
+
from .exceptions import AuthError, ClientError, NotLoggedInError
|
|
26
|
+
from .models import (
|
|
27
|
+
AccountDetails,
|
|
28
|
+
MeterReadings,
|
|
29
|
+
PaymentInfo,
|
|
30
|
+
Preferences,
|
|
31
|
+
StatementItem,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
_LOGGER = logging.getLogger(__name__)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class UnitedUtilitiesClient:
|
|
38
|
+
"""Talks to the UU mobile API for a single account.
|
|
39
|
+
|
|
40
|
+
Pass a shared ``aiohttp.ClientSession`` (HA integrations should use the one
|
|
41
|
+
from ``async_get_clientsession(hass)``). If omitted, the client creates and
|
|
42
|
+
owns its own session, closed by :meth:`close` or the context manager.
|
|
43
|
+
|
|
44
|
+
Usage::
|
|
45
|
+
|
|
46
|
+
async with UnitedUtilitiesClient(customer_id, pin, account_number) as uu:
|
|
47
|
+
await uu.login()
|
|
48
|
+
details = await uu.account_details()
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(
|
|
52
|
+
self,
|
|
53
|
+
customer_id: str,
|
|
54
|
+
pin: str,
|
|
55
|
+
account_number: str | None = None,
|
|
56
|
+
*,
|
|
57
|
+
session: ClientSession | None = None,
|
|
58
|
+
api_key: str = API_KEY,
|
|
59
|
+
base_url: str = BASE_URL,
|
|
60
|
+
) -> None:
|
|
61
|
+
self._customer_id = customer_id
|
|
62
|
+
self._pin = pin
|
|
63
|
+
self._account_number = account_number
|
|
64
|
+
self._api_key = api_key
|
|
65
|
+
self._base_url = base_url.rstrip("/")
|
|
66
|
+
self._token: str | None = None
|
|
67
|
+
self._session = session
|
|
68
|
+
self._owns_session = session is None
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def logged_in(self) -> bool:
|
|
72
|
+
return self._token is not None
|
|
73
|
+
|
|
74
|
+
async def login(self) -> None:
|
|
75
|
+
"""Exchange customerId + PIN for a session token.
|
|
76
|
+
|
|
77
|
+
Raises :class:`AuthError` on bad credentials (check
|
|
78
|
+
``.attempts_remaining`` — do NOT retry).
|
|
79
|
+
"""
|
|
80
|
+
data = await self._request(
|
|
81
|
+
"POST",
|
|
82
|
+
"/api/account/login",
|
|
83
|
+
data={"customerId": self._customer_id, "pin": self._pin, "platform": "android"},
|
|
84
|
+
authed=False,
|
|
85
|
+
)
|
|
86
|
+
token = data.get("sessionToken")
|
|
87
|
+
if not token:
|
|
88
|
+
raise AuthError("Login response contained no sessionToken.")
|
|
89
|
+
self._token = token
|
|
90
|
+
|
|
91
|
+
async def logout(self) -> None:
|
|
92
|
+
if self._token is None:
|
|
93
|
+
return
|
|
94
|
+
try:
|
|
95
|
+
# The gateway WAF 403s a body-less POST; an empty JSON object is accepted.
|
|
96
|
+
await self._request("POST", "/api/account/logout", json={})
|
|
97
|
+
finally:
|
|
98
|
+
self._token = None
|
|
99
|
+
|
|
100
|
+
async def account_details(self, account_number: str | None = None) -> AccountDetails:
|
|
101
|
+
return AccountDetails.from_json(await self._post_account("/api/account/details", account_number))
|
|
102
|
+
|
|
103
|
+
async def meter_readings(self, account_number: str | None = None) -> MeterReadings:
|
|
104
|
+
return MeterReadings.from_json(await self._post_account("/api/reading/meterreading", account_number))
|
|
105
|
+
|
|
106
|
+
async def payment_info(self, account_number: str | None = None) -> PaymentInfo:
|
|
107
|
+
return PaymentInfo.from_json(await self._post_account("/api/payment", account_number))
|
|
108
|
+
|
|
109
|
+
async def statement(self, account_number: str | None = None) -> list[StatementItem]:
|
|
110
|
+
data = await self._post_account("/api/statement", account_number)
|
|
111
|
+
return [StatementItem.from_json(x) for x in data.get("history") or []]
|
|
112
|
+
|
|
113
|
+
async def preferences(self) -> Preferences:
|
|
114
|
+
return Preferences.from_json(await self._request("GET", "/api/account/preferences"))
|
|
115
|
+
|
|
116
|
+
async def notifications(self) -> list[dict[str, Any]]:
|
|
117
|
+
data = await self._request("GET", "/api/account/GetCustomerNotifications")
|
|
118
|
+
return list(data.get("notifications") or [])
|
|
119
|
+
|
|
120
|
+
# -- internals -----------------------------------------------------------
|
|
121
|
+
|
|
122
|
+
def _ensure_session(self) -> ClientSession:
|
|
123
|
+
if self._session is None:
|
|
124
|
+
self._session = ClientSession()
|
|
125
|
+
return self._session
|
|
126
|
+
|
|
127
|
+
def _require_account(self, account_number: str | None) -> str:
|
|
128
|
+
account = account_number or self._account_number
|
|
129
|
+
if not account:
|
|
130
|
+
raise ValueError("account_number was not provided to the call or the client.")
|
|
131
|
+
return account
|
|
132
|
+
|
|
133
|
+
async def _post_account(self, path: str, account_number: str | None) -> dict[str, Any]:
|
|
134
|
+
return await self._request("POST", path, json={"accountNumber": self._require_account(account_number)})
|
|
135
|
+
|
|
136
|
+
async def _request(
|
|
137
|
+
self,
|
|
138
|
+
method: str,
|
|
139
|
+
path: str,
|
|
140
|
+
*,
|
|
141
|
+
json: dict[str, Any] | None = None,
|
|
142
|
+
data: dict[str, str] | None = None,
|
|
143
|
+
authed: bool = True,
|
|
144
|
+
) -> dict[str, Any]:
|
|
145
|
+
headers = {"apiKey": self._api_key, "User-Agent": USER_AGENT}
|
|
146
|
+
if authed:
|
|
147
|
+
if self._token is None:
|
|
148
|
+
raise NotLoggedInError("Call login() before making data requests.")
|
|
149
|
+
headers["token"] = self._token
|
|
150
|
+
|
|
151
|
+
session = self._ensure_session()
|
|
152
|
+
try:
|
|
153
|
+
async with session.request(
|
|
154
|
+
method, f"{self._base_url}{path}", headers=headers, json=json, data=data
|
|
155
|
+
) as resp:
|
|
156
|
+
if resp.status == 401:
|
|
157
|
+
return self._handle_401(path, await resp.text())
|
|
158
|
+
if resp.status >= 400:
|
|
159
|
+
raise ClientError(f"HTTP {resp.status} from {path}", code=str(resp.status))
|
|
160
|
+
body: dict[str, Any] = await resp.json(content_type=None)
|
|
161
|
+
return body
|
|
162
|
+
except (ClientError, NotLoggedInError):
|
|
163
|
+
raise
|
|
164
|
+
except AiohttpClientError as err:
|
|
165
|
+
raise ClientError(f"Request to {path} failed: {err}") from err
|
|
166
|
+
|
|
167
|
+
def _handle_401(self, path: str, text: str) -> dict[str, Any]:
|
|
168
|
+
if path.endswith("/login"):
|
|
169
|
+
attempts = None
|
|
170
|
+
with contextlib.suppress(ValueError, AttributeError):
|
|
171
|
+
attempts = _json.loads(text).get("attemptsRemaining")
|
|
172
|
+
raise AuthError(
|
|
173
|
+
"Login rejected by United Utilities (check customerId/PIN).",
|
|
174
|
+
code="401",
|
|
175
|
+
attempts_remaining=attempts,
|
|
176
|
+
)
|
|
177
|
+
# Token expired/invalid on a data call. Clear it; caller re-logs in ONCE.
|
|
178
|
+
self._token = None
|
|
179
|
+
raise NotLoggedInError("Session token rejected (401); log in again.")
|
|
180
|
+
|
|
181
|
+
async def close(self) -> None:
|
|
182
|
+
if self._owns_session and self._session is not None:
|
|
183
|
+
await self._session.close()
|
|
184
|
+
self._session = None
|
|
185
|
+
|
|
186
|
+
async def __aenter__(self) -> UnitedUtilitiesClient:
|
|
187
|
+
return self
|
|
188
|
+
|
|
189
|
+
async def __aexit__(
|
|
190
|
+
self,
|
|
191
|
+
exc_type: type[BaseException] | None,
|
|
192
|
+
exc: BaseException | None,
|
|
193
|
+
tb: TracebackType | None,
|
|
194
|
+
) -> None:
|
|
195
|
+
await self.close()
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Constants for the United Utilities mobile API.
|
|
2
|
+
|
|
3
|
+
Reverse-engineered from the "United Utilities: Your Water" app (build 102).
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
BASE_URL = "https://prd-mobile-apigateway.unitedutilities.com"
|
|
9
|
+
|
|
10
|
+
# Static per-environment key baked into the app (production). Not a user secret;
|
|
11
|
+
# it gates the gateway, not an account.
|
|
12
|
+
API_KEY = "038649FA3CB9EC16786AF845A32337849850B5CC2E9EA3FA71A8B88077B481A3"
|
|
13
|
+
|
|
14
|
+
USER_AGENT = "consumerapp/4.8 (com.unitedutilities.consumer.app; build:102)"
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Public exception hierarchy.
|
|
2
|
+
|
|
3
|
+
Kept small and HA-free so the integration can map errors to
|
|
4
|
+
ConfigEntryAuthFailed / UpdateFailed without importing Home Assistant here.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ClientError(Exception):
|
|
11
|
+
"""Base error for the client library."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, message: str, *, code: str | None = None) -> None:
|
|
14
|
+
super().__init__(message)
|
|
15
|
+
self.code = code
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AuthError(ClientError):
|
|
19
|
+
"""Login was rejected — caller should re-authenticate, never retry blindly.
|
|
20
|
+
|
|
21
|
+
``attempts_remaining`` mirrors the server countdown; the account locks when
|
|
22
|
+
it reaches zero.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
message: str,
|
|
28
|
+
*,
|
|
29
|
+
code: str | None = None,
|
|
30
|
+
attempts_remaining: int | None = None,
|
|
31
|
+
) -> None:
|
|
32
|
+
super().__init__(message, code=code)
|
|
33
|
+
self.attempts_remaining = attempts_remaining
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class NotLoggedInError(ClientError):
|
|
37
|
+
"""A data call was made before ``login()`` succeeded (or after a 401)."""
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Typed models for United Utilities API responses.
|
|
2
|
+
|
|
3
|
+
Field coverage is deliberately partial: only what a Home Assistant integration
|
|
4
|
+
needs. Shapes were confirmed against live production responses (app build 102).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from datetime import date
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from ._parsing import parse_date, parse_int
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class AccountHistoryItem:
|
|
18
|
+
amount: float | None
|
|
19
|
+
date: date | None
|
|
20
|
+
type: str | None # "BI" = bill, "PA" = payment
|
|
21
|
+
bill_cancelled: bool | None
|
|
22
|
+
|
|
23
|
+
@classmethod
|
|
24
|
+
def from_json(cls, d: dict[str, Any]) -> AccountHistoryItem:
|
|
25
|
+
return cls(
|
|
26
|
+
amount=d.get("amount"),
|
|
27
|
+
date=parse_date(d.get("date")),
|
|
28
|
+
type=d.get("type"),
|
|
29
|
+
bill_cancelled=d.get("billCancelled"),
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class AccountDetails:
|
|
35
|
+
account_balance: float | None
|
|
36
|
+
next_payment_date: date | None
|
|
37
|
+
next_payment_due: float | None
|
|
38
|
+
is_on_meter: bool | None
|
|
39
|
+
can_submit_meter_reading: bool | None
|
|
40
|
+
payment_plan: str | None
|
|
41
|
+
payment_plan_status: str | None
|
|
42
|
+
is_active: bool | None
|
|
43
|
+
has_missed_payment: bool | None
|
|
44
|
+
unread_bill_count: int | None
|
|
45
|
+
billing_preference: str | None
|
|
46
|
+
account_history: list[AccountHistoryItem]
|
|
47
|
+
|
|
48
|
+
@classmethod
|
|
49
|
+
def from_json(cls, d: dict[str, Any]) -> AccountDetails:
|
|
50
|
+
return cls(
|
|
51
|
+
account_balance=d.get("accountBalance"),
|
|
52
|
+
next_payment_date=parse_date(d.get("nextPaymentDate")),
|
|
53
|
+
next_payment_due=d.get("nextPaymentDue"),
|
|
54
|
+
is_on_meter=d.get("isOnMeter"),
|
|
55
|
+
can_submit_meter_reading=d.get("canSubmitMeterReading"),
|
|
56
|
+
payment_plan=d.get("paymentPlan"),
|
|
57
|
+
payment_plan_status=d.get("paymentPlanStatus"),
|
|
58
|
+
is_active=d.get("isActive"),
|
|
59
|
+
has_missed_payment=d.get("hasMissedPayment"),
|
|
60
|
+
unread_bill_count=d.get("getUnreadBillCount"),
|
|
61
|
+
billing_preference=d.get("billingPreference"),
|
|
62
|
+
account_history=[AccountHistoryItem.from_json(x) for x in d.get("accountHistory") or []],
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class MeterReading:
|
|
68
|
+
date: date | None
|
|
69
|
+
value: int | None
|
|
70
|
+
reading_type: str | None # "C" = customer, "R" = company read
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def from_json(cls, d: dict[str, Any]) -> MeterReading:
|
|
74
|
+
return cls(
|
|
75
|
+
date=parse_date(d.get("date")),
|
|
76
|
+
value=parse_int(d.get("value")),
|
|
77
|
+
reading_type=d.get("readingType"),
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True)
|
|
82
|
+
class MeterDetails:
|
|
83
|
+
meter_location: str | None
|
|
84
|
+
serial_number: str | None
|
|
85
|
+
number_of_dials: int | None
|
|
86
|
+
window_start_date: date | None
|
|
87
|
+
window_end_date: date | None
|
|
88
|
+
last_routine_read: int | None
|
|
89
|
+
last_reading_type: str | None
|
|
90
|
+
error_code: str | None
|
|
91
|
+
error_text: str | None
|
|
92
|
+
|
|
93
|
+
@classmethod
|
|
94
|
+
def from_json(cls, d: dict[str, Any]) -> MeterDetails:
|
|
95
|
+
return cls(
|
|
96
|
+
meter_location=d.get("meterLocation"),
|
|
97
|
+
serial_number=d.get("serialNumber"),
|
|
98
|
+
number_of_dials=d.get("numberOfDials"),
|
|
99
|
+
window_start_date=parse_date(d.get("windowStartDate")),
|
|
100
|
+
window_end_date=parse_date(d.get("windowEndDate")),
|
|
101
|
+
last_routine_read=parse_int(d.get("lastRoutineRead")),
|
|
102
|
+
last_reading_type=d.get("lastReadingType"),
|
|
103
|
+
error_code=d.get("errorCode"),
|
|
104
|
+
error_text=d.get("errorText"),
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass(frozen=True)
|
|
109
|
+
class MeterReadings:
|
|
110
|
+
details: MeterDetails | None
|
|
111
|
+
readings: list[MeterReading]
|
|
112
|
+
next_reading_date: date | None
|
|
113
|
+
|
|
114
|
+
@classmethod
|
|
115
|
+
def from_json(cls, d: dict[str, Any]) -> MeterReadings:
|
|
116
|
+
details = d.get("details")
|
|
117
|
+
return cls(
|
|
118
|
+
details=MeterDetails.from_json(details) if details else None,
|
|
119
|
+
readings=[MeterReading.from_json(x) for x in d.get("readings") or []],
|
|
120
|
+
next_reading_date=parse_date(d.get("nextReadingDate")),
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def latest(self) -> MeterReading | None:
|
|
125
|
+
"""Most recent reading, or None if there are no readings."""
|
|
126
|
+
return self.readings[0] if self.readings else None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@dataclass(frozen=True)
|
|
130
|
+
class BillingPeriod:
|
|
131
|
+
start: date | None
|
|
132
|
+
end: date | None
|
|
133
|
+
|
|
134
|
+
@classmethod
|
|
135
|
+
def from_json(cls, d: dict[str, Any]) -> BillingPeriod:
|
|
136
|
+
return cls(
|
|
137
|
+
start=parse_date(d.get("billPeriodStartDate")),
|
|
138
|
+
end=parse_date(d.get("billPeriodEndDate")),
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@dataclass(frozen=True)
|
|
143
|
+
class StatementItem:
|
|
144
|
+
item_type: str | None # "BI" = bill, "PA" = payment
|
|
145
|
+
date: date | None
|
|
146
|
+
amount: float | None
|
|
147
|
+
new_balance: float | None
|
|
148
|
+
previous_balance: float | None
|
|
149
|
+
billing_period: BillingPeriod | None
|
|
150
|
+
bill_cancelled: bool | None
|
|
151
|
+
document_id: str | None
|
|
152
|
+
|
|
153
|
+
@classmethod
|
|
154
|
+
def from_json(cls, d: dict[str, Any]) -> StatementItem:
|
|
155
|
+
period = d.get("billingPeriod")
|
|
156
|
+
return cls(
|
|
157
|
+
item_type=d.get("itemType"),
|
|
158
|
+
date=parse_date(d.get("date")),
|
|
159
|
+
amount=d.get("amount"),
|
|
160
|
+
new_balance=d.get("newBalance"),
|
|
161
|
+
previous_balance=d.get("previousBalance"),
|
|
162
|
+
billing_period=BillingPeriod.from_json(period) if period else None,
|
|
163
|
+
bill_cancelled=d.get("billCancelled"),
|
|
164
|
+
document_id=d.get("documentId"),
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@dataclass(frozen=True)
|
|
169
|
+
class PaymentInfo:
|
|
170
|
+
current_balance: float | None
|
|
171
|
+
minimum_payment: float | None
|
|
172
|
+
court_debt: bool | None
|
|
173
|
+
|
|
174
|
+
@classmethod
|
|
175
|
+
def from_json(cls, d: dict[str, Any]) -> PaymentInfo:
|
|
176
|
+
return cls(
|
|
177
|
+
current_balance=d.get("currentBalance"),
|
|
178
|
+
minimum_payment=d.get("minimumPayment"),
|
|
179
|
+
court_debt=d.get("courtDebt"),
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@dataclass(frozen=True)
|
|
184
|
+
class Preferences:
|
|
185
|
+
notifications_system_enabled: bool | None
|
|
186
|
+
notify_other: bool | None
|
|
187
|
+
notify_payment: bool | None
|
|
188
|
+
|
|
189
|
+
@classmethod
|
|
190
|
+
def from_json(cls, d: dict[str, Any]) -> Preferences:
|
|
191
|
+
return cls(
|
|
192
|
+
notifications_system_enabled=d.get("notificationsSystemEnabled"),
|
|
193
|
+
notify_other=d.get("notifyOther"),
|
|
194
|
+
notify_payment=d.get("notifyPayment"),
|
|
195
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: united-utilities
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Async Python client for the United Utilities mobile API (unofficial, reverse-engineered)
|
|
5
|
+
Author: Kieran Roper
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/KRoperUK/united-utilities-py
|
|
8
|
+
Project-URL: Repository, https://github.com/KRoperUK/united-utilities-py
|
|
9
|
+
Project-URL: Issues, https://github.com/KRoperUK/united-utilities-py/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/KRoperUK/united-utilities-py/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: united-utilities,water,utility,asyncio,homeassistant
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Framework :: AsyncIO
|
|
19
|
+
Classifier: Topic :: Home Automation
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.12
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: aiohttp>=3.9
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
27
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
|
|
28
|
+
Requires-Dist: pytest-cov>=5; extra == "dev"
|
|
29
|
+
Requires-Dist: aresponses>=3.0; extra == "dev"
|
|
30
|
+
Requires-Dist: ruff>=0.8; extra == "dev"
|
|
31
|
+
Requires-Dist: mypy>=1.13; extra == "dev"
|
|
32
|
+
Dynamic: license-file
|
|
33
|
+
|
|
34
|
+
# united-utilities-py
|
|
35
|
+
|
|
36
|
+
Async Python client for the **United Utilities** "Your Water" mobile API,
|
|
37
|
+
reverse-engineered from the app (build 102). Pairs with a Home Assistant
|
|
38
|
+
integration (`united-utilities-hass`).
|
|
39
|
+
|
|
40
|
+
> Unofficial. Uses a private app API that United Utilities can change or
|
|
41
|
+
> withdraw at any time. For personal use with your own account.
|
|
42
|
+
|
|
43
|
+
## Why the mobile API (not the website)
|
|
44
|
+
|
|
45
|
+
The `myaccount.unitedutilities.com` website is gated behind Google reCAPTCHA
|
|
46
|
+
Enterprise and Jscrambler, so a scripted login needs a real browser. The mobile
|
|
47
|
+
app talks to a separate gateway (`prd-mobile-apigateway.unitedutilities.com`)
|
|
48
|
+
with a far simpler scheme: a static app `apiKey` header plus a `customerId` +
|
|
49
|
+
numeric `PIN` login that returns a session token. No captcha.
|
|
50
|
+
|
|
51
|
+
## Credentials
|
|
52
|
+
|
|
53
|
+
The mobile API does **not** use your website email/password. It needs:
|
|
54
|
+
|
|
55
|
+
- **`customerId`** — a numeric id assigned when you register in the app.
|
|
56
|
+
- **`pin`** — the numeric PIN you set in the app.
|
|
57
|
+
- **`accountNumber`** — your water account number (for account-scoped calls).
|
|
58
|
+
|
|
59
|
+
The easiest way to find `customerId` is to capture the app's `api/account/login`
|
|
60
|
+
request once; the body is `customerId=…&pin=…&platform=…` (form-encoded). The
|
|
61
|
+
app pins its TLS certificate, so an intercepting proxy breaks the app's *data*
|
|
62
|
+
calls even though the login call goes through — that's expected.
|
|
63
|
+
|
|
64
|
+
> ⚠️ **Login has a 3-strike lockout.** A wrong PIN decrements
|
|
65
|
+
> `attemptsRemaining`; at zero the account locks. This client never retries
|
|
66
|
+
> `login()`. Do not loop on `AuthError`.
|
|
67
|
+
|
|
68
|
+
## Install
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
pip install united-utilities
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Usage
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
import asyncio
|
|
78
|
+
from united_utilities import UnitedUtilitiesClient
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
async def main() -> None:
|
|
82
|
+
async with UnitedUtilitiesClient("24000000", "000000", "4000000000") as uu:
|
|
83
|
+
await uu.login()
|
|
84
|
+
details = await uu.account_details()
|
|
85
|
+
meter = await uu.meter_readings()
|
|
86
|
+
print("balance:", details.account_balance)
|
|
87
|
+
if meter.latest:
|
|
88
|
+
print("last read:", meter.latest.value, "on", meter.latest.date)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
asyncio.run(main())
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
In Home Assistant, pass the shared session:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
|
98
|
+
|
|
99
|
+
client = UnitedUtilitiesClient(customer_id, pin, account_number,
|
|
100
|
+
session=async_get_clientsession(hass))
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Endpoints covered
|
|
104
|
+
|
|
105
|
+
| Method | Returns |
|
|
106
|
+
| --- | --- |
|
|
107
|
+
| `login()` / `logout()` | session token lifecycle |
|
|
108
|
+
| `account_details()` | balance, next payment, meter flag, payment plan, bill count |
|
|
109
|
+
| `meter_readings()` | meter details + reading history (`.latest`) |
|
|
110
|
+
| `statement()` | itemised bills & payments |
|
|
111
|
+
| `payment_info()` | current balance, minimum payment |
|
|
112
|
+
| `preferences()` | notification preferences |
|
|
113
|
+
| `notifications()` | customer notifications |
|
|
114
|
+
|
|
115
|
+
## Development
|
|
116
|
+
|
|
117
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md). Response shapes were confirmed against
|
|
118
|
+
live production responses; tests run on synthetic fixtures (no real account
|
|
119
|
+
data) with `aresponses`.
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
MIT
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/united_utilities/__init__.py
|
|
5
|
+
src/united_utilities/_parsing.py
|
|
6
|
+
src/united_utilities/client.py
|
|
7
|
+
src/united_utilities/const.py
|
|
8
|
+
src/united_utilities/exceptions.py
|
|
9
|
+
src/united_utilities/models.py
|
|
10
|
+
src/united_utilities/py.typed
|
|
11
|
+
src/united_utilities.egg-info/PKG-INFO
|
|
12
|
+
src/united_utilities.egg-info/SOURCES.txt
|
|
13
|
+
src/united_utilities.egg-info/dependency_links.txt
|
|
14
|
+
src/united_utilities.egg-info/requires.txt
|
|
15
|
+
src/united_utilities.egg-info/top_level.txt
|
|
16
|
+
tests/test_client.py
|
|
17
|
+
tests/test_parsing.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
united_utilities
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
5
|
+
from datetime import date
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import aiohttp
|
|
10
|
+
import pytest
|
|
11
|
+
from aiohttp import web
|
|
12
|
+
from aresponses import ResponsesMockServer
|
|
13
|
+
|
|
14
|
+
from united_utilities import (
|
|
15
|
+
API_KEY,
|
|
16
|
+
AuthError,
|
|
17
|
+
NotLoggedInError,
|
|
18
|
+
UnitedUtilitiesClient,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
FIXTURES = Path(__file__).parent / "fixtures"
|
|
22
|
+
TEST_HOST = "uu.test"
|
|
23
|
+
TEST_BASE_URL = f"https://{TEST_HOST}"
|
|
24
|
+
|
|
25
|
+
Handler = Callable[[web.Request], Awaitable[web.Response]]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _fixture(name: str) -> dict[str, Any]:
|
|
29
|
+
data: dict[str, Any] = json.loads((FIXTURES / name).read_text())
|
|
30
|
+
return data
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _json(payload: Any, status: int = 200) -> web.Response:
|
|
34
|
+
return web.json_response(payload, status=status)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _capture(captured: dict[str, Any], payload: Any, status: int = 200) -> Handler:
|
|
38
|
+
"""Handler that records headers + body, then returns ``payload``."""
|
|
39
|
+
|
|
40
|
+
async def handler(request: web.Request) -> web.Response:
|
|
41
|
+
captured["headers"] = dict(request.headers)
|
|
42
|
+
captured["content_type"] = request.content_type
|
|
43
|
+
captured["body"] = await request.text()
|
|
44
|
+
return _json(payload, status)
|
|
45
|
+
|
|
46
|
+
return handler
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@pytest.fixture
|
|
50
|
+
async def session() -> AsyncIterator[aiohttp.ClientSession]:
|
|
51
|
+
async with aiohttp.ClientSession() as client_session:
|
|
52
|
+
yield client_session
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@pytest.fixture
|
|
56
|
+
def client(session: aiohttp.ClientSession) -> UnitedUtilitiesClient:
|
|
57
|
+
return UnitedUtilitiesClient(
|
|
58
|
+
"24000000",
|
|
59
|
+
"000000",
|
|
60
|
+
account_number="4000000000",
|
|
61
|
+
session=session,
|
|
62
|
+
base_url=TEST_BASE_URL,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _add_login(aresponses: ResponsesMockServer, token: str = "t") -> None:
|
|
67
|
+
aresponses.add(TEST_HOST, "/api/account/login", "POST", _json({"sessionToken": token}))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def test_login_success_sets_token(client: UnitedUtilitiesClient, aresponses: ResponsesMockServer) -> None:
|
|
71
|
+
captured: dict[str, Any] = {}
|
|
72
|
+
aresponses.add(
|
|
73
|
+
TEST_HOST,
|
|
74
|
+
"/api/account/login",
|
|
75
|
+
"POST",
|
|
76
|
+
_capture(captured, {"sessionToken": "abc123", "isWeakPIN": None}),
|
|
77
|
+
)
|
|
78
|
+
await client.login()
|
|
79
|
+
|
|
80
|
+
assert client.logged_in
|
|
81
|
+
assert captured["headers"]["apiKey"] == API_KEY
|
|
82
|
+
# Login must be form-encoded, not JSON.
|
|
83
|
+
assert captured["content_type"] == "application/x-www-form-urlencoded"
|
|
84
|
+
assert "customerId=24000000" in captured["body"]
|
|
85
|
+
assert "pin=000000" in captured["body"]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
async def test_login_rejected_raises_with_attempts(
|
|
89
|
+
client: UnitedUtilitiesClient, aresponses: ResponsesMockServer
|
|
90
|
+
) -> None:
|
|
91
|
+
aresponses.add(TEST_HOST, "/api/account/login", "POST", _json({"attemptsRemaining": 2}, 401))
|
|
92
|
+
with pytest.raises(AuthError) as excinfo:
|
|
93
|
+
await client.login()
|
|
94
|
+
|
|
95
|
+
assert excinfo.value.attempts_remaining == 2
|
|
96
|
+
assert not client.logged_in
|
|
97
|
+
# Only one login route was registered; a retry would hit an unmatched route.
|
|
98
|
+
aresponses.assert_plan_strictly_followed()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
async def test_data_call_before_login_raises(client: UnitedUtilitiesClient) -> None:
|
|
102
|
+
with pytest.raises(NotLoggedInError):
|
|
103
|
+
await client.account_details()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
async def test_account_details_parsed(client: UnitedUtilitiesClient, aresponses: ResponsesMockServer) -> None:
|
|
107
|
+
captured: dict[str, Any] = {}
|
|
108
|
+
_add_login(aresponses)
|
|
109
|
+
aresponses.add(
|
|
110
|
+
TEST_HOST,
|
|
111
|
+
"/api/account/details",
|
|
112
|
+
"POST",
|
|
113
|
+
_capture(captured, _fixture("account_details.json")),
|
|
114
|
+
)
|
|
115
|
+
await client.login()
|
|
116
|
+
details = await client.account_details()
|
|
117
|
+
|
|
118
|
+
assert details.account_balance == 80.58
|
|
119
|
+
assert details.next_payment_due == 51.78
|
|
120
|
+
assert details.next_payment_date == date(2026, 11, 23)
|
|
121
|
+
assert details.is_on_meter is True
|
|
122
|
+
assert details.unread_bill_count == 2
|
|
123
|
+
assert len(details.account_history) == 2
|
|
124
|
+
assert details.account_history[0].type == "BI"
|
|
125
|
+
|
|
126
|
+
assert captured["headers"]["token"] == "t"
|
|
127
|
+
assert captured["headers"]["apiKey"] == API_KEY
|
|
128
|
+
assert json.loads(captured["body"]) == {"accountNumber": "4000000000"}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
async def test_meter_readings_parsed(client: UnitedUtilitiesClient, aresponses: ResponsesMockServer) -> None:
|
|
132
|
+
_add_login(aresponses)
|
|
133
|
+
aresponses.add(TEST_HOST, "/api/reading/meterreading", "POST", _json(_fixture("meterreading.json")))
|
|
134
|
+
await client.login()
|
|
135
|
+
meter = await client.meter_readings()
|
|
136
|
+
|
|
137
|
+
assert meter.details is not None
|
|
138
|
+
assert meter.details.serial_number == "00A000000"
|
|
139
|
+
assert meter.details.last_routine_read == 1975
|
|
140
|
+
assert len(meter.readings) == 2
|
|
141
|
+
assert meter.latest is not None
|
|
142
|
+
assert meter.latest.value == 1975
|
|
143
|
+
assert meter.latest.date == date(2026, 11, 21)
|
|
144
|
+
assert meter.next_reading_date == date(2027, 4, 9)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
async def test_statement_parsed(client: UnitedUtilitiesClient, aresponses: ResponsesMockServer) -> None:
|
|
148
|
+
_add_login(aresponses)
|
|
149
|
+
aresponses.add(TEST_HOST, "/api/statement", "POST", _json(_fixture("statement.json")))
|
|
150
|
+
await client.login()
|
|
151
|
+
items = await client.statement()
|
|
152
|
+
|
|
153
|
+
assert len(items) == 2
|
|
154
|
+
bill = items[0]
|
|
155
|
+
assert bill.item_type == "BI"
|
|
156
|
+
assert bill.amount == 76.51
|
|
157
|
+
assert bill.billing_period is not None
|
|
158
|
+
assert bill.billing_period.start == date(2026, 10, 9)
|
|
159
|
+
assert items[1].billing_period is None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
async def test_payment_info_parsed(client: UnitedUtilitiesClient, aresponses: ResponsesMockServer) -> None:
|
|
163
|
+
_add_login(aresponses)
|
|
164
|
+
aresponses.add(
|
|
165
|
+
TEST_HOST,
|
|
166
|
+
"/api/payment",
|
|
167
|
+
"POST",
|
|
168
|
+
_json({"currentBalance": 80.58, "minimumPayment": 0.0, "courtDebt": False}),
|
|
169
|
+
)
|
|
170
|
+
await client.login()
|
|
171
|
+
info = await client.payment_info()
|
|
172
|
+
|
|
173
|
+
assert info.current_balance == 80.58
|
|
174
|
+
assert info.minimum_payment == 0.0
|
|
175
|
+
assert info.court_debt is False
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
async def test_preferences_and_notifications(client: UnitedUtilitiesClient, aresponses: ResponsesMockServer) -> None:
|
|
179
|
+
_add_login(aresponses)
|
|
180
|
+
aresponses.add(
|
|
181
|
+
TEST_HOST,
|
|
182
|
+
"/api/account/preferences",
|
|
183
|
+
"GET",
|
|
184
|
+
_json({"notificationsSystemEnabled": False, "notifyOther": False, "notifyPayment": True}),
|
|
185
|
+
)
|
|
186
|
+
aresponses.add(TEST_HOST, "/api/account/GetCustomerNotifications", "GET", _json({"notifications": []}))
|
|
187
|
+
await client.login()
|
|
188
|
+
|
|
189
|
+
prefs = await client.preferences()
|
|
190
|
+
assert prefs.notify_payment is True
|
|
191
|
+
assert await client.notifications() == []
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
async def test_expired_token_surfaces_not_logged_in(
|
|
195
|
+
client: UnitedUtilitiesClient, aresponses: ResponsesMockServer
|
|
196
|
+
) -> None:
|
|
197
|
+
_add_login(aresponses)
|
|
198
|
+
aresponses.add(TEST_HOST, "/api/payment", "POST", aresponses.Response(status=401))
|
|
199
|
+
await client.login()
|
|
200
|
+
|
|
201
|
+
with pytest.raises(NotLoggedInError):
|
|
202
|
+
await client.payment_info()
|
|
203
|
+
assert not client.logged_in # token cleared so caller re-logs in deliberately
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
async def test_logout_clears_token(client: UnitedUtilitiesClient, aresponses: ResponsesMockServer) -> None:
|
|
207
|
+
captured: dict[str, Any] = {}
|
|
208
|
+
_add_login(aresponses)
|
|
209
|
+
aresponses.add(TEST_HOST, "/api/account/logout", "POST", _capture(captured, {"sessionToken": ""}))
|
|
210
|
+
await client.login()
|
|
211
|
+
await client.logout()
|
|
212
|
+
assert not client.logged_in
|
|
213
|
+
# Body-less POSTs are 403'd by the gateway WAF, so logout must send a JSON body.
|
|
214
|
+
assert captured["content_type"] == "application/json"
|
|
215
|
+
assert json.loads(captured["body"]) == {}
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
async def test_server_error_raises_client_error(client: UnitedUtilitiesClient, aresponses: ResponsesMockServer) -> None:
|
|
219
|
+
from united_utilities import ClientError
|
|
220
|
+
|
|
221
|
+
_add_login(aresponses)
|
|
222
|
+
aresponses.add(TEST_HOST, "/api/account/details", "POST", aresponses.Response(status=500))
|
|
223
|
+
await client.login()
|
|
224
|
+
|
|
225
|
+
with pytest.raises(ClientError) as excinfo:
|
|
226
|
+
await client.account_details()
|
|
227
|
+
assert excinfo.value.code == "500"
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from datetime import date
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from united_utilities._parsing import parse_date, parse_int
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@pytest.mark.parametrize(
|
|
11
|
+
("raw", "expected"),
|
|
12
|
+
[
|
|
13
|
+
("21112026", date(2026, 11, 21)),
|
|
14
|
+
("09042027", date(2027, 4, 9)),
|
|
15
|
+
("", None),
|
|
16
|
+
(None, None),
|
|
17
|
+
("2111202", None), # too short
|
|
18
|
+
("32112026", None), # invalid day
|
|
19
|
+
("abcdefgh", None),
|
|
20
|
+
],
|
|
21
|
+
)
|
|
22
|
+
def test_parse_date(raw: str | None, expected: date | None) -> None:
|
|
23
|
+
assert parse_date(raw) == expected
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@pytest.mark.parametrize(
|
|
27
|
+
("raw", "expected"),
|
|
28
|
+
[("1975", 1975), (1965, 1965), ("", None), (None, None), ("x", None)],
|
|
29
|
+
)
|
|
30
|
+
def test_parse_int(raw: str | int | None, expected: int | None) -> None:
|
|
31
|
+
assert parse_int(raw) == expected
|