python-metmalaysia 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.
- metmalaysia/__init__.py +64 -0
- metmalaysia/client.py +310 -0
- metmalaysia/const.py +38 -0
- metmalaysia/exceptions.py +18 -0
- metmalaysia/models.py +288 -0
- python_metmalaysia-0.1.0.dist-info/METADATA +42 -0
- python_metmalaysia-0.1.0.dist-info/RECORD +9 -0
- python_metmalaysia-0.1.0.dist-info/WHEEL +5 -0
- python_metmalaysia-0.1.0.dist-info/top_level.txt +1 -0
metmalaysia/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""MET Malaysia async client and parser models."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from .client import MetMalaysiaClient
|
|
5
|
+
from .const import (
|
|
6
|
+
EARTHQUAKE_URL,
|
|
7
|
+
FORECAST_URL,
|
|
8
|
+
MET_API_URL,
|
|
9
|
+
MET_TZ,
|
|
10
|
+
RADAR_URL,
|
|
11
|
+
SATELLITE_URL,
|
|
12
|
+
WARNING_URL,
|
|
13
|
+
)
|
|
14
|
+
from .exceptions import (
|
|
15
|
+
MetAuthError,
|
|
16
|
+
MetConnectionError,
|
|
17
|
+
MetError,
|
|
18
|
+
MetForbiddenError,
|
|
19
|
+
)
|
|
20
|
+
from .models import (
|
|
21
|
+
MetForecastData,
|
|
22
|
+
ObservationData,
|
|
23
|
+
Station,
|
|
24
|
+
distance_km,
|
|
25
|
+
get_met_tz,
|
|
26
|
+
loose_name,
|
|
27
|
+
met_today,
|
|
28
|
+
nearest_station,
|
|
29
|
+
normalize_name,
|
|
30
|
+
parse_forecast,
|
|
31
|
+
parse_marine,
|
|
32
|
+
parse_met_datetime,
|
|
33
|
+
parse_observations,
|
|
34
|
+
stations_from_records,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"EARTHQUAKE_URL",
|
|
39
|
+
"FORECAST_URL",
|
|
40
|
+
"MET_API_URL",
|
|
41
|
+
"MET_TZ",
|
|
42
|
+
"MetAuthError",
|
|
43
|
+
"MetConnectionError",
|
|
44
|
+
"MetError",
|
|
45
|
+
"MetForbiddenError",
|
|
46
|
+
"MetForecastData",
|
|
47
|
+
"MetMalaysiaClient",
|
|
48
|
+
"ObservationData",
|
|
49
|
+
"RADAR_URL",
|
|
50
|
+
"SATELLITE_URL",
|
|
51
|
+
"Station",
|
|
52
|
+
"WARNING_URL",
|
|
53
|
+
"distance_km",
|
|
54
|
+
"get_met_tz",
|
|
55
|
+
"loose_name",
|
|
56
|
+
"met_today",
|
|
57
|
+
"nearest_station",
|
|
58
|
+
"normalize_name",
|
|
59
|
+
"parse_forecast",
|
|
60
|
+
"parse_marine",
|
|
61
|
+
"parse_met_datetime",
|
|
62
|
+
"parse_observations",
|
|
63
|
+
"stations_from_records",
|
|
64
|
+
]
|
metmalaysia/client.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
"""Client for MET Malaysia API and data.gov.my weather."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
from collections import deque
|
|
6
|
+
from datetime import timedelta
|
|
7
|
+
import hashlib
|
|
8
|
+
import logging
|
|
9
|
+
import re
|
|
10
|
+
import time
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import aiohttp
|
|
14
|
+
|
|
15
|
+
from .const import (
|
|
16
|
+
DATA_GOV_MY_BASE,
|
|
17
|
+
EARTHQUAKE_URL,
|
|
18
|
+
FORECAST_URL,
|
|
19
|
+
MET_API_URL,
|
|
20
|
+
MET_CATEGORY_BY_PREFIX,
|
|
21
|
+
MET_LOCATION_CATEGORIES,
|
|
22
|
+
MET_PAGE_LIMIT,
|
|
23
|
+
REQUEST_TIMEOUT,
|
|
24
|
+
WARNING_URL,
|
|
25
|
+
)
|
|
26
|
+
from .exceptions import (
|
|
27
|
+
MetAuthError,
|
|
28
|
+
MetConnectionError,
|
|
29
|
+
MetError,
|
|
30
|
+
MetForbiddenError,
|
|
31
|
+
)
|
|
32
|
+
from .models import (
|
|
33
|
+
loose_name,
|
|
34
|
+
met_today,
|
|
35
|
+
normalize_name,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
_LOGGER = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
BURST_LIMIT = 9
|
|
41
|
+
BURST_WINDOW = 60.0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class _BurstLimiter:
|
|
45
|
+
"""Space out MET requests to protect the 10-requests/minute limit."""
|
|
46
|
+
|
|
47
|
+
def __init__(self) -> None:
|
|
48
|
+
self._lock = asyncio.Lock()
|
|
49
|
+
self._sent: deque[float] = deque()
|
|
50
|
+
|
|
51
|
+
async def acquire(self) -> None:
|
|
52
|
+
async with self._lock:
|
|
53
|
+
now = time.monotonic()
|
|
54
|
+
while self._sent and now - self._sent[0] >= BURST_WINDOW:
|
|
55
|
+
self._sent.popleft()
|
|
56
|
+
if len(self._sent) >= BURST_LIMIT:
|
|
57
|
+
wait = BURST_WINDOW - (now - self._sent[0])
|
|
58
|
+
_LOGGER.debug("Waiting %.0fs to stay under MET's burst limit", wait)
|
|
59
|
+
await asyncio.sleep(wait)
|
|
60
|
+
self._sent.popleft()
|
|
61
|
+
self._sent.append(time.monotonic())
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _max_age(cache_control: str | None) -> int:
|
|
65
|
+
"""Seconds a response may be reused according to Cache-Control."""
|
|
66
|
+
if not cache_control:
|
|
67
|
+
return 0
|
|
68
|
+
lowered = cache_control.lower()
|
|
69
|
+
if "no-store" in lowered or "no-cache" in lowered:
|
|
70
|
+
return 0
|
|
71
|
+
match = re.search(r"max-age\s*=\s*(\d+)", lowered)
|
|
72
|
+
return int(match.group(1)) if match else 0
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class MetMalaysiaClient:
|
|
76
|
+
"""Async client for MET Malaysia API and data.gov.my weather feeds."""
|
|
77
|
+
|
|
78
|
+
def __init__(
|
|
79
|
+
self,
|
|
80
|
+
api_key: str | None = None,
|
|
81
|
+
session: aiohttp.ClientSession | None = None,
|
|
82
|
+
timeout: int = REQUEST_TIMEOUT,
|
|
83
|
+
) -> None:
|
|
84
|
+
"""Initialize MetMalaysiaClient."""
|
|
85
|
+
self._api_key = api_key
|
|
86
|
+
self._session = session
|
|
87
|
+
self._timeout = timeout
|
|
88
|
+
self._limiter = _BurstLimiter()
|
|
89
|
+
self._cache: dict[tuple, tuple[float, Any]] = {}
|
|
90
|
+
self._key_id = (
|
|
91
|
+
hashlib.sha256(api_key.encode()).hexdigest()[:16] if api_key else ""
|
|
92
|
+
)
|
|
93
|
+
self.calls = 0
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def api_key(self) -> str | None:
|
|
97
|
+
return self._api_key
|
|
98
|
+
|
|
99
|
+
@api_key.setter
|
|
100
|
+
def api_key(self, val: str | None) -> None:
|
|
101
|
+
self._api_key = val
|
|
102
|
+
self._key_id = hashlib.sha256(val.encode()).hexdigest()[:16] if val else ""
|
|
103
|
+
|
|
104
|
+
async def _get_session(self) -> aiohttp.ClientSession:
|
|
105
|
+
if self._session is None or self._session.closed:
|
|
106
|
+
self._session = aiohttp.ClientSession()
|
|
107
|
+
return self._session
|
|
108
|
+
|
|
109
|
+
# --- data.gov.my endpoints (open, keyless) ---
|
|
110
|
+
|
|
111
|
+
async def async_get_data_gov_forecast(
|
|
112
|
+
self, params: dict[str, str] | None = None
|
|
113
|
+
) -> list[dict[str, Any]]:
|
|
114
|
+
"""Fetch weather forecasts from data.gov.my."""
|
|
115
|
+
return await self._fetch_open_json(FORECAST_URL, params)
|
|
116
|
+
|
|
117
|
+
async def async_get_data_gov_warnings(
|
|
118
|
+
self, params: dict[str, str] | None = None
|
|
119
|
+
) -> list[dict[str, Any]]:
|
|
120
|
+
"""Fetch weather warnings from data.gov.my."""
|
|
121
|
+
return await self._fetch_open_json(WARNING_URL, params)
|
|
122
|
+
|
|
123
|
+
async def async_get_data_gov_earthquakes(
|
|
124
|
+
self, params: dict[str, str] | None = None
|
|
125
|
+
) -> list[dict[str, Any]]:
|
|
126
|
+
"""Fetch earthquake alerts from data.gov.my."""
|
|
127
|
+
return await self._fetch_open_json(EARTHQUAKE_URL, params)
|
|
128
|
+
|
|
129
|
+
async def _fetch_open_json(
|
|
130
|
+
self, url: str, params: dict[str, str] | None = None
|
|
131
|
+
) -> list[dict[str, Any]]:
|
|
132
|
+
session = await self._get_session()
|
|
133
|
+
try:
|
|
134
|
+
async with asyncio.timeout(self._timeout):
|
|
135
|
+
async with session.get(url, params=params) as resp:
|
|
136
|
+
if resp.status != 200:
|
|
137
|
+
raise MetConnectionError(f"{url} returned HTTP {resp.status}")
|
|
138
|
+
data = await resp.json(content_type=None)
|
|
139
|
+
except (aiohttp.ClientError, TimeoutError) as err:
|
|
140
|
+
raise MetConnectionError(f"Error communicating with {url}: {err}") from err
|
|
141
|
+
except ValueError as err:
|
|
142
|
+
raise MetConnectionError(f"Invalid JSON from {url}: {err}") from err
|
|
143
|
+
|
|
144
|
+
if not isinstance(data, list):
|
|
145
|
+
raise MetConnectionError(f"Unexpected payload from {url}")
|
|
146
|
+
return data
|
|
147
|
+
|
|
148
|
+
# --- MET Malaysia API (optional key) ---
|
|
149
|
+
|
|
150
|
+
async def async_get(
|
|
151
|
+
self, path: str, params: dict[str, Any] | None = None, *, use_cache: bool = True
|
|
152
|
+
) -> dict[str, Any]:
|
|
153
|
+
"""GET one MET endpoint and return its JSON object."""
|
|
154
|
+
if not self._api_key:
|
|
155
|
+
raise MetAuthError("MET API key is required for this operation")
|
|
156
|
+
|
|
157
|
+
params = {k: str(v) for k, v in (params or {}).items()}
|
|
158
|
+
cache_key = (self._key_id, path, tuple(sorted(params.items())))
|
|
159
|
+
if use_cache and (hit := self._cache.get(cache_key)) and hit[0] > time.monotonic():
|
|
160
|
+
return hit[1]
|
|
161
|
+
|
|
162
|
+
await self._limiter.acquire()
|
|
163
|
+
session = await self._get_session()
|
|
164
|
+
url = f"{MET_API_URL}/{path}"
|
|
165
|
+
headers = {"Authorization": f"METToken {self._api_key}"}
|
|
166
|
+
|
|
167
|
+
try:
|
|
168
|
+
async with asyncio.timeout(self._timeout):
|
|
169
|
+
async with session.get(url, params=params, headers=headers) as response:
|
|
170
|
+
self.calls += 1
|
|
171
|
+
if response.status == 401:
|
|
172
|
+
raise MetAuthError("MET API key rejected")
|
|
173
|
+
if response.status == 403:
|
|
174
|
+
raise MetForbiddenError(f"No access to MET {path}")
|
|
175
|
+
if response.status != 200:
|
|
176
|
+
raise MetConnectionError(f"MET {path} returned HTTP {response.status}")
|
|
177
|
+
data = await response.json(content_type=None)
|
|
178
|
+
max_age = _max_age(response.headers.get("Cache-Control"))
|
|
179
|
+
except (aiohttp.ClientError, TimeoutError) as err:
|
|
180
|
+
raise MetConnectionError(f"Error communicating with MET {path}: {err}") from err
|
|
181
|
+
except ValueError as err:
|
|
182
|
+
raise MetConnectionError(f"Invalid JSON from MET {path}") from err
|
|
183
|
+
|
|
184
|
+
if not isinstance(data, dict):
|
|
185
|
+
raise MetConnectionError(f"Unexpected payload from MET {path}")
|
|
186
|
+
if max_age > 0:
|
|
187
|
+
self._cache[cache_key] = (time.monotonic() + max_age, data)
|
|
188
|
+
return data
|
|
189
|
+
|
|
190
|
+
async def async_get_all(
|
|
191
|
+
self, path: str, params: dict[str, Any] | None = None, *, max_pages: int = 5
|
|
192
|
+
) -> list[dict[str, Any]]:
|
|
193
|
+
"""GET every page with offset pagination up to max_pages."""
|
|
194
|
+
results: list[dict[str, Any]] = []
|
|
195
|
+
offset = 0
|
|
196
|
+
for _ in range(max_pages):
|
|
197
|
+
page_params = dict(params or {})
|
|
198
|
+
if offset:
|
|
199
|
+
page_params["offset"] = offset
|
|
200
|
+
data = await self.async_get(path, page_params)
|
|
201
|
+
page = [item for item in data.get("results") or [] if isinstance(item, dict)]
|
|
202
|
+
results.extend(page)
|
|
203
|
+
resultset = (data.get("metadata") or {}).get("resultset") or {}
|
|
204
|
+
count = resultset.get("count")
|
|
205
|
+
limit = resultset.get("limit") or MET_PAGE_LIMIT
|
|
206
|
+
offset += limit
|
|
207
|
+
if not page or not isinstance(count, int) or offset >= count:
|
|
208
|
+
break
|
|
209
|
+
return results
|
|
210
|
+
|
|
211
|
+
async def async_validate(self) -> None:
|
|
212
|
+
"""Validate that the API key is active and accepted."""
|
|
213
|
+
await self.async_get(
|
|
214
|
+
"locations", {"locationcategoryid": "STATE"}, use_cache=False
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
async def async_probe_observation(self) -> bool:
|
|
218
|
+
"""True when the key may read hourly observations."""
|
|
219
|
+
today = met_today().isoformat()
|
|
220
|
+
try:
|
|
221
|
+
await self.async_get(
|
|
222
|
+
"data",
|
|
223
|
+
{
|
|
224
|
+
"datasetid": "OBSERVATION",
|
|
225
|
+
"datacategoryid": "HOURLY",
|
|
226
|
+
"locationid": "ALL_LOCATIONS",
|
|
227
|
+
"start_date": today,
|
|
228
|
+
"end_date": today,
|
|
229
|
+
},
|
|
230
|
+
use_cache=False,
|
|
231
|
+
)
|
|
232
|
+
except MetForbiddenError:
|
|
233
|
+
return False
|
|
234
|
+
return True
|
|
235
|
+
|
|
236
|
+
async def async_locations(self, category: str) -> list[dict[str, Any]]:
|
|
237
|
+
"""All MET locations of one category."""
|
|
238
|
+
return await self.async_get_all(
|
|
239
|
+
"locations", {"locationcategoryid": category}, max_pages=20
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
async def async_find_location(
|
|
243
|
+
self, location_id: str, location_name: str
|
|
244
|
+
) -> dict[str, Any] | None:
|
|
245
|
+
"""Find the MET location by matching name."""
|
|
246
|
+
wanted = normalize_name(location_name)
|
|
247
|
+
if not wanted:
|
|
248
|
+
return None
|
|
249
|
+
preferred = MET_CATEGORY_BY_PREFIX.get(location_id[:2])
|
|
250
|
+
categories = [preferred] if preferred else []
|
|
251
|
+
categories += [c for c in MET_LOCATION_CATEGORIES if c != preferred]
|
|
252
|
+
for category in categories:
|
|
253
|
+
candidates = [
|
|
254
|
+
item for item in await self.async_locations(category) if item.get("id")
|
|
255
|
+
]
|
|
256
|
+
for item in candidates:
|
|
257
|
+
if normalize_name(item.get("name")) == wanted:
|
|
258
|
+
return item
|
|
259
|
+
for item in candidates:
|
|
260
|
+
if loose_name(normalize_name(item.get("name"))) == loose_name(wanted):
|
|
261
|
+
return item
|
|
262
|
+
return None
|
|
263
|
+
|
|
264
|
+
async def async_forecast(self, met_location_id: str, days: int = 7) -> list[dict[str, Any]]:
|
|
265
|
+
"""General forecast records."""
|
|
266
|
+
start = met_today()
|
|
267
|
+
return await self.async_get_all(
|
|
268
|
+
"data",
|
|
269
|
+
{
|
|
270
|
+
"datasetid": "FORECAST",
|
|
271
|
+
"datacategoryid": "GENERAL",
|
|
272
|
+
"locationid": met_location_id,
|
|
273
|
+
"start_date": start.isoformat(),
|
|
274
|
+
"end_date": (start + timedelta(days=days - 1)).isoformat(),
|
|
275
|
+
"lang": "en",
|
|
276
|
+
},
|
|
277
|
+
max_pages=3,
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
async def async_marine(self, waters_id: str) -> list[dict[str, Any]]:
|
|
281
|
+
"""Today's marine forecast for one area."""
|
|
282
|
+
today = met_today().isoformat()
|
|
283
|
+
return await self.async_get_all(
|
|
284
|
+
"data",
|
|
285
|
+
{
|
|
286
|
+
"datasetid": "FORECAST",
|
|
287
|
+
"datacategoryid": "MARINE",
|
|
288
|
+
"locationid": waters_id,
|
|
289
|
+
"start_date": today,
|
|
290
|
+
"end_date": today,
|
|
291
|
+
"lang": "en",
|
|
292
|
+
},
|
|
293
|
+
max_pages=1,
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
async def async_observations(
|
|
297
|
+
self, location_id: str, *, datatype: str | None = None, max_pages: int = 6
|
|
298
|
+
) -> list[dict[str, Any]]:
|
|
299
|
+
"""Hourly observations for one station."""
|
|
300
|
+
today = met_today().isoformat()
|
|
301
|
+
params = {
|
|
302
|
+
"datasetid": "OBSERVATION",
|
|
303
|
+
"datacategoryid": "HOURLY",
|
|
304
|
+
"locationid": location_id,
|
|
305
|
+
"start_date": today,
|
|
306
|
+
"end_date": today,
|
|
307
|
+
}
|
|
308
|
+
if datatype:
|
|
309
|
+
params["datatypeid"] = datatype
|
|
310
|
+
return await self.async_get_all("data", params, max_pages=max_pages)
|
metmalaysia/const.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Constants for MET Malaysia client."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from datetime import timedelta, timezone
|
|
5
|
+
from typing import Final
|
|
6
|
+
|
|
7
|
+
MET_TZ: Final = timezone(timedelta(hours=8))
|
|
8
|
+
MET_TIMEZONE: Final = "Asia/Kuala_Lumpur"
|
|
9
|
+
MET_API_URL: Final = "https://api.met.gov.my/v2.1"
|
|
10
|
+
DATA_GOV_MY_BASE: Final = "https://api.data.gov.my"
|
|
11
|
+
FORECAST_URL: Final = f"{DATA_GOV_MY_BASE}/weather/forecast"
|
|
12
|
+
WARNING_URL: Final = f"{DATA_GOV_MY_BASE}/weather/warning"
|
|
13
|
+
EARTHQUAKE_URL: Final = f"{DATA_GOV_MY_BASE}/weather/warning/earthquake"
|
|
14
|
+
|
|
15
|
+
MET_PAGE_LIMIT: Final = 50
|
|
16
|
+
MET_FORECAST_DAYS: Final = 7
|
|
17
|
+
|
|
18
|
+
MET_CATEGORY_BY_PREFIX: Final = {
|
|
19
|
+
"Tn": "TOWN",
|
|
20
|
+
"Ds": "DISTRICT",
|
|
21
|
+
"Rc": "TOURISTDEST",
|
|
22
|
+
"Dv": "DIVISION",
|
|
23
|
+
"St": "STATE",
|
|
24
|
+
}
|
|
25
|
+
MET_LOCATION_CATEGORIES: Final = ("TOWN", "DISTRICT", "TOURISTDEST", "DIVISION", "STATE")
|
|
26
|
+
MET_OBSERVATION_TYPES: Final = (
|
|
27
|
+
"TEMP",
|
|
28
|
+
"RH",
|
|
29
|
+
"WND_SPD",
|
|
30
|
+
"WND_DIR",
|
|
31
|
+
"VIS",
|
|
32
|
+
"RAIN_1HR",
|
|
33
|
+
"PRST_WX_ID",
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
SATELLITE_URL: Final = "https://api.met.gov.my/static/images/satelit-latest.gif"
|
|
37
|
+
RADAR_URL: Final = "https://api.met.gov.my/static/images/radar-latest.gif"
|
|
38
|
+
REQUEST_TIMEOUT: Final = 30
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Exceptions for MET Malaysia client."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class MetError(Exception):
|
|
6
|
+
"""Base error for the MET API."""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class MetAuthError(MetError):
|
|
10
|
+
"""The API key was rejected (HTTP 401)."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class MetForbiddenError(MetError):
|
|
14
|
+
"""The key is valid but has no access to this dataset (HTTP 403)."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MetConnectionError(MetError):
|
|
18
|
+
"""Timeout, connection problem, rate limit or unexpected response."""
|
metmalaysia/models.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""Data models and parsers for MET Malaysia."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from datetime import date, datetime, timedelta, timezone
|
|
6
|
+
from math import asin, cos, radians, sin, sqrt
|
|
7
|
+
import re
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .const import (
|
|
11
|
+
MET_CATEGORY_BY_PREFIX,
|
|
12
|
+
MET_LOCATION_CATEGORIES,
|
|
13
|
+
MET_OBSERVATION_TYPES,
|
|
14
|
+
MET_TZ,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
_MET_DATE_RE = re.compile(
|
|
18
|
+
r"(?P<date>\d{4}-\d{2}-\d{2})"
|
|
19
|
+
r"(?:[ T]+(?P<hour>\d{1,2}):(?P<minute>\d{2})(?::(?P<second>\d{2}))?"
|
|
20
|
+
r"\s*(?P<ampm>[AaPp][Mm])?)?"
|
|
21
|
+
r"(?:\s*\(?\s*(?:UTC|GMT)\s*(?P<tz>[+-]\d{1,2}(?::?\d{2})?)\s*\)?)?"
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def get_met_tz() -> timezone:
|
|
26
|
+
"""Return the cached MET Malaysia timezone (UTC+8)."""
|
|
27
|
+
return MET_TZ
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def met_today() -> date:
|
|
31
|
+
"""Today's date in Malaysia."""
|
|
32
|
+
return datetime.now(MET_TZ).date()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def parse_met_datetime(value: Any) -> datetime | None:
|
|
36
|
+
"""Parse a MET date string into an aware datetime; None when unparseable."""
|
|
37
|
+
if not isinstance(value, str) or not value.strip():
|
|
38
|
+
return None
|
|
39
|
+
match = _MET_DATE_RE.search(value)
|
|
40
|
+
if match is None:
|
|
41
|
+
return None
|
|
42
|
+
try:
|
|
43
|
+
day = date.fromisoformat(match["date"])
|
|
44
|
+
hour = int(match["hour"] or 0)
|
|
45
|
+
minute = int(match["minute"] or 0)
|
|
46
|
+
second = int(match["second"] or 0)
|
|
47
|
+
ampm = (match["ampm"] or "").upper()
|
|
48
|
+
if ampm == "PM" and hour < 12:
|
|
49
|
+
hour += 12
|
|
50
|
+
elif ampm == "AM" and hour == 12:
|
|
51
|
+
hour = 0
|
|
52
|
+
tzinfo: Any = MET_TZ
|
|
53
|
+
if match["tz"]:
|
|
54
|
+
raw = match["tz"].replace(":", "")
|
|
55
|
+
sign = -1 if raw[0] == "-" else 1
|
|
56
|
+
digits = raw[1:]
|
|
57
|
+
hours = int(digits[:-2] or 0) if len(digits) > 2 else int(digits)
|
|
58
|
+
minutes = int(digits[-2:]) if len(digits) > 2 else 0
|
|
59
|
+
tzinfo = timezone(sign * timedelta(hours=hours, minutes=minutes))
|
|
60
|
+
return datetime(day.year, day.month, day.day, hour, minute, second, tzinfo=tzinfo)
|
|
61
|
+
except ValueError:
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def normalize_name(name: Any) -> str:
|
|
66
|
+
"""Normalise a location name for matching: upper case, no brackets."""
|
|
67
|
+
if not isinstance(name, str):
|
|
68
|
+
return ""
|
|
69
|
+
name = name.split("(")[0]
|
|
70
|
+
name = re.sub(r"[^A-Za-z0-9]+", " ", name)
|
|
71
|
+
return " ".join(name.upper().split())
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def loose_name(name: str) -> str:
|
|
75
|
+
"""Looser form: ignore a plural S on each word (Highland/Highlands)."""
|
|
76
|
+
return " ".join(word[:-1] if word.endswith("S") and len(word) > 3 else word for word in name.split())
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def distance_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
|
80
|
+
"""Great-circle distance in km."""
|
|
81
|
+
lat1, lon1, lat2, lon2 = map(radians, (lat1, lon1, lat2, lon2))
|
|
82
|
+
a = sin((lat2 - lat1) / 2) ** 2 + cos(lat1) * cos(lat2) * sin((lon2 - lon1) / 2) ** 2
|
|
83
|
+
return 6371.0 * 2 * asin(sqrt(a))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def to_float(value: Any) -> float | None:
|
|
87
|
+
"""Convert value to float if possible."""
|
|
88
|
+
if value is None or isinstance(value, bool):
|
|
89
|
+
return None
|
|
90
|
+
try:
|
|
91
|
+
return float(str(value).strip())
|
|
92
|
+
except ValueError:
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@dataclass
|
|
97
|
+
class MetForecastData:
|
|
98
|
+
"""Parsed MET extras for one location."""
|
|
99
|
+
|
|
100
|
+
days: dict[str, dict[str, Any]] = field(default_factory=dict)
|
|
101
|
+
state: str | None = None
|
|
102
|
+
latitude: float | None = None
|
|
103
|
+
longitude: float | None = None
|
|
104
|
+
issued: datetime | None = None
|
|
105
|
+
marine: dict[str, Any] | None = None
|
|
106
|
+
|
|
107
|
+
def day(self, when: date | None = None) -> dict[str, Any] | None:
|
|
108
|
+
"""Values for one day (default today in Malaysia, else the next one)."""
|
|
109
|
+
key = (when or met_today()).isoformat()
|
|
110
|
+
if key in self.days:
|
|
111
|
+
return self.days[key]
|
|
112
|
+
upcoming = sorted(k for k in self.days if k >= key)
|
|
113
|
+
return self.days[upcoming[0]] if upcoming else None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def parse_forecast(records: list[dict[str, Any]]) -> MetForecastData:
|
|
117
|
+
"""Group MET GENERAL forecast records by day and datatype."""
|
|
118
|
+
data = MetForecastData()
|
|
119
|
+
for record in records:
|
|
120
|
+
if not isinstance(record, dict):
|
|
121
|
+
continue
|
|
122
|
+
when = parse_met_datetime(record.get("date"))
|
|
123
|
+
datatype = record.get("datatype")
|
|
124
|
+
if when is None or not isinstance(datatype, str):
|
|
125
|
+
continue
|
|
126
|
+
data.days.setdefault(when.date().isoformat(), {})[datatype] = record.get("value")
|
|
127
|
+
if data.state is None and record.get("locationrootname"):
|
|
128
|
+
data.state = record["locationrootname"]
|
|
129
|
+
if data.latitude is None:
|
|
130
|
+
data.latitude = to_float(record.get("latitude"))
|
|
131
|
+
data.longitude = to_float(record.get("longitude"))
|
|
132
|
+
attributes = record.get("attributes")
|
|
133
|
+
if isinstance(attributes, dict) and datatype in ("FGM", "FGA", "FGN"):
|
|
134
|
+
issued = parse_met_datetime(attributes.get("valid_from"))
|
|
135
|
+
if issued and (data.issued is None or issued > data.issued):
|
|
136
|
+
data.issued = issued
|
|
137
|
+
return data
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def with_unit(value: Any, attributes: Any) -> str | None:
|
|
141
|
+
if value is None or value == "":
|
|
142
|
+
return None
|
|
143
|
+
unit = attributes.get("unit") if isinstance(attributes, dict) else None
|
|
144
|
+
return f"{value} {unit}" if unit else str(value)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def parse_marine(records: list[dict[str, Any]], area_name: str | None) -> dict[str, Any] | None:
|
|
148
|
+
"""Today's marine wind and waves; None when MET returned nothing usable."""
|
|
149
|
+
today = met_today()
|
|
150
|
+
found: dict[str, Any] = {}
|
|
151
|
+
for record in records:
|
|
152
|
+
if not isinstance(record, dict):
|
|
153
|
+
continue
|
|
154
|
+
when = parse_met_datetime(record.get("date"))
|
|
155
|
+
if when is not None and when.date() != today:
|
|
156
|
+
continue
|
|
157
|
+
datatype = record.get("datatype")
|
|
158
|
+
if datatype == "FMWS":
|
|
159
|
+
found["marine_wind_speed"] = with_unit(record.get("value"), record.get("attributes"))
|
|
160
|
+
elif datatype == "FMWD":
|
|
161
|
+
found["marine_wind_direction"] = record.get("value")
|
|
162
|
+
elif datatype == "FMWH":
|
|
163
|
+
found["marine_wave_height"] = with_unit(record.get("value"), record.get("attributes"))
|
|
164
|
+
if not area_name and record.get("locationname"):
|
|
165
|
+
area_name = record["locationname"]
|
|
166
|
+
if not found:
|
|
167
|
+
return None
|
|
168
|
+
return {"marine_area": area_name, **found}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@dataclass
|
|
172
|
+
class Station:
|
|
173
|
+
"""An observation station seen in /data records."""
|
|
174
|
+
|
|
175
|
+
id: str
|
|
176
|
+
name: str | None
|
|
177
|
+
latitude: float
|
|
178
|
+
longitude: float
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def stations_from_records(records: list[dict[str, Any]]) -> list[Station]:
|
|
182
|
+
"""Unique stations with coordinates from observation records."""
|
|
183
|
+
stations: dict[str, Station] = {}
|
|
184
|
+
for record in records:
|
|
185
|
+
if not isinstance(record, dict):
|
|
186
|
+
continue
|
|
187
|
+
station_id = record.get("locationid")
|
|
188
|
+
lat = to_float(record.get("latitude"))
|
|
189
|
+
lon = to_float(record.get("longitude"))
|
|
190
|
+
if not station_id or lat is None or lon is None or station_id in stations:
|
|
191
|
+
continue
|
|
192
|
+
stations[station_id] = Station(station_id, record.get("locationname"), lat, lon)
|
|
193
|
+
return list(stations.values())
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def nearest_station(stations: list[Station], lat: float, lon: float) -> Station | None:
|
|
197
|
+
"""Closest station to a point."""
|
|
198
|
+
if not stations:
|
|
199
|
+
return None
|
|
200
|
+
return min(stations, key=lambda s: distance_km(lat, lon, s.latitude, s.longitude))
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@dataclass
|
|
204
|
+
class ObservationData:
|
|
205
|
+
"""Latest hourly observation at one station."""
|
|
206
|
+
|
|
207
|
+
station_id: str
|
|
208
|
+
station_name: str | None = None
|
|
209
|
+
observed: datetime | None = None
|
|
210
|
+
temperature: float | None = None
|
|
211
|
+
humidity: float | None = None
|
|
212
|
+
wind_speed: float | None = None # km/h
|
|
213
|
+
wind_bearing: float | str | None = None
|
|
214
|
+
visibility: float | None = None # km
|
|
215
|
+
precipitation: float | None = None # mm
|
|
216
|
+
present_weather_id: Any = None
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def unit_from_record(record: dict[str, Any]) -> str:
|
|
220
|
+
attributes = record.get("attributes")
|
|
221
|
+
unit = attributes.get("unit") if isinstance(attributes, dict) else None
|
|
222
|
+
return str(unit).strip().lower() if unit else ""
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def wind_kmh(value: float, unit: str) -> float:
|
|
226
|
+
unit = unit.replace(" ", "")
|
|
227
|
+
if unit in ("m/s", "ms-1", "ms^-1", "mps", "m s-1"):
|
|
228
|
+
return round(value * 3.6, 1)
|
|
229
|
+
if unit in ("knot", "knots", "kt", "kts", "kn"):
|
|
230
|
+
return round(value * 1.852, 1)
|
|
231
|
+
if unit in ("mph",):
|
|
232
|
+
return round(value * 1.609344, 1)
|
|
233
|
+
return value
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def visibility_km(value: float, unit: str) -> float:
|
|
237
|
+
if unit in ("m", "meter", "meters", "metre", "metres"):
|
|
238
|
+
return round(value / 1000, 2)
|
|
239
|
+
if not unit and value > 100: # unlabelled metres
|
|
240
|
+
return round(value / 1000, 2)
|
|
241
|
+
return value
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def parse_observations(
|
|
245
|
+
records: list[dict[str, Any]], station_id: str, now: datetime | None = None, max_age: timedelta | None = None
|
|
246
|
+
) -> ObservationData | None:
|
|
247
|
+
"""Latest value of each hourly datatype for one station."""
|
|
248
|
+
latest: dict[str, tuple[datetime, dict[str, Any]]] = {}
|
|
249
|
+
name: str | None = None
|
|
250
|
+
for record in records:
|
|
251
|
+
if not isinstance(record, dict) or record.get("locationid") != station_id:
|
|
252
|
+
continue
|
|
253
|
+
datatype = record.get("datatype")
|
|
254
|
+
when = parse_met_datetime(record.get("date"))
|
|
255
|
+
if datatype not in MET_OBSERVATION_TYPES or when is None:
|
|
256
|
+
continue
|
|
257
|
+
if record.get("value") is None or record.get("value") == "":
|
|
258
|
+
continue
|
|
259
|
+
name = name or record.get("locationname")
|
|
260
|
+
if datatype not in latest or when > latest[datatype][0]:
|
|
261
|
+
latest[datatype] = (when, record)
|
|
262
|
+
if not latest:
|
|
263
|
+
return None
|
|
264
|
+
|
|
265
|
+
observed = max(when for when, _ in latest.values())
|
|
266
|
+
if now is not None and max_age is not None and now - observed > max_age:
|
|
267
|
+
return None
|
|
268
|
+
|
|
269
|
+
data = ObservationData(station_id=station_id, station_name=name, observed=observed)
|
|
270
|
+
for datatype, (_, record) in latest.items():
|
|
271
|
+
value = record.get("value")
|
|
272
|
+
number = to_float(value)
|
|
273
|
+
unit = unit_from_record(record)
|
|
274
|
+
if datatype == "TEMP":
|
|
275
|
+
data.temperature = number
|
|
276
|
+
elif datatype == "RH" and number is not None:
|
|
277
|
+
data.humidity = number
|
|
278
|
+
elif datatype == "WND_SPD" and number is not None:
|
|
279
|
+
data.wind_speed = wind_kmh(number, unit)
|
|
280
|
+
elif datatype == "WND_DIR":
|
|
281
|
+
data.wind_bearing = number if number is not None else (str(value).strip() or None)
|
|
282
|
+
elif datatype == "VIS" and number is not None:
|
|
283
|
+
data.visibility = visibility_km(number, unit)
|
|
284
|
+
elif datatype == "RAIN_1HR":
|
|
285
|
+
data.precipitation = number
|
|
286
|
+
elif datatype == "PRST_WX_ID":
|
|
287
|
+
data.present_weather_id = value
|
|
288
|
+
return data
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: python-metmalaysia
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Asynchronous Python client for MET Malaysia API and data.gov.my weather services
|
|
5
|
+
Author: Zubir Jamal
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/zubirjamal/python-metmalaysia
|
|
8
|
+
Project-URL: Repository, https://github.com/zubirjamal/python-metmalaysia
|
|
9
|
+
Project-URL: Issues, https://github.com/zubirjamal/python-metmalaysia/issues
|
|
10
|
+
Keywords: metmalaysia,weather,malaysia,datagovmy,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
|
+
Requires-Dist: aresponses>=3.0.0; extra == "test"
|
|
27
|
+
|
|
28
|
+
# python-metmalaysia
|
|
29
|
+
|
|
30
|
+
Asynchronous Python client for MET Malaysia (Malaysian Meteorological Department) API and data.gov.my open weather services.
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install python-metmalaysia
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Features
|
|
39
|
+
- Complete client for official MET Malaysia API (`api.met.gov.my/v2.1`)
|
|
40
|
+
- Client for `data.gov.my` weather forecasts, weather warnings, and earthquake alerts
|
|
41
|
+
- Rate-limiting, caching, and robust datetime/spatial parsing helpers
|
|
42
|
+
- Built for asynchronous use with `aiohttp` and Home Assistant
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
metmalaysia/__init__.py,sha256=rCeAGk6HsqpHxxJcJn88nmh-lNmSMgslWCna9Vxl3ZY,1230
|
|
2
|
+
metmalaysia/client.py,sha256=4F_UuQC163yEDMBCmZV6J8_1h_aEuaHC3jkFzX14ZDU,11317
|
|
3
|
+
metmalaysia/const.py,sha256=L3l5srn9PT-erE3PiHSWEkx6pi7QSekyaPDHyorNk9o,1134
|
|
4
|
+
metmalaysia/exceptions.py,sha256=csjleVdzOpxrSOsT8ep83ceMU_a4hIY0u5YW42jojuU,445
|
|
5
|
+
metmalaysia/models.py,sha256=W4h2L4PKLumkXafk4pW0jiPSIqkrekqj2_-qR-IrLaA,10576
|
|
6
|
+
python_metmalaysia-0.1.0.dist-info/METADATA,sha256=HNTVVgj_tX_2r_4dHXnrkGIikawuNBMNxcE9KMABow8,1704
|
|
7
|
+
python_metmalaysia-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
python_metmalaysia-0.1.0.dist-info/top_level.txt,sha256=lJKnBRc-fEjn4RDnaN_7bTHjkljix12cqygx5HvY05M,12
|
|
9
|
+
python_metmalaysia-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
metmalaysia
|