diff --git a/backend/router/v1/watch/protocol.py b/backend/router/v1/watch/protocol.py index b957944..4c4d551 100644 --- a/backend/router/v1/watch/protocol.py +++ b/backend/router/v1/watch/protocol.py @@ -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 diff --git a/backend/router/v1/watch/watch.py b/backend/router/v1/watch/watch.py index b2dc72e..d66c17e 100644 --- a/backend/router/v1/watch/watch.py +++ b/backend/router/v1/watch/watch.py @@ -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: diff --git a/backend/services/external/kma.py b/backend/services/external/kma.py index 52de55a..d933c52 100644 --- a/backend/services/external/kma.py +++ b/backend/services/external/kma.py @@ -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 ] diff --git a/backend/services/now_service.py b/backend/services/now_service.py index 47dbec6..93d4e52 100644 --- a/backend/services/now_service.py +++ b/backend/services/now_service.py @@ -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 diff --git a/backend/tests/test_now_parse.py b/backend/tests/test_now_parse.py index 4264b2f..09e8d4d 100644 --- a/backend/tests/test_now_parse.py +++ b/backend/tests/test_now_parse.py @@ -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] diff --git a/backend/tests/test_watch.py b/backend/tests/test_watch.py index 9c9ab0a..73a379c 100644 --- a/backend/tests/test_watch.py +++ b/backend/tests/test_watch.py @@ -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 diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/RainComplicationService.kt b/watch/app/src/main/java/kr/o2o/nalssigak/RainComplicationService.kt index 0dba4f0..8eec0f3 100644 --- a/watch/app/src/main/java/kr/o2o/nalssigak/RainComplicationService.kt +++ b/watch/app/src/main/java/kr/o2o/nalssigak/RainComplicationService.kt @@ -10,7 +10,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlin.math.roundToInt -/** 워치 스킨 아래 칩: 글자 = 지금 기온, 제목 = 비 소식. 스킨은 제목("비 와요"·"곧 비"·"눈 와요")을 보고 빗줄기·눈송이도 그린다. */ +/** 워치 스킨 아래 칩: 글자 = 지금 기온, 제목 = 비 소식. 스킨은 제목("비 와요"·"곧 비"·"천둥 쳐요"·"눈 와요")을 보고 빗줄기·눈송이와 가운데 구름도 그린다. */ class RainComplicationService : SuspendingComplicationDataSourceService() { override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData? { diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt b/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt index cf82459..de85967 100644 --- a/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt +++ b/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt @@ -40,6 +40,8 @@ data class Summary( val nowIcon: String?, val rainText: String?, val rain2h: Boolean?, + /** 2시간 안에 낙뢰 예보 */ + val thunder: Boolean?, val warning: String?, val top: List, val picks: List, @@ -51,16 +53,17 @@ data class Summary( /** 컴플리케이션·타일에 올릴 각: 내 각 첫 번째, 없으면 오늘 1위 */ val myGak: Gak? get() = picks.firstOrNull() ?: top.firstOrNull() - /** 비·눈 화면: "rain" | "snow" | null. 지금 칸이 눈이면 눈, 지금 칸이 비거나 2시간 안에 비 소식이면 비 */ + /** 비·눈: "rain" | "snow" | null. 지금 칸이 눈이면 눈, 지금 칸이 비거나 2시간 안에 비 소식이면 비 */ val precip: String? get() = when { nowIcon == "snow" -> "snow" nowIcon == "rain" || rain2h == true -> "rain" else -> null } - /** 스킨 칩의 비 소식. 비·눈 화면과 어긋나지 않게 precip 을 따른다 */ + /** 스킨 칩의 비 소식. 스킨은 이 글자를 보고 가운데를 비구름·천둥 구름·눈구름으로 바꾼다 */ val rainLabel: String get() = when { precip == "snow" -> "눈 와요" + thunder == true -> "천둥 쳐요" nowIcon == "rain" -> "비 와요" precip == "rain" -> "곧 비" rain2h == false -> "비 없음" @@ -95,6 +98,7 @@ fun parseSummary(json: String): Summary { nowIcon = now?.str("icon"), rainText = now?.str("text"), rain2h = now?.takeIf { it.has("rain_2h") }?.getBoolean("rain_2h"), + thunder = now?.takeIf { it.has("thunder") }?.getBoolean("thunder"), warning = o.str("warning"), top = o.list("top", ::gak), picks = o.list("picks", ::gak), @@ -117,9 +121,9 @@ object SummaryRepo { /** 캐시가 refresh_at 전이면 캐시, 아니면 새로 받는다. 받기 실패하면 지난 캐시라도. 네트워크를 쓰니 메인 스레드에서 부르지 않는다. */ fun load(context: Context, force: Boolean = false): Summary? = fetch(context, force)?.let { s -> - // 디버그 빌드 확인용: shared_prefs/debug.xml 의 precip(rain|snow)로 비·눈 화면을 강제로 띄운다 + // 디버그 빌드 확인용: shared_prefs/debug.xml 의 precip(rain|snow|thunder)로 스킨의 비·눈·천둥을 강제로 띄운다 val forced = if (BuildConfig.DEBUG) context.getSharedPreferences("debug", Context.MODE_PRIVATE).getString("precip", null) else null - if (forced == null) s else s.copy(nowIcon = forced, rain2h = forced == "rain") + if (forced == null) s else s.copy(nowIcon = if (forced == "thunder") "rain" else forced, rain2h = forced != "snow", thunder = forced == "thunder") } private fun fetch(context: Context, force: Boolean): Summary? { diff --git a/watch/watchface/gen_watchface.py b/watch/watchface/gen_watchface.py index c7f6bb9..7b3e7b9 100644 --- a/watch/watchface/gen_watchface.py +++ b/watch/watchface/gen_watchface.py @@ -77,6 +77,33 @@ def sun_rays(): ''' +# 비·눈·천둥 때 해 대신 가운데 구름: 몸통, 아래 그늘. 점수가 흰 글씨라 눈구름도 너무 밝지 않게 +CLOUD_ORB = {"rain": ("#FF8796B0", "#4D394A66"), "thunder": ("#FF5F6684", "#66232A45"), "snow": ("#FF9FB2D3", "#40394A66")} + +def cloud_orb(kind): + """해 구슬 자리에 몽실한 구름 하나 (봉우리 셋 + 둥근 바닥). 천둥이면 오른쪽 아래로 번개, 5초에 한 번 화면이 번쩍""" + body, shade = CLOUD_ORB[kind] + k = ORB / 136 + puffs = [(10, 34, 60), (36, 8, 80), (80, 44, 52)] + shapes = "".join(f'' for x, y, d in puffs) + shapes += f'' + shapes += f'' + shapes += f'' + out = f'{AMB0}{shapes}' + if kind == "thunder": + bolt = [(26, 2), (12, 28), (28, 28), (14, 54)] + lines = "".join(f'' for a, b in zip(bolt, bolt[1:])) + out += f'{AMB0}{lines}' + out += (f'{AMB0}' + f'') + return out + +NIGHT_EXPR = "[HOUR_0_23] < 5 || [HOUR_0_23] >= 21" + +def sun_or_moon(): + """맑을 때(또는 앱 값이 아직 없을 때) 가운데: 밤엔 달빛 구슬, 낮엔 햇살 두른 해""" + return f'{orb_fill(MOON)}{sun_rays()}{orb_fill(SUN)}' + def mode_block(colors, pos, ink, night=False): parts = [sky(colors, pos)] if night: @@ -156,7 +183,8 @@ def chip(x, w, icon, expr): def precip_slot(): """화면 전체를 덮는 숨은 칸. 날씨각 앱(RainComplicationService)이 글자 = 기온, 제목 = 비 소식을 주면 - 아래에 기온·비 칩을 그리고, 비 소식이 "비 와요"·"곧 비"면 빗줄기, "눈 와요"면 눈송이를 그린다. + 아래에 기온·비 칩을 그리고, 비 소식이 "비 와요"·"곧 비"면 빗줄기와 비구름, "천둥 쳐요"면 빗줄기와 번개 구름, + "눈 와요"면 눈송이와 눈구름을 가운데 해 자리에 그린다. 날씨 값은 이 칸 안에서만 읽혀서 맑을 때 해·달 구슬도 여기서 그린다. 터치는 막지 않게 BoundingOval 을 1px 로 둔다. 주기는 60 의 약수여야 분이 바뀔 때 튀지 않는다.""" import random r = random.Random(7) @@ -185,22 +213,37 @@ def precip_slot(): + + + + {shade("#80394766")} + {"".join(drops)} + {cloud_orb("thunder")} + {shade("#66485A78")} {"".join(drops)} + {cloud_orb("rain")} {shade("#40A0AEC4")} {"".join(flakes)} + {cloud_orb("snow")} + {sun_or_moon()} {chip(108, 104, "thermo", "[COMPLICATION.TEXT]")} {chip(220, 122, "umbrella", "[COMPLICATION.TITLE]")} - + + + + {sun_or_moon()} + + ''' def event_slot(): @@ -230,7 +273,7 @@ exprs = "\n ".join(f'\n {mode_block(v[1], v[2], v[3])}\n ' for k, v in MODES.items()) xml = f''' - @@ -247,13 +290,8 @@ xml = f''' + {precip_slot()} - - - = 21]]> - {orb_fill(MOON)} - {sun_rays()}{orb_fill(SUN)} - {clock("#FFFFFFFF", ambient_visible=True)} {orb_slot()} {"".join(ring_slot(i, a) for i, a in enumerate(ANGLES))} diff --git a/watch/watchface/src/main/res/raw/watchface.xml b/watch/watchface/src/main/res/raw/watchface.xml index acc11d3..a0bc3c4 100644 --- a/watch/watchface/src/main/res/raw/watchface.xml +++ b/watch/watchface/src/main/res/raw/watchface.xml @@ -1,5 +1,5 @@ - @@ -147,15 +147,125 @@ + + + = 21]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -261,6 +371,7 @@ + @@ -369,7 +480,20 @@ + + + + + + + + + + + + + @@ -388,17 +512,14 @@ - - - - - = 21]]> - + + + = 21]]> + - - + @@ -406,7 +527,9 @@ - + + + @@ -444,7 +567,7 @@ - + @@ -471,7 +594,7 @@ - + @@ -498,7 +621,7 @@ - + @@ -525,7 +648,7 @@ - + @@ -552,7 +675,7 @@ - + @@ -579,7 +702,7 @@ - +