gauger 4.0.0__py3-none-any.whl

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.
gauger/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ """gauger — async client library and CLI for the GREMLIN tank monitoring API.
2
+
3
+ The name: a *gauger* measures the contents of a tank; this project is a
4
+ digital one for Angus Energy GREMLIN tank monitors.
5
+ """
6
+
7
+ from .api import GremlinClient
8
+ from .auth import TokenStore
9
+ from .config import Hosts
10
+ from .exceptions import AuthenticationError, GremlinAPIError
11
+
12
+ __version__ = "4.0.0"
13
+ __all__ = [
14
+ "GremlinClient",
15
+ "TokenStore",
16
+ "Hosts",
17
+ "GremlinAPIError",
18
+ "AuthenticationError",
19
+ "__version__",
20
+ ]
gauger/api/__init__.py ADDED
@@ -0,0 +1,147 @@
1
+ """GremlinClient — the async facade composing the endpoint-group mixins.
2
+
3
+ from gauger import GremlinClient
4
+
5
+ async with GremlinClient() as client:
6
+ await client.login("user", "pass") # or client.use_token(...)
7
+ report = await client.get_tank_status() # customer + tanks + levels
8
+ for tank in report.tanks:
9
+ print(tank.display_name, tank.percent, tank.volume_gallons)
10
+
11
+ Every method maps 1:1 onto an endpoint documented in GREMLIN_API.md.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ import logging
18
+ from contextvars import ContextVar
19
+ from typing import Any, Optional, Tuple
20
+
21
+ from ..auth import GremlinAuth, TokenStore
22
+ from ..config import DEFAULT_TIMEOUT, Hosts
23
+ from ..models import SignInResponse, TmsConfigResponse
24
+ from ..transport import api_json, build_clients
25
+ from .account import AccountAPI
26
+ from .catalogs import CatalogAPI
27
+ from .device import DeviceAPI
28
+ from .provisioning import ProvisioningAPI
29
+ from .tanks import TankAPI
30
+
31
+ __all__ = ["GremlinClient"]
32
+
33
+ # Task-local guard: an inner sign-in request must not recursively re-login.
34
+ _RELOGIN_ACTIVE: ContextVar[bool] = ContextVar("gauger_relogin_active", default=False)
35
+
36
+
37
+ class GremlinClient(AccountAPI, TankAPI, ProvisioningAPI, CatalogAPI, DeviceAPI):
38
+ def __init__(
39
+ self,
40
+ hosts: Optional[Hosts] = None,
41
+ timeout: float = DEFAULT_TIMEOUT,
42
+ verify: bool = True,
43
+ use_keyring: bool = True,
44
+ log: Optional[logging.Logger] = None,
45
+ ):
46
+ self.hosts = hosts or Hosts.current()
47
+ self.token_store = TokenStore(use_keyring=use_keyring)
48
+ self._relogin_lock = asyncio.Lock()
49
+ self._session_version = 0
50
+ self._auth = GremlinAuth(
51
+ self.token_store,
52
+ relogin=self._relogin,
53
+ can_relogin=lambda: (
54
+ self._credentials is not None and not _RELOGIN_ACTIVE.get()
55
+ ),
56
+ session_version=lambda: self._session_version,
57
+ )
58
+ self._consumer, self._catalogs = build_clients(
59
+ self.hosts, auth=self._auth, timeout=timeout, verify=verify
60
+ )
61
+ # Session state (mirrors the app's Config.token — module 1118)
62
+ self.username: Optional[str] = None
63
+ self.subscriber_id: Optional[object] = None
64
+ self.dealer_id: Optional[object] = None
65
+ self.tms_config: Optional[TmsConfigResponse] = None
66
+ self._credentials: Optional[Tuple[str, str]] = None # in-memory; enables 401 re-login
67
+
68
+ async def close(self) -> None:
69
+ """Close both HTTP clients, attempting the second even if the first fails."""
70
+ first_error: Optional[Exception] = None
71
+ try:
72
+ await self._consumer.aclose()
73
+ except Exception as exc: # pragma: no cover - transport-specific cleanup failure
74
+ first_error = exc
75
+ try:
76
+ await self._catalogs.aclose()
77
+ except Exception as exc: # pragma: no cover - transport-specific cleanup failure
78
+ if first_error is None:
79
+ first_error = exc
80
+ if first_error is not None:
81
+ raise first_error
82
+
83
+ async def __aenter__(self) -> "GremlinClient":
84
+ return self
85
+
86
+ async def __aexit__(self, *exc: object) -> None:
87
+ await self.close()
88
+
89
+ # -- plumbing shared by the endpoint mixins --------------------------------
90
+
91
+ async def _consumer_json(
92
+ self,
93
+ method: str,
94
+ path: str,
95
+ *,
96
+ json_body: Optional[object] = None,
97
+ params: Optional[dict] = None,
98
+ timeout: Optional[float] = None,
99
+ ) -> Any:
100
+ response = await self._consumer.request(
101
+ method, path, json=json_body, params=params, timeout=timeout
102
+ )
103
+ return api_json(response)
104
+
105
+ async def _catalogs_json(
106
+ self, method: str, path: str, *, timeout: Optional[float] = None
107
+ ) -> Any:
108
+ response = await self._catalogs.request(method, path, timeout=timeout)
109
+ return api_json(response)
110
+
111
+ # -- session management ------------------------------------------------------
112
+
113
+ async def _apply_session(self, resp: SignInResponse, username: str) -> None:
114
+ self.username = resp.user.username or username
115
+ self.subscriber_id = resp.user.subscriber_id
116
+ self.dealer_id = resp.user.dealer_id
117
+ self._session_version += 1
118
+ await self.token_store.aset(resp.token, username=self.username)
119
+
120
+ async def _relogin(
121
+ self, rejected_token: Optional[str], request_version: int
122
+ ) -> Optional[str]:
123
+ """Single-flight re-login on 401, called from the auth flow.
124
+
125
+ After taking the lock, reuse the session another task already
126
+ refreshed; otherwise sign in once. A task-local guard prevents the
127
+ nested sign-in request from attempting a second re-login.
128
+ """
129
+ async with self._relogin_lock:
130
+ current = await self.token_store.aget()
131
+ if self._session_version != request_version and current:
132
+ return current
133
+ if current and current != rejected_token:
134
+ return current
135
+
136
+ creds = self._credentials
137
+ if not creds:
138
+ return None
139
+
140
+ marker = _RELOGIN_ACTIVE.set(True)
141
+ try:
142
+ username, password = creds
143
+ resp = await self._sign_in_raw(username, password)
144
+ await self._apply_session(resp, username)
145
+ return resp.token
146
+ finally:
147
+ _RELOGIN_ACTIVE.reset(marker)
gauger/api/account.py ADDED
@@ -0,0 +1,164 @@
1
+ """Account endpoints: signIn, register, recovery, password, deletion, codes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+ from typing import Optional
7
+
8
+ import httpx
9
+ from tenacity import (
10
+ AsyncRetrying,
11
+ retry_if_exception_type,
12
+ stop_after_attempt,
13
+ wait_exponential,
14
+ )
15
+
16
+ from ..config import TENANT_CODE
17
+ from ..models import (
18
+ ChangePasswordResult,
19
+ DeleteResult,
20
+ RecoverUsernameResult,
21
+ RegisterResult,
22
+ SignInResponse,
23
+ UsernameAvailableResult,
24
+ )
25
+
26
+
27
+ def _created_on() -> str:
28
+ """The app sends a locale timestamp; ISO-8601 serves the same purpose."""
29
+ return datetime.now().isoformat(timespec="seconds")
30
+
31
+
32
+ class AccountAPI:
33
+ """Endpoints on the consumer host (see GREMLIN_API.md §5)."""
34
+
35
+ async def _sign_in_raw(self, username: str, password: str) -> SignInResponse:
36
+ data = await self._consumer_json(
37
+ "POST", "/consumer/signIn", json_body={"username": username, "password": password}
38
+ )
39
+ return SignInResponse.model_validate(data)
40
+
41
+ async def sign_in(self, username: str, password: str) -> SignInResponse:
42
+ """POST /consumer/signIn → token + user; stores the token for reuse."""
43
+ resp = await self._sign_in_raw(username, password)
44
+ await self._apply_session(resp, username)
45
+ self._credentials = (username, password) # in-memory only; enables 401 re-login
46
+ return resp
47
+
48
+ async def login(self, username: str, password: str, max_attempts: int = 5) -> SignInResponse:
49
+ """App-style login: sign-in + /tms/config, retrying transport errors.
50
+
51
+ Mirrors the app's ×5 retry (module 1510). Authentication failures are
52
+ never retried, and the backoff sleeps asynchronously.
53
+ """
54
+ async for attempt in AsyncRetrying(
55
+ stop=stop_after_attempt(max_attempts),
56
+ wait=wait_exponential(multiplier=0.5, max=8),
57
+ retry=retry_if_exception_type(httpx.TransportError),
58
+ reraise=True,
59
+ ):
60
+ async with attempt:
61
+ resp = await self.sign_in(username, password)
62
+ await self.get_tms_config()
63
+ return resp
64
+ raise AssertionError("unreachable") # pragma: no cover
65
+
66
+ def use_token(
67
+ self,
68
+ token: str,
69
+ subscriber_id: Optional[object] = None,
70
+ dealer_id: Optional[object] = None,
71
+ username: Optional[str] = None,
72
+ ) -> None:
73
+ """Skip sign-in and use a token captured earlier (transient, not persisted)."""
74
+ self.token_store.set(token, username=username, persist=False)
75
+ self.username = username
76
+ self.subscriber_id = subscriber_id
77
+ self.dealer_id = dealer_id
78
+
79
+ async def get_username_available(self, username: str) -> bool:
80
+ data = await self._consumer_json("GET", f"/consumer/usernameAvailable/{username}")
81
+ return UsernameAvailableResult.model_validate(data).is_available
82
+
83
+ async def register(
84
+ self,
85
+ *,
86
+ username: str,
87
+ email: str,
88
+ password: str,
89
+ confirm_password: str,
90
+ account_number: str,
91
+ phone_number: str,
92
+ serial_number: str,
93
+ ) -> RegisterResult:
94
+ body = {
95
+ "username": username,
96
+ "email": email,
97
+ "password": password,
98
+ "confirmPassword": confirm_password,
99
+ "accountNumber": account_number,
100
+ "phoneNumber": phone_number,
101
+ "serialNumber": serial_number,
102
+ }
103
+ return RegisterResult.model_validate(
104
+ await self._consumer_json("POST", "/consumer/register", json_body=body)
105
+ )
106
+
107
+ async def recover_username(self, email: str, serial_number: str) -> RecoverUsernameResult:
108
+ body = {"email": email, "serialNumber": serial_number}
109
+ return RecoverUsernameResult.model_validate(
110
+ await self._consumer_json("POST", "/consumer/recoverUsername", json_body=body)
111
+ )
112
+
113
+ async def change_password(
114
+ self, username: str, new_password: str, confirm_new_password: str
115
+ ) -> ChangePasswordResult:
116
+ """POST /consumer/changePassword — no token needed; carries the app's tenant code."""
117
+ body = {
118
+ "username": username,
119
+ "newPassword": new_password,
120
+ "confirmNewPassword": confirm_new_password,
121
+ "code": TENANT_CODE,
122
+ }
123
+ return ChangePasswordResult.model_validate(
124
+ await self._consumer_json("POST", "/consumer/changePassword", json_body=body)
125
+ )
126
+
127
+ async def change_password_consumer(
128
+ self, old_password: str, new_password: str, reenter_password: str
129
+ ) -> ChangePasswordResult:
130
+ """POST /consumer/changePasswordConsumer — authenticated variant (app module 1507)."""
131
+ body = {
132
+ "oldPassword": old_password,
133
+ "newPassword": new_password,
134
+ "reenterPassword": reenter_password,
135
+ "code": TENANT_CODE,
136
+ }
137
+ return ChangePasswordResult.model_validate(
138
+ await self._consumer_json("POST", "/consumer/changePasswordConsumer", json_body=body)
139
+ )
140
+
141
+ async def delete_account(self, username: str) -> DeleteResult:
142
+ return DeleteResult.model_validate(
143
+ await self._consumer_json(
144
+ "POST", "/consumer/delete", json_body={"username": username}
145
+ )
146
+ )
147
+
148
+ # -- v5.9.5 replacements for the retired alert service (GREMLIN_API.md §8.3) --
149
+
150
+ async def send_verification_code(self, username: str) -> object:
151
+ """POST /consumer/recoverUsername/sendcode {username, createdOn}."""
152
+ return await self._consumer_json(
153
+ "POST",
154
+ "/consumer/recoverUsername/sendcode",
155
+ json_body={"username": username, "createdOn": _created_on()},
156
+ )
157
+
158
+ async def check_verification_code(self, email: str, code: str) -> object:
159
+ """POST /consumer/recoverUsername/checkcode {email, code, createdOn}."""
160
+ return await self._consumer_json(
161
+ "POST",
162
+ "/consumer/recoverUsername/checkcode",
163
+ json_body={"email": email, "code": code, "createdOn": _created_on()},
164
+ )
gauger/api/catalogs.py ADDED
@@ -0,0 +1,39 @@
1
+ """Constants catalogs on the tank-monitor host (v5.9.5; verified live)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import List
6
+
7
+ from ..models import (
8
+ ConstantsResponse,
9
+ ContainerGeometry,
10
+ MonitorType,
11
+ MultiplierEntry,
12
+ MultipliersResponse,
13
+ )
14
+
15
+
16
+ class CatalogAPI:
17
+ """Public endpoints on the catalogs host — no auth required."""
18
+
19
+ async def get_constants(self) -> ConstantsResponse:
20
+ """GET constants/ams → monitor types + container geometry presets.
21
+
22
+ The v5.9.5 app joins the *relative* path 'constants/ams' onto the
23
+ trailing-slash base https://tank-monitor.brite2.com/ — preserved here.
24
+ Both response columns are JSON-encoded strings (see models.ConstantsRow).
25
+ """
26
+ return ConstantsResponse.model_validate(
27
+ await self._catalogs_json("GET", "constants/ams")
28
+ )
29
+
30
+ async def get_monitor_types(self) -> List[MonitorType]:
31
+ return (await self.get_constants()).monitor_types
32
+
33
+ async def get_container_geometries(self) -> List[ContainerGeometry]:
34
+ return (await self.get_constants()).container_geometries
35
+
36
+ async def get_multipliers(self) -> List[MultiplierEntry]:
37
+ """GET constant/multipliers — geometry dimensions keyed by multiplier."""
38
+ data = await self._catalogs_json("GET", "constant/multipliers")
39
+ return MultipliersResponse.model_validate(data).multipliers
gauger/api/device.py ADDED
@@ -0,0 +1,76 @@
1
+ """Local device provisioning over the monitor's WiFi AP (http://192.168.4.1).
2
+
3
+ The GREMLIN monitor in setup mode hosts an AP with a small config server.
4
+ Timeouts mirror the app (module 1190): GET 30 s, POST 5 s.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import List, Optional
11
+
12
+ import httpx
13
+
14
+ from ..config import DEVICE_AP, USER_AGENT
15
+ from ..models import DeviceInfo
16
+ from ..transport import api_text
17
+
18
+ _SERIAL_RE = re.compile(r'<td class="style23" align="left">\s*(\d+)\s*</td>')
19
+ _SSID_RE = re.compile(r'<option value="(.*?)">')
20
+ _SSID_EXCLUDE = ("choose_from_list", "manually_entered")
21
+
22
+
23
+ class DeviceAPI:
24
+ """The only place in the client that scrapes HTML (two fixed patterns)."""
25
+
26
+ async def device_get_info(
27
+ self, base: str = DEVICE_AP, timeout: float = 30.0
28
+ ) -> DeviceInfo:
29
+ """GET the setup page → {monitor_serial, ssids} (app module 1190)."""
30
+ async with httpx.AsyncClient(
31
+ base_url=base, timeout=timeout, headers={"User-Agent": USER_AGENT}
32
+ ) as client:
33
+ response = await client.get("")
34
+ html = api_text(response)
35
+ serial_match = _SERIAL_RE.search(html)
36
+ serial = serial_match.group(1).lstrip("0") if serial_match else ""
37
+ ssids: List[str] = [s for s in _SSID_RE.findall(html) if s not in _SSID_EXCLUDE]
38
+ return DeviceInfo(monitor_serial=serial, ssids=ssids)
39
+
40
+ async def device_set_upload_endpoint(
41
+ self,
42
+ url: Optional[str] = None,
43
+ port: Optional[int] = None,
44
+ base: str = DEVICE_AP,
45
+ timeout: float = 5.0,
46
+ ) -> None:
47
+ """POST /data?command=send — TEKSettings={'SURL':…,'SPORT':…}.
48
+
49
+ Defaults come from /tms/config; the v5.9.5 fallback is
50
+ http://monitors.angusenergy.net : 344 (v5.1.5 used monitors.paygo.net).
51
+ The body is a plain string, not JSON — exactly like the app.
52
+ """
53
+ endpoint = self.tms_config.monitor_api if self.tms_config else None
54
+ surl = url or (endpoint.url if endpoint and endpoint.url else self.hosts.fallback_ingest_url)
55
+ sport = (
56
+ port
57
+ if port is not None
58
+ else (endpoint.port if endpoint and endpoint.port is not None
59
+ else self.hosts.fallback_ingest_port)
60
+ )
61
+ body = "TEKSettings={'SURL':'%s','SPORT':'%s'}" % (surl, sport)
62
+ async with httpx.AsyncClient(
63
+ base_url=base, timeout=timeout, headers={"User-Agent": USER_AGENT}
64
+ ) as client:
65
+ await client.post(
66
+ "data?command=send", content=body, headers={"Content-Type": "text/plain"}
67
+ )
68
+
69
+ async def device_set_wifi(
70
+ self, ssid: str, password: str, base: str = DEVICE_AP, timeout: float = 5.0
71
+ ) -> None:
72
+ """POST /config?command=wifi — {ssid, password} (app modules 1189/1190)."""
73
+ async with httpx.AsyncClient(
74
+ base_url=base, timeout=timeout, headers={"User-Agent": USER_AGENT}
75
+ ) as client:
76
+ await client.post("config?command=wifi", json={"ssid": ssid, "password": password})
@@ -0,0 +1,100 @@
1
+ """Monitor provisioning: serial validation and tank-geometry installation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ from typing import Optional, Union
8
+
9
+ from ..config import MONITOR_TYPE_TMS
10
+ from ..models import ValidateResult
11
+
12
+ LOG = logging.getLogger("gauger.provisioning")
13
+
14
+
15
+ class ProvisioningAPI:
16
+ """Endpoints on the consumer host (GREMLIN_API.md §6)."""
17
+
18
+ async def validate_monitor(self, serial: str, monitor_type: int) -> ValidateResult:
19
+ """POST /tms/validate {serial, monitorType} — app uses a 4.5 s timeout."""
20
+ data = await self._consumer_json(
21
+ "POST",
22
+ "/tms/validate",
23
+ json_body={"serial": serial, "monitorType": monitor_type},
24
+ timeout=4.5,
25
+ )
26
+ return ValidateResult.model_validate(data)
27
+
28
+ async def wait_for_monitor(
29
+ self,
30
+ serial: str,
31
+ monitor_type: int,
32
+ attempts: int = 10,
33
+ delay: float = 5.0,
34
+ ) -> ValidateResult:
35
+ """Server-driven poll for /tms/validate (app: 5 s × ~10).
36
+
37
+ This is *semantic* polling, distinct from transport retries: the
38
+ server itself reports ``canRetry``/``canContinue`` (verified live), so
39
+ a plain loop driven by the response model is the honest encoding.
40
+ The delay is asynchronous and therefore cancellable.
41
+ """
42
+ result = await self.validate_monitor(serial, monitor_type)
43
+ for _ in range(attempts - 1):
44
+ if result.can_continue or not result.can_retry:
45
+ return result
46
+ LOG.debug("validate: %s — retrying in %.0fs",
47
+ result.retry_message or "not ready", delay)
48
+ await asyncio.sleep(delay)
49
+ result = await self.validate_monitor(serial, monitor_type)
50
+ return result
51
+
52
+ async def map_monitor_to_tank(
53
+ self, tank_key: Union[str, int], serial_number: str, monitor_type: str = MONITOR_TYPE_TMS
54
+ ) -> dict:
55
+ """POST /api/subscribers/{sub}/containers/{tankKey}/monitors {serialNumber, type}."""
56
+ path = f"/api/subscribers/{self.subscriber_id}/containers/{tank_key}/monitors"
57
+ return await self._consumer_json(
58
+ "POST", path, json_body={"serialNumber": serial_number, "type": monitor_type}
59
+ )
60
+
61
+ async def install_geometry(
62
+ self,
63
+ tank_key: Union[str, int],
64
+ *,
65
+ shape_id: int,
66
+ height: float,
67
+ width: float,
68
+ length: float,
69
+ sensor_offset: float,
70
+ outlet_height: float,
71
+ safe_capacity: float,
72
+ monitor_type: int,
73
+ multiplier: float,
74
+ container_geometry_key: int,
75
+ location_id: int = 1,
76
+ antenna_type_id: int = 1,
77
+ ) -> dict:
78
+ """PUT /api/subscribers/{sub}/containers/{tankKey}/monitors — geometry install.
79
+
80
+ App rule (module 1183): for monitorType not in {1, 6}, locationId and
81
+ monitorAntennaTypeId are forced to 2.
82
+ """
83
+ if monitor_type not in (1, 6):
84
+ location_id, antenna_type_id = 2, 2
85
+ body = {
86
+ "locationId": location_id,
87
+ "monitorAntennaTypeId": antenna_type_id,
88
+ "shapeId": shape_id,
89
+ "height": height,
90
+ "width": width,
91
+ "length": length,
92
+ "sensorOffset": sensor_offset,
93
+ "outletHeight": outlet_height,
94
+ "safeCapacity": safe_capacity,
95
+ "type": monitor_type,
96
+ "multiplier": multiplier,
97
+ "containerGeometryKey": int(container_geometry_key),
98
+ }
99
+ path = f"/api/subscribers/{self.subscriber_id}/containers/{tank_key}/monitors"
100
+ return await self._consumer_json("PUT", path, json_body=body)
gauger/api/tanks.py ADDED
@@ -0,0 +1,104 @@
1
+ """Tank status endpoints (GREMLIN_API.md §4) — the core of the API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import date, timedelta
6
+ from typing import Any, List, Optional, Union
7
+
8
+ from ..models import ConsumerData, Level, TankStatus, TankStatusReport, TmsConfigResponse
9
+ from ..transport import api_json, api_text
10
+
11
+
12
+ class TankAPI:
13
+ """Endpoints on the consumer host; authenticated via x-access-token."""
14
+
15
+ async def get_tms_config(self) -> TmsConfigResponse:
16
+ """GET /tms/config → monitor ingest endpoint (SURL/SPORT for devices)."""
17
+ self.tms_config = TmsConfigResponse.model_validate(
18
+ await self._consumer_json("GET", "/tms/config")
19
+ )
20
+ return self.tms_config
21
+
22
+ async def get_consumer_data(self) -> ConsumerData:
23
+ """GET /consumer/api — customer record + tank list."""
24
+ return ConsumerData.model_validate(await self._consumer_json("GET", "/consumer/api"))
25
+
26
+ async def get_tank_levels(
27
+ self, tank_key: Union[str, int], start_date: Optional[Union[date, str]] = None
28
+ ) -> List[Level]:
29
+ """GET /consumer/api/tanks/{key}/levels — reading history.
30
+
31
+ ``start_date`` mirrors the v5.9.5 app's ``?startDate=YYYY-MM-DD``
32
+ window; omit it for the v5.1.5-style unbounded history. Levels are
33
+ sorted newest-first and capped at 30 entries (app module 1488).
34
+ """
35
+ params = None
36
+ if start_date is not None:
37
+ sd = start_date.isoformat() if isinstance(start_date, date) else str(start_date)
38
+ params = {"startDate": sd}
39
+ data = await self._consumer_json(
40
+ "GET", f"/consumer/api/tanks/{tank_key}/levels", params=params
41
+ )
42
+ levels = [Level.model_validate(x) for x in ((data or {}).get("levels") or [])]
43
+ levels.sort(key=lambda lv: lv.reading_date, reverse=True)
44
+ return levels[:30]
45
+
46
+ async def get_tank_status(self, days: Optional[int] = None) -> TankStatusReport:
47
+ """High-level query: customer + every tank with current status and history.
48
+
49
+ Reproduces the dashboard's request sequence (one /consumer/api, then
50
+ sequential /levels calls per tank) and its post-processing:
51
+ percent = floor(clamp(0,100)), ``"Tank #N"`` name fallback, top-30
52
+ newest-first history. ``days`` bounds each levels query to
53
+ ``startDate = today - N`` (app style).
54
+ """
55
+ data = await self.get_consumer_data()
56
+ start: Optional[date] = None
57
+ if days is not None:
58
+ start = date.today() - timedelta(days=days)
59
+
60
+ tanks: List[TankStatus] = []
61
+ for tank in data.tanks:
62
+ levels = (
63
+ await self.get_tank_levels(tank.key, start_date=start) if tank.key else []
64
+ )
65
+ latest = levels[0] if levels else None
66
+ percent: Optional[int] = None
67
+ if latest is not None and latest.percent is not None:
68
+ percent = int(max(min(float(latest.percent), 100.0), 0.0))
69
+ tanks.append(
70
+ TankStatus(
71
+ key=tank.key,
72
+ name=tank.name,
73
+ percent=percent,
74
+ latest=latest,
75
+ levels=levels,
76
+ last_delivery=tank.last_delivery,
77
+ next_delivery=tank.next_delivery,
78
+ )
79
+ )
80
+ return TankStatusReport(customer=data, tanks=tanks)
81
+
82
+ async def get_logo(self) -> str:
83
+ """GET /consumer/api/subscribers/{id}/logo → dealer logo URL string."""
84
+ response = await self._consumer.get(
85
+ f"/consumer/api/subscribers/{self.subscriber_id}/logo"
86
+ )
87
+ return api_text(response)
88
+
89
+ async def get_dealer_contacts(self) -> Any:
90
+ """GET /consumer/api/subscribers/{id}/tmsContacts?dealerId={id}."""
91
+ params = {"dealerId": self.dealer_id} if self.dealer_id else None
92
+ response = await self._consumer.get(
93
+ f"/consumer/api/subscribers/{self.subscriber_id}/tmsContacts", params=params
94
+ )
95
+ return api_json(response)
96
+
97
+ async def set_notification_pref(
98
+ self, expo_token: str, notify: bool, username: Optional[str] = None
99
+ ) -> Any:
100
+ """POST /consumer/api/notification/notify — push prefs (v5.9.5)."""
101
+ body = {"username": username or self.username, "tokens": expo_token, "notify": notify}
102
+ return await self._consumer_json(
103
+ "POST", "/consumer/api/notification/notify", json_body=body
104
+ )