feat: 워치 스킨 가운데를 날씨 따라 비구름·천둥 구름·눈구름으로 — 초단기예보 낙뢰(LGT)로 2시간 안 천둥을 워치에 알림
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a74e3b49d0
commit
c0e0363759
10 files changed
+236
-37
No files matched your search
@@ -9,6 +9,7 @@ class WatchNow(WebPacketProtocol):
|
||||
temp_c: Optional[float] = None
|
||||
icon: Optional[str] = None
|
||||
rain_2h: Optional[bool] = None
|
||||
thunder: Optional[bool] = None # 2시간 안에 낙뢰 예보
|
||||
text: Optional[str] = None
|
||||
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ async def get_watch_summary(
|
||||
for s in today.slots if s.at > now
|
||||
]
|
||||
if now_w is not None:
|
||||
res.now = (res.now or WatchNow()).model_copy(update={"rain_2h": now_w.will_rain_2h, "text": now_w.rain_2h_text})
|
||||
res.now = (res.now or WatchNow()).model_copy(update={"rain_2h": now_w.will_rain_2h, "thunder": now_w.thunder_2h, "text": now_w.rain_2h_text})
|
||||
res.warning = now_w.warnings[0].text if now_w.warnings else None
|
||||
|
||||
if board is not None:
|
||||
|
||||
Vendored
+2
-2
@@ -79,13 +79,13 @@ def day_start_base(day: date) -> datetime:
|
||||
|
||||
|
||||
def parse_ultra(items: list[dict]) -> list[dict]:
|
||||
"""초단기예보 6시간: 시각별 비 형태·1시간 강수량·기온."""
|
||||
"""초단기예보 6시간: 시각별 비 형태·1시간 강수량·기온·낙뢰(LGT, 0 이면 없음)."""
|
||||
by_time: dict[datetime, dict[str, str]] = {}
|
||||
for it in items:
|
||||
at = datetime.strptime(it["fcstDate"] + it["fcstTime"], "%Y%m%d%H%M").replace(tzinfo=KST)
|
||||
by_time.setdefault(at, {})[it["category"]] = it["fcstValue"]
|
||||
return [
|
||||
{"at": at, "rain_type": _PTY[v["PTY"]], "rain_mm": parse_amount(v.get("RN1", "")), "temp_c": float(v["T1H"])}
|
||||
{"at": at, "rain_type": _PTY[v["PTY"]], "rain_mm": parse_amount(v.get("RN1", "")), "temp_c": float(v["T1H"]), "lightning": parse_amount(v.get("LGT", "")) > 0}
|
||||
for at, v in sorted(by_time.items())
|
||||
if "PTY" in v and "T1H" in v
|
||||
]
|
||||
|
||||
@@ -33,6 +33,7 @@ class RainHour:
|
||||
at: datetime
|
||||
rain_type: RainType
|
||||
rain_mm: float
|
||||
lightning: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -56,6 +57,7 @@ class NowWeather:
|
||||
air: Optional[AirQuality]
|
||||
air_text: Optional[str]
|
||||
warnings: Optional[list[WarningItem]] = field(default=None)
|
||||
thunder_2h: bool = False
|
||||
|
||||
|
||||
def _weather_word(rain: RainType, sky: Sky, rain_mm: float) -> tuple[str, str]:
|
||||
@@ -139,6 +141,7 @@ class NowService:
|
||||
return ErrorType.SUCCESS, NowWeather(
|
||||
region=region, will_rain_2h=will_rain, rain_2h_text=rain_text, rain_hours=hours,
|
||||
tomorrow_text=tomorrow_text, tomorrow_rain_from=rain_from, commute=commute, air=air, air_text=air_text, warnings=warnings,
|
||||
thunder_2h=any(h.lightning for h in hours),
|
||||
)
|
||||
|
||||
async def _ultra(self, region: Region, now: datetime) -> Optional[list[RainHour]]:
|
||||
@@ -155,7 +158,10 @@ async def _cached_ultra(key: str, base: datetime) -> Optional[list[RainHour]]:
|
||||
data = orjson.loads(cached)
|
||||
if data["base"] != base.isoformat():
|
||||
return None
|
||||
return [RainHour(at=datetime.fromisoformat(h["at"]), rain_type=RainType(h["rain_type"]), rain_mm=h["rain_mm"]) for h in data["hours"]]
|
||||
return [
|
||||
RainHour(at=datetime.fromisoformat(h["at"]), rain_type=RainType(h["rain_type"]), rain_mm=h["rain_mm"], lightning=h.get("lightning", False))
|
||||
for h in data["hours"]
|
||||
]
|
||||
|
||||
|
||||
async def ultra_hours(region: Region, now: datetime, wait: bool = False) -> Optional[list[RainHour]]:
|
||||
@@ -173,9 +179,9 @@ async def ultra_hours(region: Region, now: datetime, wait: bool = False) -> Opti
|
||||
continue
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
parsed = parse_ultra(await fetch_ultra(client, region.nx, region.ny, base))
|
||||
hours = [RainHour(at=p["at"], rain_type=p["rain_type"], rain_mm=p["rain_mm"]) for p in parsed]
|
||||
hours = [RainHour(at=p["at"], rain_type=p["rain_type"], rain_mm=p["rain_mm"], lightning=p["lightning"]) for p in parsed]
|
||||
ttl = int((base + timedelta(hours=1, minutes=15) - now).total_seconds())
|
||||
payload = {"base": base.isoformat(), "hours": [{"at": h.at.isoformat(), "rain_type": h.rain_type.value, "rain_mm": h.rain_mm} for h in hours]}
|
||||
payload = {"base": base.isoformat(), "hours": [{"at": h.at.isoformat(), "rain_type": h.rain_type.value, "rain_mm": h.rain_mm, "lightning": h.lightning} for h in hours]}
|
||||
await REDIS.conn.set(key, orjson.dumps(payload), ex=max(ttl, 60))
|
||||
return hours
|
||||
return None
|
||||
|
||||
@@ -18,7 +18,7 @@ def test_parse_ultra_reads_rain_and_temp():
|
||||
{"category": c, "fcstDate": "20261002", "fcstTime": "1000", "fcstValue": v}
|
||||
for c, v in [("PTY", "1"), ("RN1", "1mm 미만"), ("T1H", "17")]
|
||||
]
|
||||
assert parse_ultra(items) == [{"at": _kst(2, 10), "rain_type": RainType.RAIN, "rain_mm": 0.5, "temp_c": 17.0}]
|
||||
assert parse_ultra(items) == [{"at": _kst(2, 10), "rain_type": RainType.RAIN, "rain_mm": 0.5, "temp_c": 17.0, "lightning": False}]
|
||||
|
||||
|
||||
def _event(area, var, cmd, tm, seq=1, stress=0):
|
||||
@@ -82,3 +82,13 @@ def test_parse_ultra_reads_drizzle_codes():
|
||||
for c, v in [("PTY", pty), ("RN1", "1mm 미만"), ("T1H", "17")]
|
||||
]
|
||||
assert [p["rain_type"] for p in parse_ultra(items)] == [RainType.RAIN, RainType.SLEET, RainType.SNOW]
|
||||
|
||||
|
||||
def test_parse_ultra_reads_lightning():
|
||||
"""LGT 는 낙뢰(kA). 0 이면 없음, 칸이 없어도 없음."""
|
||||
items = [
|
||||
{"fcstDate": "20261013", "fcstTime": f"{h:02d}00", "category": c, "fcstValue": v}
|
||||
for h, lgt in ((10, "0"), (11, "3"), (12, None))
|
||||
for c, v in [("PTY", "1"), ("RN1", "5.0mm"), ("T1H", "17"), ("LGT", lgt)] if v is not None
|
||||
]
|
||||
assert [p["lightning"] for p in parse_ultra(items)] == [False, True, False]
|
||||
@@ -4,7 +4,9 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
import services.now_service as now_service
|
||||
import services.week_service as week_service
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.utils.kma_time import KST, now_kst
|
||||
from router.router import app
|
||||
from router.v1.watch.watch import timeline
|
||||
@@ -83,3 +85,18 @@ async def test_watch_summary_unknown_region_fails(offline):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/watch/summary", params={"region": "0000000000"})).json()
|
||||
assert body["result"]["success"] is False
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_watch_summary_flags_thunder_within_2_hours(offline, monkeypatch):
|
||||
start = now_kst().replace(minute=0, second=0, microsecond=0)
|
||||
items = [
|
||||
{"category": c, "fcstDate": (start + timedelta(hours=h)).strftime("%Y%m%d"), "fcstTime": (start + timedelta(hours=h)).strftime("%H%M"), "fcstValue": v}
|
||||
for h in range(1, 7) for c, v in [("PTY", "1"), ("RN1", "5.0mm"), ("T1H", "20"), ("LGT", "2" if h == 1 else "0")]
|
||||
]
|
||||
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(items))
|
||||
# 앞 테스트가 받아 둔 초단기예보 캐시(비 없음)를 지워야 새 예보를 읽는다
|
||||
await REDIS.conn.delete(f"ultra:{REGION}", f"lock:ultra:{REGION}")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/watch/summary", params={"region": REGION})).json()
|
||||
assert body["now"]["rain_2h"] is True and body["now"]["thunder"] is True
|
||||
Reference in new issue
Block a user