aioratio 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.
- aioratio-0.1.0/.github/workflows/ci.yml +21 -0
- aioratio-0.1.0/.github/workflows/publish.yml +35 -0
- aioratio-0.1.0/.gitignore +35 -0
- aioratio-0.1.0/LICENSE +21 -0
- aioratio-0.1.0/PKG-INFO +36 -0
- aioratio-0.1.0/README.md +3 -0
- aioratio-0.1.0/pyproject.toml +48 -0
- aioratio-0.1.0/scripts/smoke.py +203 -0
- aioratio-0.1.0/src/aioratio/__init__.py +27 -0
- aioratio-0.1.0/src/aioratio/_transport.py +132 -0
- aioratio-0.1.0/src/aioratio/auth.py +396 -0
- aioratio-0.1.0/src/aioratio/client.py +387 -0
- aioratio-0.1.0/src/aioratio/const.py +11 -0
- aioratio-0.1.0/src/aioratio/exceptions.py +22 -0
- aioratio-0.1.0/src/aioratio/models/__init__.py +61 -0
- aioratio-0.1.0/src/aioratio/models/charger.py +210 -0
- aioratio-0.1.0/src/aioratio/models/command.py +91 -0
- aioratio-0.1.0/src/aioratio/models/history.py +82 -0
- aioratio-0.1.0/src/aioratio/models/settings.py +219 -0
- aioratio-0.1.0/src/aioratio/models/vehicle.py +40 -0
- aioratio-0.1.0/src/aioratio/py.typed +0 -0
- aioratio-0.1.0/src/aioratio/srp.py +333 -0
- aioratio-0.1.0/src/aioratio/token_store.py +141 -0
- aioratio-0.1.0/tests/__init__.py +0 -0
- aioratio-0.1.0/tests/conftest.py +2 -0
- aioratio-0.1.0/tests/test_auth.py +450 -0
- aioratio-0.1.0/tests/test_client.py +590 -0
- aioratio-0.1.0/tests/test_models.py +333 -0
- aioratio-0.1.0/tests/test_srp.py +256 -0
- aioratio-0.1.0/tests/test_token_store.py +157 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
name: ci
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [master]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
test:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
strategy:
|
|
12
|
+
matrix:
|
|
13
|
+
python-version: ["3.11", "3.12", "3.13"]
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: actions/setup-python@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: ${{ matrix.python-version }}
|
|
19
|
+
- run: python -m pip install --upgrade pip
|
|
20
|
+
- run: pip install -e '.[dev]'
|
|
21
|
+
- run: pytest -q
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
name: publish
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags:
|
|
6
|
+
- "v*"
|
|
7
|
+
workflow_dispatch:
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
build:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
steps:
|
|
13
|
+
- uses: actions/checkout@v4
|
|
14
|
+
- uses: actions/setup-python@v5
|
|
15
|
+
with:
|
|
16
|
+
python-version: "3.12"
|
|
17
|
+
- run: python -m pip install --upgrade build
|
|
18
|
+
- run: python -m build
|
|
19
|
+
- uses: actions/upload-artifact@v4
|
|
20
|
+
with:
|
|
21
|
+
name: dist
|
|
22
|
+
path: dist/
|
|
23
|
+
|
|
24
|
+
publish:
|
|
25
|
+
needs: build
|
|
26
|
+
runs-on: ubuntu-latest
|
|
27
|
+
environment: pypi
|
|
28
|
+
permissions:
|
|
29
|
+
id-token: write
|
|
30
|
+
steps:
|
|
31
|
+
- uses: actions/download-artifact@v4
|
|
32
|
+
with:
|
|
33
|
+
name: dist
|
|
34
|
+
path: dist/
|
|
35
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# Distribution / packaging
|
|
7
|
+
.Python
|
|
8
|
+
build/
|
|
9
|
+
dist/
|
|
10
|
+
*.egg-info/
|
|
11
|
+
*.egg
|
|
12
|
+
wheels/
|
|
13
|
+
|
|
14
|
+
# Virtual environments
|
|
15
|
+
.venv/
|
|
16
|
+
venv/
|
|
17
|
+
env/
|
|
18
|
+
|
|
19
|
+
# Testing
|
|
20
|
+
.pytest_cache/
|
|
21
|
+
.mypy_cache/
|
|
22
|
+
.coverage
|
|
23
|
+
htmlcov/
|
|
24
|
+
.tox/
|
|
25
|
+
|
|
26
|
+
# IDE
|
|
27
|
+
.vscode/
|
|
28
|
+
.idea/
|
|
29
|
+
*.swp
|
|
30
|
+
|
|
31
|
+
# OS
|
|
32
|
+
.DS_Store
|
|
33
|
+
.claude/
|
|
34
|
+
smoke.tokens.json
|
|
35
|
+
scripts/__pycache__/
|
aioratio-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tim <tim@iosharp.com>
|
|
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.
|
aioratio-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: aioratio
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async Python client for the Ratio EV Charging cloud API
|
|
5
|
+
Project-URL: Homepage, https://github.com/aaearon/aioratio
|
|
6
|
+
Project-URL: Source, https://github.com/aaearon/aioratio
|
|
7
|
+
Project-URL: Issues, https://github.com/aaearon/aioratio/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/aaearon/aioratio/releases
|
|
9
|
+
Author-email: Tim <tim@iosharp.com>
|
|
10
|
+
License: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: async,charger,cognito,ev,home-assistant,ratio
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Framework :: AsyncIO
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Home Automation
|
|
23
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
24
|
+
Classifier: Typing :: Typed
|
|
25
|
+
Requires-Python: >=3.11
|
|
26
|
+
Requires-Dist: aiohttp>=3.9
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: mypy>=1.8; extra == 'dev'
|
|
29
|
+
Requires-Dist: pytest-aiohttp>=1.0; extra == 'dev'
|
|
30
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
31
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
# aioratio
|
|
35
|
+
|
|
36
|
+
Async Python client for the Ratio EV Charging cloud API.
|
aioratio-0.1.0/README.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "aioratio"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Async Python client for the Ratio EV Charging cloud API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
authors = [{ name = "Tim", email = "tim@iosharp.com" }]
|
|
13
|
+
keywords = ["ratio", "ev", "charger", "home-assistant", "cognito", "async"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Framework :: AsyncIO",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Topic :: Home Automation",
|
|
25
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
26
|
+
"Typing :: Typed",
|
|
27
|
+
]
|
|
28
|
+
dependencies = ["aiohttp>=3.9"]
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
Homepage = "https://github.com/aaearon/aioratio"
|
|
32
|
+
Source = "https://github.com/aaearon/aioratio"
|
|
33
|
+
Issues = "https://github.com/aaearon/aioratio/issues"
|
|
34
|
+
Changelog = "https://github.com/aaearon/aioratio/releases"
|
|
35
|
+
|
|
36
|
+
[project.optional-dependencies]
|
|
37
|
+
dev = [
|
|
38
|
+
"pytest>=8",
|
|
39
|
+
"pytest-asyncio>=0.23",
|
|
40
|
+
"pytest-aiohttp>=1.0",
|
|
41
|
+
"mypy>=1.8",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
[tool.hatch.build.targets.wheel]
|
|
45
|
+
packages = ["src/aioratio"]
|
|
46
|
+
|
|
47
|
+
[tool.pytest.ini_options]
|
|
48
|
+
asyncio_mode = "auto"
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""Live smoke test against the user's real Ratio account.
|
|
2
|
+
|
|
3
|
+
Reads credentials from ../.env. Persists tokens to ./smoke.tokens.json
|
|
4
|
+
(in cleartext — gitignored). Run multiple times to exercise refresh
|
|
5
|
+
and DEVICE_SRP_AUTH paths.
|
|
6
|
+
|
|
7
|
+
Usage:
|
|
8
|
+
python3 scripts/smoke.py [step]
|
|
9
|
+
step = all | login | overview | refresh | restart | rotation
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import asyncio
|
|
14
|
+
import sys
|
|
15
|
+
import time
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
import aiohttp
|
|
19
|
+
|
|
20
|
+
from aioratio import RatioClient
|
|
21
|
+
from aioratio.auth import CognitoSrpAuth
|
|
22
|
+
from aioratio.token_store import JsonFileTokenStore
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
REPO_ROOT = Path(__file__).resolve().parent.parent
|
|
26
|
+
ENV_PATH = REPO_ROOT.parent / ".env"
|
|
27
|
+
TOKENS_PATH = REPO_ROOT / "smoke.tokens.json"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def load_env() -> tuple[str, str]:
|
|
31
|
+
text = ENV_PATH.read_text()
|
|
32
|
+
env: dict[str, str] = {}
|
|
33
|
+
for line in text.splitlines():
|
|
34
|
+
line = line.strip()
|
|
35
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
36
|
+
continue
|
|
37
|
+
k, _, v = line.partition("=")
|
|
38
|
+
env[k.strip()] = v.strip()
|
|
39
|
+
return env["RATIO_USERNAME"], env["RATIO_PASSWORD"]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def redact(s: str | None, keep: int = 4) -> str:
|
|
43
|
+
if not s:
|
|
44
|
+
return "<none>"
|
|
45
|
+
if len(s) <= keep * 2:
|
|
46
|
+
return "***"
|
|
47
|
+
return f"{s[:keep]}...{s[-keep:]}"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
async def show_bundle(store: JsonFileTokenStore, label: str) -> None:
|
|
51
|
+
b = await store.load()
|
|
52
|
+
if b is None:
|
|
53
|
+
print(f" [{label}] bundle: None")
|
|
54
|
+
return
|
|
55
|
+
print(
|
|
56
|
+
f" [{label}] access={redact(b.access_token)} "
|
|
57
|
+
f"refresh={redact(b.refresh_token)} "
|
|
58
|
+
f"device_key={redact(b.device_key)} "
|
|
59
|
+
f"device_password={redact(b.device_password)} "
|
|
60
|
+
f"expires_in={int(b.expires_at - time.time())}s"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
async def step_login(email: str, password: str) -> None:
|
|
65
|
+
"""Step 1: First login from clean state. Removes any existing tokens."""
|
|
66
|
+
print("\n=== STEP 1: First login (clean state) ===")
|
|
67
|
+
if TOKENS_PATH.exists():
|
|
68
|
+
TOKENS_PATH.unlink()
|
|
69
|
+
print(" removed existing token file")
|
|
70
|
+
store = JsonFileTokenStore(TOKENS_PATH)
|
|
71
|
+
async with aiohttp.ClientSession() as s:
|
|
72
|
+
client = RatioClient(email=email, password=password, token_store=store, session=s)
|
|
73
|
+
await client.login()
|
|
74
|
+
print(" login OK")
|
|
75
|
+
await show_bundle(store, "post-login")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
async def step_overview(email: str, password: str) -> None:
|
|
79
|
+
"""Step 2: chargers_overview returns expected data."""
|
|
80
|
+
print("\n=== STEP 2: chargers_overview ===")
|
|
81
|
+
store = JsonFileTokenStore(TOKENS_PATH)
|
|
82
|
+
async with aiohttp.ClientSession() as s:
|
|
83
|
+
client = RatioClient(email=email, password=password, token_store=store, session=s)
|
|
84
|
+
overviews = await client.chargers_overview()
|
|
85
|
+
print(f" got {len(overviews)} charger(s)")
|
|
86
|
+
for o in overviews:
|
|
87
|
+
print(f" serial={redact(o.serial_number, 6)} status={getattr(o, 'status', None)}")
|
|
88
|
+
# Dump full structure (sanitised) for fixture capture
|
|
89
|
+
from dataclasses import asdict
|
|
90
|
+
print(f" raw fields: {list(asdict(o).keys())}")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
async def step_refresh(email: str, password: str) -> None:
|
|
94
|
+
"""Step 3: force-expire access token, observe refresh succeeds."""
|
|
95
|
+
print("\n=== STEP 3: refresh round-trip ===")
|
|
96
|
+
store = JsonFileTokenStore(TOKENS_PATH)
|
|
97
|
+
bundle = await store.load()
|
|
98
|
+
if bundle is None:
|
|
99
|
+
print(" no bundle — run login first")
|
|
100
|
+
return
|
|
101
|
+
old_access = bundle.access_token
|
|
102
|
+
old_refresh = bundle.refresh_token
|
|
103
|
+
# Force-expire
|
|
104
|
+
bundle.expires_at = 0
|
|
105
|
+
await store.save(bundle)
|
|
106
|
+
print(f" forced expiry; old_access={redact(old_access)}")
|
|
107
|
+
async with aiohttp.ClientSession() as s:
|
|
108
|
+
client = RatioClient(email=email, password=password, token_store=store, session=s)
|
|
109
|
+
overviews = await client.chargers_overview()
|
|
110
|
+
print(f" request after expiry succeeded, {len(overviews)} chargers")
|
|
111
|
+
new = await store.load()
|
|
112
|
+
assert new is not None
|
|
113
|
+
print(f" new_access={redact(new.access_token)}")
|
|
114
|
+
assert new.access_token != old_access, "access token did not rotate"
|
|
115
|
+
print(" access token rotated OK")
|
|
116
|
+
rotated = new.refresh_token != old_refresh
|
|
117
|
+
print(f" refresh token rotation: {'YES' if rotated else 'NO (kept old)'}")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
async def step_restart(email: str, password: str) -> None:
|
|
121
|
+
"""Step 4: drop in-memory state, reload from store, observe DEVICE_SRP_AUTH path on next login."""
|
|
122
|
+
print("\n=== STEP 4: restart simulation (DEVICE_SRP_AUTH path) ===")
|
|
123
|
+
store = JsonFileTokenStore(TOKENS_PATH)
|
|
124
|
+
bundle = await store.load()
|
|
125
|
+
if bundle is None or bundle.device_key is None:
|
|
126
|
+
print(" no device bundle — run login first")
|
|
127
|
+
return
|
|
128
|
+
# Force a full login (not refresh) by using the auth driver directly
|
|
129
|
+
print(f" using device_key={redact(bundle.device_key)}")
|
|
130
|
+
# Patch _cognito_call to log challenge progression
|
|
131
|
+
challenges: list[str] = []
|
|
132
|
+
|
|
133
|
+
async with aiohttp.ClientSession() as s:
|
|
134
|
+
auth = CognitoSrpAuth(
|
|
135
|
+
email=email, password=password, token_store=store, session=s,
|
|
136
|
+
)
|
|
137
|
+
orig = auth._cognito_call
|
|
138
|
+
|
|
139
|
+
async def trace(target, body):
|
|
140
|
+
r = await orig(target, body)
|
|
141
|
+
cn = r.get("ChallengeName")
|
|
142
|
+
if cn:
|
|
143
|
+
challenges.append(cn)
|
|
144
|
+
print(f" challenge: {cn}")
|
|
145
|
+
elif "AuthenticationResult" in r:
|
|
146
|
+
print(" AuthenticationResult received")
|
|
147
|
+
return r
|
|
148
|
+
|
|
149
|
+
auth._cognito_call = trace # type: ignore[assignment]
|
|
150
|
+
await auth.login()
|
|
151
|
+
print(f" challenge sequence: {challenges}")
|
|
152
|
+
if "DEVICE_SRP_AUTH" in challenges and "DEVICE_PASSWORD_VERIFIER" in challenges:
|
|
153
|
+
print(" DEVICE_SRP_AUTH path exercised OK")
|
|
154
|
+
else:
|
|
155
|
+
print(" WARNING: device path not exercised — check device persistence")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
async def step_commands(email: str, password: str) -> None:
|
|
159
|
+
"""Step 5: start_charge + stop_charge against real charger (car must NOT be plugged)."""
|
|
160
|
+
print("\n=== STEP 5: start/stop charge commands ===")
|
|
161
|
+
store = JsonFileTokenStore(TOKENS_PATH)
|
|
162
|
+
async with aiohttp.ClientSession() as s:
|
|
163
|
+
client = RatioClient(email=email, password=password, token_store=store, session=s)
|
|
164
|
+
overviews = await client.chargers_overview()
|
|
165
|
+
if not overviews:
|
|
166
|
+
print(" no chargers")
|
|
167
|
+
return
|
|
168
|
+
serial = overviews[0].serial_number
|
|
169
|
+
print(f" using serial={redact(serial, 6)}")
|
|
170
|
+
try:
|
|
171
|
+
print(" -> start_charge (no vehicle_id)")
|
|
172
|
+
await client.start_charge(serial)
|
|
173
|
+
print(" start_charge accepted")
|
|
174
|
+
except Exception as e:
|
|
175
|
+
print(f" start_charge raised: {type(e).__name__}: {e}")
|
|
176
|
+
await asyncio.sleep(2)
|
|
177
|
+
try:
|
|
178
|
+
print(" -> stop_charge")
|
|
179
|
+
await client.stop_charge(serial)
|
|
180
|
+
print(" stop_charge accepted")
|
|
181
|
+
except Exception as e:
|
|
182
|
+
print(f" stop_charge raised: {type(e).__name__}: {e}")
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
async def main() -> None:
|
|
186
|
+
step = sys.argv[1] if len(sys.argv) > 1 else "all"
|
|
187
|
+
email, password = load_env()
|
|
188
|
+
print(f"User: {email}")
|
|
189
|
+
|
|
190
|
+
if step in ("all", "login"):
|
|
191
|
+
await step_login(email, password)
|
|
192
|
+
if step in ("all", "overview"):
|
|
193
|
+
await step_overview(email, password)
|
|
194
|
+
if step in ("all", "refresh"):
|
|
195
|
+
await step_refresh(email, password)
|
|
196
|
+
if step in ("all", "restart"):
|
|
197
|
+
await step_restart(email, password)
|
|
198
|
+
if step in ("all", "commands"):
|
|
199
|
+
await step_commands(email, password)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
if __name__ == "__main__":
|
|
203
|
+
asyncio.run(main())
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""aioratio — async Python client for the Ratio EV Charging cloud API."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from .client import RatioClient
|
|
5
|
+
from .exceptions import (
|
|
6
|
+
RatioApiError,
|
|
7
|
+
RatioAuthError,
|
|
8
|
+
RatioConnectionError,
|
|
9
|
+
RatioError,
|
|
10
|
+
RatioRateLimitError,
|
|
11
|
+
)
|
|
12
|
+
from .token_store import JsonFileTokenStore, MemoryTokenStore, TokenBundle, TokenStore
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"RatioClient",
|
|
16
|
+
"RatioError",
|
|
17
|
+
"RatioAuthError",
|
|
18
|
+
"RatioApiError",
|
|
19
|
+
"RatioRateLimitError",
|
|
20
|
+
"RatioConnectionError",
|
|
21
|
+
"TokenStore",
|
|
22
|
+
"TokenBundle",
|
|
23
|
+
"MemoryTokenStore",
|
|
24
|
+
"JsonFileTokenStore",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Private HTTP transport for the Ratio cloud API.
|
|
2
|
+
|
|
3
|
+
Wraps an :class:`aiohttp.ClientSession` and a :class:`CognitoSrpAuth`
|
|
4
|
+
instance: every request is signed with a bearer access token and a
|
|
5
|
+
single 401 retry is attempted (forcing the auth driver to refresh or
|
|
6
|
+
re-login on the second call).
|
|
7
|
+
|
|
8
|
+
This module is intentionally private -- public callers go through
|
|
9
|
+
:class:`aioratio.client.RatioClient`.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import asyncio
|
|
14
|
+
import json as _json
|
|
15
|
+
from typing import TYPE_CHECKING, Any
|
|
16
|
+
|
|
17
|
+
import aiohttp
|
|
18
|
+
|
|
19
|
+
from .const import API_BASE_URL, USER_AGENT
|
|
20
|
+
from .exceptions import (
|
|
21
|
+
RatioApiError,
|
|
22
|
+
RatioAuthError,
|
|
23
|
+
RatioConnectionError,
|
|
24
|
+
RatioRateLimitError,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
if TYPE_CHECKING:
|
|
28
|
+
from .auth import CognitoSrpAuth
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _CloudTransport:
|
|
32
|
+
"""Private async HTTP transport for the Ratio cloud API."""
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
*,
|
|
37
|
+
auth: "CognitoSrpAuth",
|
|
38
|
+
session: aiohttp.ClientSession,
|
|
39
|
+
base_url: str = API_BASE_URL,
|
|
40
|
+
timeout: float = 30.0,
|
|
41
|
+
) -> None:
|
|
42
|
+
self._auth = auth
|
|
43
|
+
self._session = session
|
|
44
|
+
self._base_url = base_url.rstrip("/")
|
|
45
|
+
self._timeout = aiohttp.ClientTimeout(total=timeout)
|
|
46
|
+
|
|
47
|
+
async def request(
|
|
48
|
+
self,
|
|
49
|
+
method: str,
|
|
50
|
+
path: str,
|
|
51
|
+
*,
|
|
52
|
+
params: dict[str, Any] | None = None,
|
|
53
|
+
json: dict[str, Any] | None = None,
|
|
54
|
+
) -> Any:
|
|
55
|
+
"""Send an authenticated request and return parsed JSON or None."""
|
|
56
|
+
if not path.startswith("/"):
|
|
57
|
+
path = "/" + path
|
|
58
|
+
url = self._base_url + path
|
|
59
|
+
method_upper = method.upper()
|
|
60
|
+
|
|
61
|
+
retried = False
|
|
62
|
+
while True:
|
|
63
|
+
access_token = await self._auth.get_access_token()
|
|
64
|
+
headers = {
|
|
65
|
+
"Authorization": f"Bearer {access_token}",
|
|
66
|
+
"User-Agent": USER_AGENT,
|
|
67
|
+
"Accept": "application/json",
|
|
68
|
+
}
|
|
69
|
+
if method_upper != "GET" and json is not None:
|
|
70
|
+
headers["Content-Type"] = "application/json"
|
|
71
|
+
|
|
72
|
+
try:
|
|
73
|
+
async with self._session.request(
|
|
74
|
+
method_upper,
|
|
75
|
+
url,
|
|
76
|
+
params=params,
|
|
77
|
+
json=json,
|
|
78
|
+
headers=headers,
|
|
79
|
+
timeout=self._timeout,
|
|
80
|
+
) as resp:
|
|
81
|
+
status = resp.status
|
|
82
|
+
body_bytes = await resp.read()
|
|
83
|
+
content_type = resp.headers.get("Content-Type", "")
|
|
84
|
+
retry_after = resp.headers.get("Retry-After")
|
|
85
|
+
except aiohttp.ClientError as err:
|
|
86
|
+
raise RatioConnectionError(str(err)) from err
|
|
87
|
+
except asyncio.TimeoutError as err:
|
|
88
|
+
raise RatioConnectionError("request timed out") from err
|
|
89
|
+
|
|
90
|
+
if status == 401:
|
|
91
|
+
if retried:
|
|
92
|
+
raise RatioAuthError("authentication rejected after refresh")
|
|
93
|
+
retried = True
|
|
94
|
+
# Best-effort: expire any cached bundle so the next
|
|
95
|
+
# get_access_token() forces a refresh or re-login.
|
|
96
|
+
store = getattr(self._auth, "_token_store", None)
|
|
97
|
+
if store is not None:
|
|
98
|
+
try:
|
|
99
|
+
bundle = await store.load()
|
|
100
|
+
except Exception: # pragma: no cover - defensive
|
|
101
|
+
bundle = None
|
|
102
|
+
if bundle is not None:
|
|
103
|
+
bundle.expires_at = 0.0
|
|
104
|
+
try:
|
|
105
|
+
await store.save(bundle)
|
|
106
|
+
except Exception: # pragma: no cover - defensive
|
|
107
|
+
pass
|
|
108
|
+
continue
|
|
109
|
+
|
|
110
|
+
if status == 429:
|
|
111
|
+
msg = "rate limit exceeded"
|
|
112
|
+
if retry_after:
|
|
113
|
+
msg = f"{msg} (retry-after={retry_after})"
|
|
114
|
+
raise RatioRateLimitError(msg)
|
|
115
|
+
|
|
116
|
+
if status >= 400:
|
|
117
|
+
body_text = body_bytes.decode("utf-8", errors="replace")
|
|
118
|
+
raise RatioApiError(f"HTTP {status}: {body_text}")
|
|
119
|
+
|
|
120
|
+
if not body_bytes:
|
|
121
|
+
return None
|
|
122
|
+
if "json" in content_type.lower() or body_bytes.lstrip().startswith(
|
|
123
|
+
(b"{", b"[")
|
|
124
|
+
):
|
|
125
|
+
try:
|
|
126
|
+
return _json.loads(body_bytes.decode("utf-8"))
|
|
127
|
+
except ValueError as err:
|
|
128
|
+
raise RatioApiError(f"invalid JSON response: {err}") from err
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
__all__ = ["_CloudTransport"]
|