python-airselangor 0.1.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.
@@ -0,0 +1,29 @@
1
+ """Python client for Air Selangor customer portal API."""
2
+
3
+ from .client import AirSelangorClient
4
+ from .exceptions import (
5
+ AirSelangorApiError,
6
+ AirSelangorAuthError,
7
+ AirSelangorConnectionError,
8
+ AirSelangorError,
9
+ AirSelangorRateLimitError,
10
+ GeoBlockedError,
11
+ )
12
+ from .models import AccountData, Bill, Payment, WaterAccount
13
+
14
+ __version__ = "0.1.0"
15
+
16
+ __all__ = [
17
+ "AccountData",
18
+ "AirSelangorApiError",
19
+ "AirSelangorAuthError",
20
+ "AirSelangorClient",
21
+ "AirSelangorConnectionError",
22
+ "AirSelangorError",
23
+ "AirSelangorRateLimitError",
24
+ "Bill",
25
+ "GeoBlockedError",
26
+ "Payment",
27
+ "WaterAccount",
28
+ "__version__",
29
+ ]
@@ -0,0 +1,4 @@
1
+ from airselangor.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
airselangor/cli.py ADDED
@@ -0,0 +1,74 @@
1
+ """CLI tool for testing Air Selangor credentials and inspecting accounts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import sys
8
+
9
+ from .client import AirSelangorClient
10
+ from .exceptions import AirSelangorError, GeoBlockedError
11
+
12
+
13
+ async def _run_cli(args: argparse.Namespace) -> int:
14
+ print(f"Connecting to Air Selangor as {args.login_id}...")
15
+
16
+ async with AirSelangorClient(args.login_id, args.password) as client:
17
+ try:
18
+ await client.login()
19
+ print("Authentication successful!")
20
+
21
+ profile = await client.get_profile()
22
+ name = profile.get("fullname") or profile.get("username") or args.login_id
23
+ print(f"User: {name}")
24
+
25
+ accounts = await client.get_accounts()
26
+ print(f"\nDiscovered {len(accounts)} water account(s):")
27
+
28
+ for idx, acc in enumerate(accounts, start=1):
29
+ print(f"\n--- [{idx}] Account: {acc.account_number} ({acc.display_name}) ---")
30
+ print(f"Status: {acc.status} | Smart Meter: {acc.is_smart_meter}")
31
+ if acc.address:
32
+ print(f"Address: {acc.address}")
33
+
34
+ data = await client.get_account_data(acc)
35
+ print(f"Current Balance : RM {data.current_balance_rm or 0.0:.2f}")
36
+ print(f"Outstanding : RM {data.outstanding_rm or 0.0:.2f}")
37
+
38
+ if data.latest_bill:
39
+ print(
40
+ f"Latest Bill : {data.latest_bill.bill_date} -> "
41
+ f"{data.latest_bill.usage_m3} m³ (RM {data.latest_bill.amount_rm:.2f})"
42
+ )
43
+
44
+ if data.last_payment:
45
+ print(
46
+ f"Last Payment : RM {data.last_payment.amount_rm or 0.0:.2f} "
47
+ f"on {data.last_payment.paid_at} ({data.last_payment.reference})"
48
+ )
49
+
50
+ return 0
51
+
52
+ except GeoBlockedError as err:
53
+ print(f"\n[GEO-BLOCKED ERROR] {err}", file=sys.stderr)
54
+ return 2
55
+ except AirSelangorError as err:
56
+ print(f"\n[ERROR] {err}", file=sys.stderr)
57
+ return 1
58
+
59
+
60
+ def main() -> None:
61
+ parser = argparse.ArgumentParser(
62
+ prog="python -m airselangor",
63
+ description="Air Selangor CLI test utility",
64
+ )
65
+ parser.add_argument("login_id", help="IC Number, Passport, or Email")
66
+ parser.add_argument("password", help="Account Password")
67
+
68
+ args = parser.parse_args()
69
+ code = asyncio.run(_run_cli(args))
70
+ sys.exit(code)
71
+
72
+
73
+ if __name__ == "__main__":
74
+ main()
airselangor/client.py ADDED
@@ -0,0 +1,415 @@
1
+ """Async client for the Air Selangor customer API (api3.airselangor.com).
2
+
3
+ Reverse-engineered from the www.airselangor.com Next.js portal:
4
+ * Every request is a JSON POST to ``https://api3.airselangor.com/<path>``.
5
+ * Unauthenticated calls carry a "public token":
6
+ ``Authorization: Bearer sha256("airselangorsecretkey" + Timestamp)``.
7
+ * Authenticated calls carry ``Authorization: Bearer <accesstoken>``.
8
+ * Responses are wrapped: ``{"status": bool, "message": str, "error": {...}, "data": {...}}``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import hashlib
15
+ import logging
16
+ import uuid
17
+ from datetime import UTC, date, datetime
18
+ from typing import Any
19
+
20
+ import aiohttp
21
+
22
+ from .exceptions import (
23
+ AirSelangorApiError,
24
+ AirSelangorAuthError,
25
+ AirSelangorConnectionError,
26
+ AirSelangorError,
27
+ AirSelangorRateLimitError,
28
+ GeoBlockedError,
29
+ )
30
+ from .models import AccountData, Bill, Payment, WaterAccount, _to_date, _to_float
31
+ from .retry import RETRYABLE_STATUS_CODES, with_retry
32
+
33
+ _LOGGER = logging.getLogger(__name__)
34
+
35
+ BASE_URL = "https://api3.airselangor.com/"
36
+ PUBLIC_SECRET = "airselangorsecretkey"
37
+ USER_AGENT = (
38
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
39
+ "(KHTML, like Gecko) Chrome/126.0 Safari/537.36 Python-AirSelangor"
40
+ )
41
+ DEFAULT_TIMEOUT = aiohttp.ClientTimeout(total=30)
42
+
43
+ INVALID_TOKEN_CODES = {"999"}
44
+ INVALID_CREDENTIALS_CODES = {"129"}
45
+ LOCKED_OUT_CODES = {"111", "112"}
46
+
47
+ TREND_RECENT = 1
48
+ TREND_PREVIOUS = 2
49
+
50
+
51
+ class AirSelangorClient:
52
+ """Async API client for Air Selangor with automatic token refresh and backoff retry."""
53
+
54
+ def __init__(
55
+ self,
56
+ login_id: str,
57
+ password: str,
58
+ session: aiohttp.ClientSession | None = None,
59
+ *,
60
+ retry_attempts: int = 3,
61
+ retry_base_delay: float = 0.5,
62
+ ) -> None:
63
+ """Initialize the client.
64
+
65
+ Args:
66
+ login_id: Portal login ID (IC number, passport, or registered email).
67
+ password: Portal account password.
68
+ session: Optional shared aiohttp ClientSession (e.g. from Home Assistant).
69
+ If not provided, a dedicated session is created internally.
70
+ retry_attempts: Maximum retry attempts for transient network/5xx failures.
71
+ retry_base_delay: Base delay for exponential backoff with jitter.
72
+ """
73
+ self._login_id = login_id
74
+ self._password = password
75
+ self._external_session = session is not None
76
+ self._session = session
77
+ self._retry_attempts = retry_attempts
78
+ self._retry_base_delay = retry_base_delay
79
+
80
+ self._device_uid = str(uuid.uuid4())
81
+ self._access_token: str | None = None
82
+ self._refresh_token: str | None = None
83
+ self._csrf_token: str | None = None
84
+ self._lock = asyncio.Lock()
85
+
86
+ async def __aenter__(self) -> AirSelangorClient:
87
+ return self
88
+
89
+ async def __aexit__(
90
+ self,
91
+ exc_type: type[BaseException] | None,
92
+ exc_val: BaseException | None,
93
+ exc_tb: Any,
94
+ ) -> None:
95
+ await self.close()
96
+
97
+ async def _get_session(self) -> aiohttp.ClientSession:
98
+ if self._session is None or self._session.closed:
99
+ self._session = aiohttp.ClientSession()
100
+ self._external_session = False
101
+ return self._session
102
+
103
+ async def close(self) -> None:
104
+ """Close internal session if created by this client."""
105
+ if not self._external_session and self._session and not self._session.closed:
106
+ await self._session.close()
107
+
108
+ @staticmethod
109
+ def _timestamp() -> str:
110
+ return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
111
+
112
+ def _headers(self, authenticated: bool) -> dict[str, str]:
113
+ ts = self._timestamp()
114
+ headers = {
115
+ "Timestamp": ts,
116
+ "Language": "en",
117
+ "Transactionid": str(uuid.uuid4()),
118
+ "device-name": "browser",
119
+ "os-type": "web",
120
+ "os-version": "python-airselangor",
121
+ "Content-Type": "application/json",
122
+ "Accept": "application/json",
123
+ "Origin": "https://www.airselangor.com",
124
+ "Referer": "https://www.airselangor.com/",
125
+ "User-Agent": USER_AGENT,
126
+ }
127
+ if authenticated and self._access_token:
128
+ headers["Authorization"] = f"Bearer {self._access_token}"
129
+ if self._csrf_token:
130
+ headers["X-Csrf-Token"] = self._csrf_token
131
+ else:
132
+ public = hashlib.sha256(f"{PUBLIC_SECRET}{ts}".encode()).hexdigest()
133
+ headers["Authorization"] = f"Bearer {public}"
134
+ return headers
135
+
136
+ async def _raw_post_single(
137
+ self, path: str, body: dict[str, Any], authenticated: bool
138
+ ) -> tuple[int, Any]:
139
+ session = await self._get_session()
140
+ url = BASE_URL + path.lstrip("/")
141
+ headers = self._headers(authenticated)
142
+
143
+ try:
144
+ async with session.post(
145
+ url,
146
+ json=body,
147
+ headers=headers,
148
+ timeout=DEFAULT_TIMEOUT,
149
+ ) as resp:
150
+ status = resp.status
151
+
152
+ if status == 403:
153
+ # Check for Cloudflare / WAF Geo-Block
154
+ raw_text = await resp.text()
155
+ if "Access denied" in raw_text or "Cloudflare" in raw_text or "WAF" in raw_text:
156
+ raise GeoBlockedError()
157
+ raise AirSelangorAuthError(f"{path}: HTTP 403 Forbidden")
158
+
159
+ if status == 429:
160
+ raise AirSelangorRateLimitError(f"{path}: HTTP 429 Too Many Requests")
161
+
162
+ if status in RETRYABLE_STATUS_CODES:
163
+ raise AirSelangorConnectionError(f"{path}: HTTP {status} transient error")
164
+
165
+ try:
166
+ payload = await resp.json(content_type=None)
167
+ except (aiohttp.ContentTypeError, ValueError):
168
+ payload = None
169
+ return status, payload
170
+
171
+ except (TimeoutError, aiohttp.ClientError) as err:
172
+ raise AirSelangorConnectionError(f"{path}: {err}") from err
173
+
174
+ async def _raw_post(
175
+ self, path: str, body: dict[str, Any], authenticated: bool
176
+ ) -> tuple[int, Any]:
177
+ """Execute request wrapped with bounded retry and exponential backoff."""
178
+ return await with_retry(
179
+ lambda: self._raw_post_single(path, body, authenticated),
180
+ attempts=self._retry_attempts,
181
+ base_delay=self._retry_base_delay,
182
+ logger=_LOGGER,
183
+ )
184
+
185
+ @staticmethod
186
+ def _unwrap(path: str, status: int, payload: Any) -> dict[str, Any]:
187
+ if not isinstance(payload, dict):
188
+ raise AirSelangorApiError(f"{path}: HTTP {status}, non-JSON response")
189
+ if not payload.get("status"):
190
+ err = payload.get("error") or {}
191
+ raise AirSelangorApiError(
192
+ f"{path}: {err.get('message') or payload.get('message')}",
193
+ code=str(err.get("code")) if err.get("code") is not None else None,
194
+ )
195
+ return payload.get("data") or {}
196
+
197
+ async def _post(
198
+ self, path: str, body: dict[str, Any] | None = None
199
+ ) -> dict[str, Any]:
200
+ body = body or {}
201
+ if self._access_token is None:
202
+ async with self._lock:
203
+ if self._access_token is None:
204
+ await self._login_unlocked()
205
+ used_token = self._access_token
206
+ status, payload = await self._raw_post(path, body, True)
207
+ if self._token_rejected(status, payload):
208
+ _LOGGER.debug("Access token rejected on %s, re-authenticating", path)
209
+ await self._reauthenticate(used_token)
210
+ status, payload = await self._raw_post(path, body, True)
211
+ if self._token_rejected(status, payload):
212
+ raise AirSelangorAuthError("Session rejected after re-login")
213
+ return self._unwrap(path, status, payload)
214
+
215
+ @staticmethod
216
+ def _token_rejected(status: int, payload: Any) -> bool:
217
+ if status == 401:
218
+ return True
219
+ if isinstance(payload, dict) and not payload.get("status"):
220
+ code = (payload.get("error") or {}).get("code")
221
+ return str(code) in INVALID_TOKEN_CODES
222
+ return False
223
+
224
+ async def login(self) -> None:
225
+ """Log in with portal credentials."""
226
+ async with self._lock:
227
+ await self._login_unlocked()
228
+
229
+ async def _login_unlocked(self) -> None:
230
+ """Perform login assuming ``self._lock`` is already held."""
231
+ status, payload = await self._raw_post(
232
+ "/authentication/v1/login",
233
+ {
234
+ "loginid": self._login_id,
235
+ "password": self._password,
236
+ "deviceuid": self._device_uid,
237
+ "apptype": "1",
238
+ "loginType": "1",
239
+ "ostype": "Linux",
240
+ "osversion": "x86_64",
241
+ "devicename": "Chrome",
242
+ "app": "Chrome",
243
+ "appversion": "126",
244
+ },
245
+ False,
246
+ )
247
+ if status >= 500:
248
+ raise AirSelangorConnectionError(f"login: HTTP {status}")
249
+ try:
250
+ data = self._unwrap("login", status, payload)
251
+ except AirSelangorApiError as err:
252
+ if err.code in LOCKED_OUT_CODES:
253
+ raise AirSelangorAuthError(
254
+ "Account temporarily locked after failed logins"
255
+ ) from err
256
+ has_attempts = (
257
+ isinstance(payload, dict)
258
+ and isinstance(payload.get("data"), dict)
259
+ and "attempts" in payload["data"]
260
+ )
261
+ if err.code in INVALID_CREDENTIALS_CODES or has_attempts:
262
+ raise AirSelangorAuthError(str(err)) from err
263
+ raise
264
+
265
+ token = data.get("accesstoken")
266
+ if not token:
267
+ raise AirSelangorAuthError("Login returned no access token")
268
+ self._access_token = token
269
+ self._refresh_token = data.get("refreshtoken")
270
+ self._csrf_token = data.get("csrftoken")
271
+
272
+ async def _reauthenticate(self, rejected_token: str | None = None) -> None:
273
+ """Try refresh token first, then full login."""
274
+ async with self._lock:
275
+ if (
276
+ rejected_token is not None
277
+ and self._access_token is not None
278
+ and self._access_token != rejected_token
279
+ ):
280
+ return
281
+ if self._refresh_token:
282
+ status, payload = await self._raw_post(
283
+ "/authentication/v1/refreshtoken",
284
+ {"refreshtoken": self._refresh_token},
285
+ False,
286
+ )
287
+ if (
288
+ status == 200
289
+ and isinstance(payload, dict)
290
+ and payload.get("status")
291
+ and (payload.get("data") or {}).get("accesstoken")
292
+ ):
293
+ self._access_token = payload["data"]["accesstoken"]
294
+ return
295
+ self._access_token = None
296
+ await self._login_unlocked()
297
+
298
+ async def get_profile(self) -> dict[str, Any]:
299
+ """Fetch basic user profile information."""
300
+ return await self._post("/userprofile/v2/view/basic")
301
+
302
+ async def get_accounts(self) -> list[WaterAccount]:
303
+ """Fetch all water accounts linked to user's portal login."""
304
+ accounts: list[WaterAccount] = []
305
+ offset = 0
306
+ while True:
307
+ data = await self._post(
308
+ "/wateraccount/v1/dashboardlist",
309
+ {"offset": offset, "limit": 100, "isebiztab": False},
310
+ )
311
+ items = data.get("items") or []
312
+ accounts.extend(WaterAccount.from_api(i) for i in items)
313
+ total = int(data.get("total") or 0)
314
+ offset += 100
315
+ if not items or offset >= total:
316
+ return accounts
317
+
318
+ async def get_account_details(self, account_id: str) -> dict[str, Any]:
319
+ """Fetch billing details, balances, and status for one account."""
320
+ data = await self._post(
321
+ "/wateraccount/v1/details", {"wateraccountid": account_id}
322
+ )
323
+ return data.get("accountdetails") or {}
324
+
325
+ async def get_bills(self, account_number: str) -> list[Bill]:
326
+ """Fetch up to 12 monthly bills, oldest first."""
327
+ bills: dict[date, Bill] = {}
328
+ for trend_type in (TREND_PREVIOUS, TREND_RECENT):
329
+ data = await self._post(
330
+ "/billing/v1/watertrend",
331
+ {"accountnumber": account_number, "type": trend_type},
332
+ )
333
+ for item in data.get("items") or []:
334
+ bill = Bill.from_api(item)
335
+ if bill is not None:
336
+ bills[bill.bill_date] = bill
337
+ return [bills[d] for d in sorted(bills)]
338
+
339
+ async def get_household_usage(self, account_id: str) -> dict[str, Any]:
340
+ """Fetch household usage and LCD metrics."""
341
+ return await self._post(
342
+ "/lifestyle/v1/lcd/latestbillwaterusage",
343
+ {"wateraccountid": account_id, "channel": "web"},
344
+ )
345
+
346
+ async def get_payments(self, account_id: str) -> list[Payment]:
347
+ """Fetch recent payment history."""
348
+ data = await self._post(
349
+ "/payment/v1/history",
350
+ {
351
+ "accountid": account_id,
352
+ "wateraccountguid": account_id,
353
+ "type": 0,
354
+ "limit": 0,
355
+ },
356
+ )
357
+ return [Payment.from_api(p) for p in data.get("payment_histories") or []]
358
+
359
+ async def get_account_data(self, account: WaterAccount) -> AccountData:
360
+ """Fetch complete consolidated data bundle for one account."""
361
+ details = await self.get_account_details(account.account_id)
362
+ bills = await self.get_bills(account.account_number)
363
+
364
+ household: dict[str, Any] = {}
365
+ try:
366
+ household = await self.get_household_usage(account.account_id)
367
+ except AirSelangorApiError as err:
368
+ _LOGGER.debug("No household usage for %s: %s", account.account_number, err)
369
+
370
+ payments: list[Payment] = []
371
+ try:
372
+ payments = await self.get_payments(account.account_id)
373
+ except AirSelangorApiError as err:
374
+ _LOGGER.debug("No payment history for %s: %s", account.account_number, err)
375
+
376
+ account.display_name = details.get("displayname") or account.display_name
377
+ account.address = details.get("address") or account.address
378
+ account.status = details.get("status") or account.status
379
+
380
+ household_size = household.get("billdatehouseholdnumber") or household.get(
381
+ "householdnumber"
382
+ )
383
+ return AccountData(
384
+ account=account,
385
+ current_balance_rm=_to_float(details.get("currentBalance")),
386
+ outstanding_rm=_to_float(details.get("outstandingamount")),
387
+ overdue_rm=_to_float(details.get("overdueamount")),
388
+ latest_bill_amount_rm=_to_float(details.get("amount")),
389
+ overdue_status=details.get("overduestatus"),
390
+ bill_number=details.get("billnumber"),
391
+ bill_date=_to_date(details.get("billdate")),
392
+ due_date=_to_date(details.get("duedate")),
393
+ last_payment_date=_to_date(details.get("lastpaymentdate")),
394
+ household_size=int(household_size) if household_size else None,
395
+ lcd_target_lpcd=_to_float(household.get("householdconsumption")),
396
+ bills=bills,
397
+ payments=payments,
398
+ raw_details=details,
399
+ )
400
+
401
+ async def logout(self) -> None:
402
+ """Terminate the active session on the portal."""
403
+ if not self._refresh_token:
404
+ return
405
+ try:
406
+ await self._raw_post(
407
+ "/authentication/v1/logout",
408
+ {"refreshtoken": self._refresh_token},
409
+ True,
410
+ )
411
+ except AirSelangorError:
412
+ pass
413
+ finally:
414
+ self._access_token = None
415
+ self._refresh_token = None
@@ -0,0 +1,53 @@
1
+ """Custom exceptions for the Air Selangor API client."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class AirSelangorError(Exception):
7
+ """Base exception for all Air Selangor client errors."""
8
+
9
+
10
+ class AirSelangorAuthError(AirSelangorError):
11
+ """Raised when authentication fails or session is rejected."""
12
+
13
+
14
+ class AirSelangorApiError(AirSelangorError):
15
+ """Raised when the API returns an error envelope or unexpected response."""
16
+
17
+ def __init__(
18
+ self,
19
+ message: str,
20
+ code: str | None = None,
21
+ retryable: bool = False,
22
+ ) -> None:
23
+ super().__init__(message)
24
+ self.code = code
25
+ self.retryable = retryable
26
+
27
+
28
+ class AirSelangorConnectionError(AirSelangorError):
29
+ """Raised on network-level failure or gateway timeout (5xx)."""
30
+
31
+ def __init__(self, message: str) -> None:
32
+ super().__init__(message)
33
+ self.retryable = True
34
+
35
+
36
+ class AirSelangorRateLimitError(AirSelangorError):
37
+ """Raised when API returns rate limit or too many requests (429)."""
38
+
39
+
40
+ class GeoBlockedError(AirSelangorAuthError):
41
+ """Raised when request is blocked due to geographic/VPN restrictions.
42
+
43
+ Malaysian utility APIs frequently block non-Malaysian IP addresses and VPNs.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ message: str = (
49
+ "Access denied — Air Selangor API restricted to Malaysian IP addresses. "
50
+ "Please connect directly from a Malaysian network without VPN."
51
+ ),
52
+ ) -> None:
53
+ super().__init__(message)
airselangor/models.py ADDED
@@ -0,0 +1,174 @@
1
+ """Data models for Air Selangor accounts, bills, and payments."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from datetime import UTC, date, datetime
7
+ from typing import Any
8
+
9
+
10
+ def _to_float(value: Any) -> float | None:
11
+ """Parse string representation of float safely."""
12
+ if value is None or value == "":
13
+ return None
14
+ try:
15
+ return float(str(value).replace(",", "").strip())
16
+ except (TypeError, ValueError):
17
+ return None
18
+
19
+
20
+ def _to_date(value: Any) -> date | None:
21
+ """Parse ``2026-10-21T00:00:00`` style dates."""
22
+ if not value:
23
+ return None
24
+ try:
25
+ return datetime.fromisoformat(str(value)[:19]).date()
26
+ except ValueError:
27
+ return None
28
+
29
+
30
+ def _parse_portal_datetime(value: Any) -> datetime | None:
31
+ """Parse portal timestamps into an aware datetime.
32
+
33
+ Accepts ISO-8601 UTC (``2025-11-24T22:52:55.091594Z``) or display strings
34
+ (``Tue 2025-11-25 6:52 AM (UTC+08:00)``).
35
+ """
36
+ if not value:
37
+ return None
38
+ text = str(value).strip()
39
+ try:
40
+ parsed = datetime.fromisoformat(text.replace("Z", "+00:00"))
41
+ except ValueError:
42
+ parsed = None
43
+ if parsed is not None:
44
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
45
+ try:
46
+ body, _, zone = text.partition("(UTC")
47
+ parts = body.split()
48
+ if parts and not parts[0][0].isdigit():
49
+ parts = parts[1:] # drop weekday
50
+ naive = datetime.strptime(" ".join(parts[:3]), "%Y-%m-%d %I:%M %p")
51
+ offset = zone.rstrip(")").strip() or "+00:00"
52
+ return datetime.fromisoformat(naive.isoformat() + offset)
53
+ except (ValueError, IndexError):
54
+ return None
55
+
56
+
57
+ @dataclass(slots=True)
58
+ class WaterAccount:
59
+ """One water account linked to the portal user."""
60
+
61
+ account_id: str
62
+ account_number: str
63
+ display_name: str
64
+ address: str | None = None
65
+ status: str | None = None
66
+ is_smart_meter: bool = False
67
+ is_ebill: bool = False
68
+
69
+ @classmethod
70
+ def from_api(cls, item: dict[str, Any]) -> WaterAccount:
71
+ return cls(
72
+ account_id=str(item["wateraccountid"]),
73
+ account_number=str(item["accountnumber"]),
74
+ display_name=item.get("displayname") or str(item["accountnumber"]),
75
+ address=item.get("address"),
76
+ status=item.get("status"),
77
+ is_smart_meter=bool(item.get("issmartmeter")),
78
+ is_ebill=bool(item.get("is_ebil")),
79
+ )
80
+
81
+
82
+ @dataclass(slots=True)
83
+ class Bill:
84
+ """One monthly bill from the water-trend endpoint."""
85
+
86
+ bill_date: date
87
+ usage_m3: float
88
+ amount_rm: float
89
+
90
+ @classmethod
91
+ def from_api(cls, item: dict[str, Any]) -> Bill | None:
92
+ bill_date = _to_date(item.get("billdate"))
93
+ if bill_date is None:
94
+ return None
95
+ return cls(
96
+ bill_date=bill_date,
97
+ usage_m3=_to_float(item.get("waterusage")) or 0.0,
98
+ amount_rm=_to_float(item.get("amount")) or 0.0,
99
+ )
100
+
101
+
102
+ @dataclass(slots=True)
103
+ class Payment:
104
+ """One payment transaction."""
105
+
106
+ reference: str
107
+ amount_rm: float | None
108
+ status: str | None
109
+ method: str | None
110
+ bank: str | None
111
+ paid_at: datetime | None
112
+
113
+ @classmethod
114
+ def from_api(cls, item: dict[str, Any]) -> Payment:
115
+ return cls(
116
+ reference=item.get("referenceno") or item.get("transactionid") or "",
117
+ amount_rm=_to_float(item.get("amount")),
118
+ status=item.get("status"),
119
+ method=item.get("paymenttype") or None,
120
+ bank=item.get("bank") or None,
121
+ paid_at=_parse_portal_datetime(item.get("transactiondate")),
122
+ )
123
+
124
+
125
+ @dataclass(slots=True)
126
+ class AccountData:
127
+ """Aggregated information for one water account."""
128
+
129
+ account: WaterAccount
130
+ current_balance_rm: float | None = None
131
+ outstanding_rm: float | None = None
132
+ # Negative values mean the account is in credit
133
+ overdue_rm: float | None = None
134
+ latest_bill_amount_rm: float | None = None
135
+ overdue_status: str | None = None
136
+ bill_number: str | None = None
137
+ bill_date: date | None = None
138
+ due_date: date | None = None
139
+ last_payment_date: date | None = None
140
+ household_size: int | None = None
141
+ lcd_target_lpcd: float | None = None
142
+ bills: list[Bill] = field(default_factory=list)
143
+ payments: list[Payment] = field(default_factory=list)
144
+ raw_details: dict[str, Any] = field(default_factory=dict)
145
+
146
+ @property
147
+ def latest_bill(self) -> Bill | None:
148
+ return self.bills[-1] if self.bills else None
149
+
150
+ @property
151
+ def previous_bill(self) -> Bill | None:
152
+ return self.bills[-2] if len(self.bills) > 1 else None
153
+
154
+ @property
155
+ def average_usage_m3(self) -> float | None:
156
+ if not self.bills:
157
+ return None
158
+ return round(sum(b.usage_m3 for b in self.bills) / len(self.bills), 2)
159
+
160
+ @property
161
+ def usage_per_person_lpd(self) -> float | None:
162
+ """Litres per person per day for the latest bill (portal's LCD calculation)."""
163
+ bill = self.latest_bill
164
+ if bill is None or not self.household_size:
165
+ return None
166
+ days = 30
167
+ if self.previous_bill:
168
+ days = max((bill.bill_date - self.previous_bill.bill_date).days, 1)
169
+ return round(bill.usage_m3 * 1000 / days / self.household_size, 1)
170
+
171
+ @property
172
+ def last_payment(self) -> Payment | None:
173
+ ok = [p for p in self.payments if p.paid_at is not None]
174
+ return max(ok, key=lambda p: p.paid_at) if ok else None
airselangor/retry.py ADDED
@@ -0,0 +1,87 @@
1
+ """Bounded retry with exponential backoff and jitter for transient transport failures.
2
+
3
+ The Air Selangor customer portal APIs sit behind WAF/CDNs and intermittently
4
+ return transient 5xx errors or dropped connections. This helper absorbs these
5
+ transient hiccups inside individual API requests with exponential backoff and jitter.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+ import random
13
+ from collections.abc import Awaitable, Callable
14
+ from typing import TypeVar
15
+
16
+ import aiohttp
17
+
18
+ from .exceptions import AirSelangorError
19
+
20
+ T = TypeVar("T")
21
+
22
+ RETRYABLE_STATUS_CODES = frozenset({500, 502, 503, 504})
23
+
24
+ _RETRYABLE_EXCEPTIONS = (
25
+ asyncio.TimeoutError,
26
+ TimeoutError,
27
+ aiohttp.ClientError,
28
+ aiohttp.ServerDisconnectedError,
29
+ )
30
+
31
+ DEFAULT_MAX_ATTEMPTS = 3
32
+ DEFAULT_BASE_DELAY = 0.5
33
+ DEFAULT_BACKOFF_FACTOR = 2.0
34
+
35
+
36
+ def is_retryable_error(err: Exception) -> bool:
37
+ """Return True if the error is a transient failure worth retrying."""
38
+ if isinstance(err, _RETRYABLE_EXCEPTIONS):
39
+ return True
40
+ return isinstance(err, AirSelangorError) and getattr(err, "retryable", False)
41
+
42
+
43
+ async def with_retry(
44
+ send: Callable[[], Awaitable[T]],
45
+ *,
46
+ attempts: int = DEFAULT_MAX_ATTEMPTS,
47
+ base_delay: float = DEFAULT_BASE_DELAY,
48
+ backoff_factor: float = DEFAULT_BACKOFF_FACTOR,
49
+ logger: logging.Logger | None = None,
50
+ ) -> T:
51
+ """Call ``send`` with exponential backoff + jitter on transient failures.
52
+
53
+ Args:
54
+ send: Zero-arg coroutine factory performing one request attempt.
55
+ attempts: Maximum number of attempts (including the first).
56
+ base_delay: Base delay in seconds.
57
+ backoff_factor: Multiplier applied per attempt.
58
+ logger: Optional logger for debug notifications between attempts.
59
+
60
+ Returns:
61
+ Whatever ``send`` returns on the first successful attempt.
62
+ """
63
+ if attempts < 1:
64
+ raise ValueError(f"attempts must be >= 1, got {attempts}")
65
+ if base_delay < 0:
66
+ raise ValueError(f"base_delay must be >= 0, got {base_delay}")
67
+ if backoff_factor < 1:
68
+ raise ValueError(f"backoff_factor must be >= 1, got {backoff_factor}")
69
+
70
+ for attempt in range(attempts):
71
+ try:
72
+ return await send()
73
+ except Exception as err:
74
+ if attempt >= attempts - 1 or not is_retryable_error(err):
75
+ raise
76
+ delay = base_delay * (backoff_factor**attempt) + random.uniform(0, base_delay)
77
+ if logger is not None:
78
+ logger.debug(
79
+ "Transient Air Selangor request failure (attempt %d/%d), retrying in %.2fs: %s",
80
+ attempt + 1,
81
+ attempts,
82
+ delay,
83
+ err,
84
+ )
85
+ await asyncio.sleep(delay)
86
+
87
+ raise RuntimeError("with_retry exhausted attempts without returning")
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-airselangor
3
+ Version: 0.1.0
4
+ Summary: Asynchronous Python client for Air Selangor customer portal API
5
+ Author: Zubir Jamal
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/zubirjamal/python-airselangor
8
+ Project-URL: Repository, https://github.com/zubirjamal/python-airselangor
9
+ Project-URL: Issues, https://github.com/zubirjamal/python-airselangor/issues
10
+ Keywords: air-selangor,water-bill,utilities,malaysia,home-assistant
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Topic :: Home Automation
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Classifier: Intended Audience :: Developers
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+ Requires-Dist: aiohttp>=3.9.0
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest>=8.0.0; extra == "test"
25
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == "test"
26
+
27
+ # python-airselangor
28
+
29
+ [![PyPI](https://img.shields.io/pypi/v/python-airselangor.svg)](https://pypi.org/project/python-airselangor/)
30
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
31
+
32
+ Asynchronous Python client library for the **Air Selangor** customer portal (`api3.airselangor.com`).
33
+
34
+ Designed for standalone scripts, CLI exploration, and powering Home Assistant integrations.
35
+
36
+ ## Features
37
+
38
+ * **Full Async Support**: Native `async`/`await` powered by `aiohttp`.
39
+ * **Automatic Session Management**: Handles token acquisition, refresh tokens, and serialized re-authentication automatically.
40
+ * **Transient Error Resilience**: Built-in exponential backoff with randomized jitter on transient 5xx / connection drops to gracefully handle WAF/gateway hiccups.
41
+ * **Geo-Block Detection**: Detects and raises `GeoBlockedError` when accessed outside Malaysia or via blocked VPNs.
42
+ * **Typed Data Models**: Typed dataclasses for water accounts, monthly trend bills, payment transactions, and consumption stats.
43
+ * **Built-in CLI**: Quickly test credentials and inspect accounts directly from your terminal.
44
+
45
+ ## Installation
46
+
47
+ ```bash
48
+ pip install python-airselangor
49
+ ```
50
+
51
+ ## Quick Start (Python)
52
+
53
+ ```python
54
+ import asyncio
55
+ from airselangor import AirSelangorClient
56
+
57
+ async def main():
58
+ async with AirSelangorClient("YOUR_LOGIN_ID", "YOUR_PASSWORD") as client:
59
+ await client.login()
60
+ accounts = await client.get_accounts()
61
+ for acc in accounts:
62
+ data = await client.get_account_data(acc)
63
+ print(f"Account: {acc.account_number} ({acc.display_name})")
64
+ print(f"Current Balance: RM {data.current_balance_rm:.2f}")
65
+ if data.latest_bill:
66
+ print(f"Latest Bill: {data.latest_bill.usage_m3} m³ (RM {data.latest_bill.amount_rm:.2f})")
67
+
68
+ asyncio.run(main())
69
+ ```
70
+
71
+ ## CLI Usage
72
+
73
+ ```bash
74
+ python -m airselangor <login_id> <password>
75
+ ```
76
+
77
+ ## License
78
+
79
+ MIT License. See [LICENSE](LICENSE) for details.
@@ -0,0 +1,12 @@
1
+ airselangor/__init__.py,sha256=eYVAWGeK0zTtgTu4CaJxxc2QFj6D4mY-XndK3WheNv0,660
2
+ airselangor/__main__.py,sha256=2nUMNgsjar5raIaEya51Cmi6Dot-DERwxdUzSLvdLno,72
3
+ airselangor/cli.py,sha256=Rifho3k_SGC-3GEH7JRaBX3SapP2qgVYRQqaZQZmzNQ,2596
4
+ airselangor/client.py,sha256=Tgn__ZKBEq1g7EXdtqfjcN5aP_4X3lk110WHWqb_FA4,16067
5
+ airselangor/exceptions.py,sha256=y8t4pihgPx_wBxs4T8xRYwOgB3my-x8MVGDifbW3_XQ,1515
6
+ airselangor/models.py,sha256=Vb0_lD0SKnhHKnLloUAzEAZ8xhxAl0R6OqKNQz5yz1I,5530
7
+ airselangor/retry.py,sha256=cyfzqIT_4Jj7znXvd0ASCLhbfoiK8jNpV6Eq01tLUUM,2860
8
+ python_airselangor-0.1.0.dist-info/METADATA,sha256=186kQVFvlrNlpK_53yxM8GFzzRaj6X-OJqxCH5yeuII,3136
9
+ python_airselangor-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ python_airselangor-0.1.0.dist-info/entry_points.txt,sha256=tycJRKxIoUaXlzGKgxD_JuYnma0mF_5FG-R4sqWS658,53
11
+ python_airselangor-0.1.0.dist-info/top_level.txt,sha256=U7mLyRgSaTFqvZz2-iD6PtmgiXXuxDm-L4ipipHB7Uk,12
12
+ python_airselangor-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ airselangor = airselangor.cli:main
@@ -0,0 +1 @@
1
+ airselangor