diff --git a/.gitignore b/.gitignore
index 7392bc9..7f38461 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,3 +21,5 @@ backend/openapi.json
# 디자인 도구(impeccable) 캐시
.impeccable/
+
+/zzz
\ No newline at end of file
diff --git a/backend/docs/openmeteo-data.md b/backend/docs/openmeteo-data.md
index 6d8fecc..637e61d 100644
--- a/backend/docs/openmeteo-data.md
+++ b/backend/docs/openmeteo-data.md
@@ -118,10 +118,12 @@ light = 1 - min(low100 + 0.5×mid100, 100) / 100
| 축 | 값 (지수 계산 창 안에서) | 점수 규칙 (기본값, 지수별로 시드 JSON에서 바꿈) | 칼럼 |
|---|---|---|---|
-| `uv` 자외선 | `uv_index` **최대** | 2 이하 100점, 8 이상 0점, 사이는 선형 | `weight_uv`, `uv_score` |
-| `sun` 햇빛 | 해 난 비율(`sunshine_s ÷ 10,800`)의 **평균** | 80% 이상 100점, 20% 이하 0점, 사이는 선형 | `weight_sun`, `sun_score` |
-| `view` 가시거리 | `visibility_m` **최소**(km) | 20km 이상 100점, 5km 이하 0점, 사이는 선형 | `weight_view`, `view_score` |
+| `uv` 자외선 | `uv_index` **최대** | 2 이하 100점, 8 이상 0점, 사이는 완만한 곡선 | `weight_uv`, `uv_score` |
+| `sun` 햇빛 | 해 난 비율(`sunshine_s ÷ 10,800`)의 **평균** | 80% 이상 100점, 20% 이하 0점, 사이는 완만한 곡선 | `weight_sun`, `sun_score` |
+| `view` 가시거리 | `visibility_m` **최소**(km) | 20km 이상 100점, 5km 이하 0점, 사이는 완만한 곡선 | `weight_view`, `view_score` |
+- 완만한 곡선: 만점 구간 끝에서 0점 지점까지를 정규분포 곡선(σ = 그 거리) 모양으로 내려간다 (`index_calc._fall`). 가운데 지점이 50점이 아니라 70점이라 만점 근처는 천천히, 0점 근처는 빨리 내려간다. 모든 축(기온·비·바람·습도·미세먼지 포함)에 같은 곡선을 쓰고, 만점 기준·0점 지점·0점 조건은 그대로다.
+- 기온·습도 편한 범위(`range`): 최적값(`best`, 없으면 범위 가운데) ±2°(습도 ±5%p)는 100점, 범위 끝은 85점, 사이는 완만한 곡선. 100점 구간은 최적값~범위 끝 거리의 1/3을 넘지 않는다 (`index_calc._range`). 100점은 완벽에 가까운 조건에만 준다는 10/2 회의 결정을 따른 것이다.
- 값이 없으면(수집 전, 구간 없음) 미세먼지처럼 **70점(정보 없음)**.
- 비중이 0인 지수에서는 점수에 영향이 없고, 상세 API(`/v1/index/{id}`)에도 나오지 않는다. 기존 6개 축도 같은 규칙으로, 비중이 0이면 나오지 않는다.
- 중기예보로 내는 예상 점수(`estimate`)에서는 값이 없으므로 비중이 있으면 70점(정보 없음)이다.
diff --git a/backend/router/v1/watch/protocol.py b/backend/router/v1/watch/protocol.py
index 9a7fac7..b957944 100644
--- a/backend/router/v1/watch/protocol.py
+++ b/backend/router/v1/watch/protocol.py
@@ -27,6 +27,13 @@ class WatchSlot(WebPacketProtocol):
rain_prob: Optional[int] = None
+class WatchEvent(WebPacketProtocol):
+ name: str
+ place_name: str
+ status_label: str
+ fit: Optional[str] = None
+
+
class WatchTimeline(WebPacketProtocol):
start_at: datetime
kind: Literal["gak", "sunset"]
@@ -45,3 +52,4 @@ class Res_WatchSummary(Res_WebPacketProtocol):
sunset: Optional[WatchSunset] = None
slots: list[WatchSlot] = []
timeline: list[WatchTimeline] = []
+ events: list[WatchEvent] = []
diff --git a/backend/router/v1/watch/watch.py b/backend/router/v1/watch/watch.py
index 757d34f..ff82612 100644
--- a/backend/router/v1/watch/watch.py
+++ b/backend/router/v1/watch/watch.py
@@ -1,4 +1,5 @@
import asyncio
+import re
from datetime import datetime, timedelta
from typing import Optional
@@ -6,9 +7,10 @@ from fastapi import APIRouter, Depends, Query
from common.database.model.models import SkyScore
from common.enums import ErrorType, SkyGrade
+from common.logger import LOG
from common.models.errors import error_info
from common.utils.kma_time import KST, now_kst
-from router.v1.watch.protocol import Res_WatchSummary, WatchNow, WatchSlot, WatchSunset, WatchTimeline
+from router.v1.watch.protocol import Res_WatchSummary, WatchEvent, WatchNow, WatchSlot, WatchSunset, WatchTimeline
from services.calc.sky_score import GRADE_LABEL
from services.calc.sun import sun_times
from services.feed_service import _SUNSET_FULL, _top, feed_ttl_sec, slot_of
@@ -16,18 +18,32 @@ from services.index_service import IndexService
from services.now_service import NowService
from services.sky_service import SkyService
from services.weather_service import WeatherService
+from services.week_service import EventItem, WeekService
router = APIRouter(prefix="/v1/watch", tags=["watch"])
MAX_PICKS = 3
# 워치 스킨이 큰 원(1위) + 둘레 링 6개(2~7위)를 채운다
TOP_N = 7
+MAX_EVENTS = 2
+# 워치 readTimeout(10초) 안에 끝나도록. 첫 조회라 TourAPI 를 부르다 늦으면 이번 요약엔 축제를 빼고, 캐시는 다음 조회가 채운다
+EVENTS_TIMEOUT_SEC = 4
+# "[하트하트아트앤컬처] 마음의 각도" 처럼 이름 앞 주최·분류 괄호. 워치 칸이 좁아 뺀다
+_NAME_PREFIX = re.compile(r"^(\[[^\]]*\]\s*)+")
def _best(score: SkyScore, kind: str) -> datetime:
return datetime.fromisoformat(next(b["at"] for b in score.best_times if b["kind"] == kind)).astimezone(KST)
+async def _events(week: WeekService, region: str) -> tuple[ErrorType, list[EventItem]]:
+ try:
+ return await asyncio.wait_for(week.events(region, None), EVENTS_TIMEOUT_SEC)
+ except TimeoutError:
+ LOG.warning(f"[watch] events {region}: {EVENTS_TIMEOUT_SEC}초 넘어 생략")
+ return ErrorType.EXTERNAL_API_ERROR, []
+
+
def timeline(now: datetime, sunset: Optional[SkyScore], is_today: bool) -> list[WatchTimeline]:
"""컴플리케이션이 언제 무엇을 보여줄지. 오늘 노을이 볼 만하면(60점 이상) 일몰 2시간 전부터 보랏빛 하늘까지 노을, 나머지는 각."""
if sunset is None or not is_today or sunset.score < _SUNSET_FULL:
@@ -47,9 +63,10 @@ async def get_watch_summary(
now_service: NowService = Depends(),
sky: SkyService = Depends(),
index: IndexService = Depends(),
+ week: WeekService = Depends(),
) -> Res_WatchSummary:
- (err_t, today), (err_n, now_w), (err_s, view), (err_i, board) = await asyncio.gather(
- weather.today(region), now_service.now(region), sky.view(region), index.board(region),
+ (err_t, today), (err_n, now_w), (err_s, view), (err_i, board), (err_e, events) = await asyncio.gather(
+ weather.today(region), now_service.now(region), sky.view(region), index.board(region), _events(week, region),
)
today = today if err_t is ErrorType.SUCCESS else None
now_w = now_w if err_n is ErrorType.SUCCESS else None
@@ -95,4 +112,11 @@ async def get_watch_summary(
sunset_at=_best(target, "sun"), best_at=_best(target, "peak"),
)
res.timeline = timeline(now, target, is_today)
+ # 축제를 못 가져와도 요약은 그대로 낸다 (err_e 면 빈 목록)
+ if err_e is ErrorType.SUCCESS:
+ res.events = [
+ WatchEvent(name=_NAME_PREFIX.sub("", i.event.name) or i.event.name, place_name=i.event.place_name, status_label=i.status_label, fit=i.fit)
+ # 진행 중인 행사를 먼저 (스킨은 첫 번째 하나만 보여 준다). 같은 상태 안에서는 서버 순서(가까운 날짜·거리) 그대로
+ for i in sorted(events, key=lambda i: i.status != "live")[:MAX_EVENTS]
+ ]
return res
diff --git a/backend/services/calc/index_calc.py b/backend/services/calc/index_calc.py
index 2938758..1ca37d8 100644
--- a/backend/services/calc/index_calc.py
+++ b/backend/services/calc/index_calc.py
@@ -1,7 +1,7 @@
from collections import Counter
from dataclasses import dataclass, field
from datetime import date
-from math import cos, pi
+from math import cos, exp, pi
from statistics import mean
from typing import Optional
@@ -14,6 +14,10 @@ _WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
_UNKNOWN = 70
_EDGE = 85
_WORST_PULL = 0.25
+_FALL_FLOOR = exp(-0.5)
+# 편한 범위 안에서 최적값 ±이만큼은 100점 (기온 °, 습도 %p)
+_TEMP_PLATEAU = 2
+_HUMIDITY_PLATEAU = 5
@dataclass(frozen=True)
@@ -70,17 +74,33 @@ def _clamp(v: float) -> int:
return round(max(0.0, min(100.0, v)))
+def _fall(t: float) -> float:
+ """만점 구간 끝(t=0)에서 0점 지점(t=1)까지 1→0. 정규분포 곡선(σ = 그 거리) 모양이라 만점 근처는 천천히 내려간다."""
+ if t <= 0:
+ return 1.0
+ if t >= 1:
+ return 0.0
+ return (exp(-t * t / 2) - _FALL_FLOOR) / (1 - _FALL_FLOOR)
+
+
def _linear(v: float, zero: float, full: float) -> int:
- return _clamp((v - zero) / (full - zero) * 100)
+ """full 쪽은 100, zero 에서 0. 사이는 _fall 곡선."""
+ return _clamp(100 * _fall((v - full) / (zero - full)))
-def _peak(v: float, lo: float, hi: float, best: Optional[float], per_out: float) -> int:
- """최적값에서만 100. 편한 범위 끝은 _EDGE, 범위 밖은 한 단위마다 per_out 씩 깎는다."""
- best = (lo + hi) / 2 if best is None else best
+def _range(v: float, lo: float, hi: float, best: Optional[float], plateau: float, per_out: float) -> int:
+ """편한 범위 안: 최적값 ±plateau 는 100, 범위 끝으로 갈수록 _EDGE 까지 _fall 곡선으로 내려간다.
+ 100점 구간은 최적값~범위 끝 거리의 1/3 을 넘지 않아 범위가 좁아도 끝에서 뚝 떨어지지 않는다.
+ 범위 밖: _EDGE 에서 예전 직선(한 단위마다 per_out)이 0이 되던 거리까지 _fall 곡선으로 0."""
if v < lo or v > hi:
- return _clamp(_EDGE - per_out * min(abs(v - lo), abs(v - hi)))
- side = (best - lo) if v < best else (hi - best)
- return _clamp(100 - (100 - _EDGE) * (abs(v - best) / side if side else 0))
+ return _clamp(_EDGE * _fall(min(abs(v - lo), abs(v - hi)) * per_out / _EDGE))
+ best = (lo + hi) / 2 if best is None else best
+ side = abs((lo if v < best else hi) - best)
+ flat = min(plateau, side / 3)
+ off = abs(v - best) - flat
+ if off <= 0:
+ return 100
+ return _clamp(_EDGE + (100 - _EDGE) * _fall(off / (side - flat)))
def temp_score(rule: dict, feels: float) -> tuple[int, str]:
@@ -88,7 +108,7 @@ def temp_score(rule: dict, feels: float) -> tuple[int, str]:
shown = f"산 정상 기준 {round(t)}°" if rule.get("offset") else f"체감 {round(t)}°"
if rule["type"] == "range":
lo, hi = rule["lo"], rule["hi"]
- return _peak(t, lo, hi, rule.get("best"), 8), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if lo <= t <= hi else '밖'}"
+ return _range(t, lo, hi, rule.get("best"), _TEMP_PLATEAU, 8), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if lo <= t <= hi else '밖'}"
if rule["type"] == "away":
lo, hi = rule["lo"], rule["hi"]
dist = 0 if lo <= t <= hi else min(abs(t - lo), abs(t - hi))
@@ -99,8 +119,8 @@ def temp_score(rule: dict, feels: float) -> tuple[int, str]:
def rain_score(rule: dict, max_prob: int, raining: bool, until: str = "") -> tuple[int, str]:
prob = f"{until} 비 확률 {max_prob}%" if until else f"비 확률 {max_prob}%"
if rule["dir"] == "wet":
- return (100 if raining else _clamp(max_prob)), (f"비 소식, {prob}" if raining else f"{prob}, 비 오면 올라가요")
- return (0 if raining else _clamp(100 - max_prob)), (f"비 소식, {prob}" if raining else prob)
+ return (100 if raining else _linear(max_prob, 0, 100)), (f"비 소식, {prob}" if raining else f"{prob}, 비 오면 올라가요")
+ return (0 if raining else _linear(max_prob, 100, 0)), (f"비 소식, {prob}" if raining else prob)
def wind_score(rule: dict, wind: Optional[float]) -> tuple[int, str]:
@@ -115,7 +135,7 @@ def wind_score(rule: dict, wind: Optional[float]) -> tuple[int, str]:
return 100, note
if wind <= ok:
return _clamp(100 - (100 - _EDGE) * (wind - ok / 2) / (ok / 2)), note
- return _clamp(_EDGE * (rule["limit"] - wind) / (rule["limit"] - ok)), note
+ return _clamp(_EDGE * _fall((wind - ok) / (rule["limit"] - ok))), note
if rule["type"] == "moderate":
if 2 <= wind <= 5:
return 100, note
@@ -126,7 +146,7 @@ def wind_score(rule: dict, wind: Optional[float]) -> tuple[int, str]:
def humidity_score(rule: dict, humidity: float) -> tuple[int, str]:
note = f"습도 {round(humidity)}%"
if rule["type"] == "range":
- return _peak(humidity, rule["lo"], rule["hi"], rule.get("best"), 2), note
+ return _range(humidity, rule["lo"], rule["hi"], rule.get("best"), _HUMIDITY_PLATEAU, 2), note
if rule["type"] == "higher":
return _linear(humidity, 40, 90), note
if rule["type"] == "lower":
diff --git a/backend/tests/test_index_calc.py b/backend/tests/test_index_calc.py
index c94590e..0800a43 100644
--- a/backend/tests/test_index_calc.py
+++ b/backend/tests/test_index_calc.py
@@ -39,15 +39,17 @@ def test_good_but_not_perfect_stays_below_100():
def test_one_bad_factor_pulls_total_down():
- assert evaluate(_defn(), [[_h(19, wind=1.0, prob=60)]], CTX).score < 80
+ assert evaluate(_defn(), [[_h(19, wind=1.0, prob=75)]], CTX).score < 75
-def test_temp_peaks_at_best_and_loses_8_per_degree_outside():
- assert temp_score({"type": "range", "lo": 18, "hi": 24}, 21)[0] == 100
- assert temp_score({"type": "range", "lo": 18, "hi": 24}, 24)[0] == 85
+def test_temp_is_full_near_best_and_falls_gently_to_zero_outside():
+ rule = {"type": "range", "lo": 14, "hi": 28} # 최적 21 ±2 = 19~23 은 100
+ assert [temp_score(rule, t)[0] for t in (19, 21, 23)] == [100, 100, 100]
+ assert 85 < temp_score(rule, 25)[0] < 100 and temp_score(rule, 28)[0] == 85 # 범위 끝으로 갈수록 85까지
assert temp_score({"type": "range", "lo": 18, "hi": 24, "best": 22}, 22)[0] == 100
- assert temp_score({"type": "range", "lo": 18, "hi": 24}, 15)[0] == 61
- assert temp_score({"type": "lower", "zero": 25, "full": 5}, 15)[0] == 50
+ assert temp_score({"type": "range", "lo": 18, "hi": 24}, 15)[0] == 77 # 범위 밖 3°
+ assert temp_score({"type": "range", "lo": 18, "hi": 24}, 18 - 85 / 8)[0] == 0 # 예전 직선이 0이 되던 거리에서 0
+ assert temp_score({"type": "lower", "zero": 25, "full": 5}, 15)[0] == 70
assert temp_score({"type": "range", "lo": 10, "hi": 20, "offset": -6}, 21)[1].startswith("산 정상 기준 15°")
@@ -59,7 +61,8 @@ def test_temp_away_rises_outside_comfort():
def test_rain_dry_and_wet():
- assert rain_score({"dir": "dry"}, 30, False)[0] == 70
+ assert rain_score({"dir": "dry"}, 30, False)[0] == 89
+ assert rain_score({"dir": "dry"}, 100, False)[0] == 0
assert rain_score({"dir": "dry"}, 30, True)[0] == 0
assert rain_score({"dir": "wet"}, 30, True)[0] == 100
@@ -111,10 +114,10 @@ def test_moon_full_and_new():
assert illumination(datetime(2000, 1, 21, 12, tzinfo=timezone.utc)) > 0.95
-def test_uv_sun_view_scores_are_linear_and_unknown_is_70():
- assert uv_score({"zero": 8, "full": 2}, 1)[0] == 100 and uv_score({"zero": 8, "full": 2}, 5)[0] == 50 and uv_score({"zero": 8, "full": 2}, 9)[0] == 0
- assert sun_score({"zero": 0.2, "full": 0.8}, 0.5)[0] == 50 and sun_score({"zero": 0.2, "full": 0.8}, 1.0)[0] == 100
- assert view_score({"zero": 5, "full": 20}, 12.5)[0] == 50 and view_score({"zero": 5, "full": 20}, 3)[0] == 0
+def test_uv_sun_view_scores_fall_gently_and_unknown_is_70():
+ assert uv_score({"zero": 8, "full": 2}, 1)[0] == 100 and uv_score({"zero": 8, "full": 2}, 5)[0] == 70 and uv_score({"zero": 8, "full": 2}, 9)[0] == 0
+ assert sun_score({"zero": 0.2, "full": 0.8}, 0.5)[0] == 70 and sun_score({"zero": 0.2, "full": 0.8}, 1.0)[0] == 100
+ assert view_score({"zero": 5, "full": 20}, 12.5)[0] == 70 and view_score({"zero": 5, "full": 20}, 3)[0] == 0
assert (uv_score({"zero": 8, "full": 2}, None)[0], sun_score({"zero": 0.2, "full": 0.8}, None)[0], view_score({"zero": 5, "full": 20}, None)[0]) == (70, 70, 70)
assert uv_score({"zero": 8, "full": 2}, 5)[1] == "자외선 5.0"
assert view_score({"zero": 5, "full": 20}, 12.5)[1] == "가시거리 12.5km" and view_score({"zero": 5, "full": 20}, None)[1] == "가시거리 정보 없음"
@@ -175,7 +178,7 @@ def test_estimate_is_flagged_and_unknown_factors_are_70():
def test_estimate_uses_rain_prob_of_the_window_half_day():
morning, evening = estimate(_defn(), _fc(am=60, pm=0), [[9, 10]], CTX), estimate(_defn(), _fc(am=60, pm=0), [[19, 20]], CTX)
- assert morning.factors["rain"] == 40 and evening.factors["rain"] == 100
+ assert morning.factors["rain"] == 58 and evening.factors["rain"] == 100
def test_estimate_applies_rain_zero_rule_only():
diff --git a/backend/tests/test_index_slots.py b/backend/tests/test_index_slots.py
index d375039..13207af 100644
--- a/backend/tests/test_index_slots.py
+++ b/backend/tests/test_index_slots.py
@@ -61,7 +61,7 @@ def test_weekend_in_short_range_uses_hourly_score():
def test_weekend_beyond_short_range_uses_mid_forecast_estimate():
r = day_result(DEFN, SAT, REGION, {}, FC, CTX, short=False)
- assert r.estimated is True and r.factors["wind"] == 70 and r.factors["rain"] == 80
+ assert r.estimated is True and r.factors["wind"] == 70 and r.factors["rain"] == 95
def test_partial_hourly_falls_back_to_estimate():
diff --git a/backend/tests/test_watch.py b/backend/tests/test_watch.py
index e22bb28..9c9ab0a 100644
--- a/backend/tests/test_watch.py
+++ b/backend/tests/test_watch.py
@@ -4,7 +4,8 @@ from types import SimpleNamespace
import pytest
from httpx import ASGITransport, AsyncClient
-from common.utils.kma_time import KST
+import services.week_service as week_service
+from common.utils.kma_time import KST, now_kst
from router.router import app
from router.v1.watch.watch import timeline
@@ -12,6 +13,10 @@ REGION = "1141000000"
SUN = datetime(2026, 10, 6, 18, 0, tzinfo=KST)
+async def _async(v):
+ return v
+
+
def _sunset(score: int) -> SimpleNamespace:
return SimpleNamespace(score=score, best_times=[
{"at": SUN.isoformat(), "kind": "sun", "label": "해 져요"},
@@ -42,6 +47,8 @@ def test_timeline_skips_weak_tomorrow_or_finished_sunset():
@pytest.mark.anyio
async def test_watch_summary_bundles_now_top_picks_sunset(offline):
+ # 행사는 스케줄러가 7일마다 모아 둔다. 요청은 DB 만 읽으니 먼저 모아 둔다
+ await week_service.collect_events("11", now_kst().date())
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
body = (await client.get("/v1/watch/summary", params={"region": REGION, "pick": "laundry, nope,running,carwash,bike"})).json()
assert body["result"]["success"] is True
@@ -53,6 +60,22 @@ async def test_watch_summary_bundles_now_top_picks_sunset(offline):
assert body["sunset"]["best_at"] > body["sunset"]["sunset_at"]
assert all(s["at"] > body["issued_at"] for s in body["slots"])
assert body["timeline"][0]["start_at"] == body["issued_at"]
+ assert [(e["name"], e["status_label"]) for e in body["events"]] == [("테스트 축제", "진행 중")]
+
+
+@pytest.mark.anyio
+async def test_watch_summary_puts_live_event_first_without_bracket_prefix(offline, monkeypatch):
+ # 서버 순서는 시작일이 가까운 순이라 내일 시작이 먼저지만, 스킨에 하나만 띄우니 진행 중을 앞으로. 이름 앞 [주최] 는 뺀다
+ today = now_kst().date()
+ day = lambda n: (today + timedelta(days=n)).strftime("%Y%m%d")
+ monkeypatch.setattr(week_service, "fetch_festivals", lambda c, sido, since: _async([
+ {"contentid": "1", "title": "내일 축제", "addr1": "서울", "eventstartdate": day(1), "eventenddate": day(2)},
+ {"contentid": "2", "title": "[주최] 열리는 축제", "addr1": "서울", "eventstartdate": day(-3), "eventenddate": day(2)},
+ ] if sido == "11" else []))
+ await week_service.collect_events("11", today)
+ 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 [e["name"] for e in body["events"]] == ["열리는 축제", "내일 축제"]
@pytest.mark.anyio
diff --git a/watch/app/src/main/AndroidManifest.xml b/watch/app/src/main/AndroidManifest.xml
index 01402e0..ec1e0a5 100644
--- a/watch/app/src/main/AndroidManifest.xml
+++ b/watch/app/src/main/AndroidManifest.xml
@@ -140,6 +140,20 @@
+
+
+
+
+
+
+
+
+
Unit) {
@@ -72,6 +72,7 @@ private fun App(s: Summary?, loading: Boolean, opened: String?, onRetry: () -> U
add(Page.SKY)
if (s.top.isNotEmpty()) add(Page.TOP)
if (s.picks.isNotEmpty()) add(Page.PICKS)
+ if (s.events.isNotEmpty()) add(Page.EVENTS)
if (s.sunset != null) add(Page.SUNSET)
if (s.slots.isNotEmpty()) add(Page.HOURS)
}
@@ -83,6 +84,7 @@ private fun App(s: Summary?, loading: Boolean, opened: String?, onRetry: () -> U
Page.SKY -> SkyPage(s, now)
Page.TOP -> GakListPage("오늘의 각", s.top.take(3), bgButter, medals = true, now)
Page.PICKS -> GakListPage("내 각", s.picks, bgMint, medals = false, now)
+ Page.EVENTS -> EventsPage(s.events, now)
Page.SUNSET -> SunsetPage(s.sunset!!, now)
Page.HOURS -> HoursPage(s, now)
}
diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/Screens.kt b/watch/app/src/main/java/kr/o2o/nalssigak/Screens.kt
index ed3bb2a..b00cb24 100644
--- a/watch/app/src/main/java/kr/o2o/nalssigak/Screens.kt
+++ b/watch/app/src/main/java/kr/o2o/nalssigak/Screens.kt
@@ -335,6 +335,30 @@ private fun GakRow(g: Gak, medal: String?, open: Boolean, modifier: Modifier, on
}
}
+@Composable
+fun EventsPage(events: List, now: Instant) {
+ Box(Modifier.fillMaxSize().background(bgButter)) {
+ Clock(now, Tok.ink)
+ Column(
+ Modifier.fillMaxSize().padding(start = 22.dp, end = 22.dp, top = 34.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(6.dp),
+ ) {
+ T("근처 축제", 14.sp, color = Tok.ink)
+ events.forEach { e ->
+ Column(Modifier.fillMaxWidth().mallang().padding(start = 10.dp, end = 10.dp, top = 5.dp, bottom = 8.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ T(e.name, 13.sp, color = Tok.ink, modifier = Modifier.weight(1f), align = TextAlign.Start, maxLines = 1)
+ T(e.status, 9.sp, FontFamily.Default, Color.White, Modifier.padding(start = 4.dp).background(Tok.orange, CircleShape).padding(horizontal = 5.dp),
+ weight = FontWeight.ExtraBold, maxLines = 1)
+ }
+ T(listOfNotNull(e.place.takeIf { it.isNotBlank() }, e.fit).joinToString(" · "), 9.sp, FontFamily.Default, Tok.ink2, align = TextAlign.Start, weight = FontWeight.Bold, maxLines = 1)
+ }
+ }
+ }
+ }
+}
+
// ───────────── 4. 노을 ─────────────
// 웹 .b-skyline::after 의 건물 윤곽 (x%, y%)
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 1b61961..cf82459 100644
--- a/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt
+++ b/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt
@@ -4,8 +4,11 @@ import android.Manifest
import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager
+import android.location.Location
import android.location.LocationManager
+import android.os.CancellationSignal
import android.util.Log
+import androidx.annotation.RequiresPermission
import androidx.wear.tiles.TileService
import androidx.wear.watchface.complications.datasource.ComplicationDataSourceUpdateRequester
import org.json.JSONArray
@@ -17,11 +20,15 @@ import java.time.Instant
import java.time.OffsetDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
data class Gak(val code: String, val name: String, val icon: String, val score: Int, val rank: Int, val summary: String?)
data class Sunset(val isToday: Boolean, val score: Int, val grade: String, val sunsetAt: Instant, val bestAt: Instant)
data class Slot(val at: Instant, val icon: String, val tempC: Double?, val rainProb: Int?)
data class Phase(val startAt: Instant, val kind: String)
+/** 근처 축제·행사. status 는 "진행 중", "이번 토요일", "D-12" */
+data class Event(val name: String, val place: String, val status: String, val fit: String?)
data class Summary(
val regionName: String,
@@ -39,6 +46,7 @@ data class Summary(
val sunset: Sunset?,
val slots: List,
val timeline: List,
+ val events: List,
) {
/** 컴플리케이션·타일에 올릴 각: 내 각 첫 번째, 없으면 오늘 1위 */
val myGak: Gak? get() = picks.firstOrNull() ?: top.firstOrNull()
@@ -95,6 +103,7 @@ fun parseSummary(json: String): Summary {
},
slots = o.list("slots") { Slot(time(it.getString("at")), it.getString("icon"), it.dbl("temp_c"), it.int("rain_prob")) },
timeline = o.list("timeline") { Phase(time(it.getString("start_at")), it.getString("kind")) },
+ events = o.list("events") { Event(it.getString("name"), it.getString("place_name"), it.getString("status_label"), it.str("fit")) },
)
}
@@ -104,6 +113,7 @@ object SummaryRepo {
private const val PICKS = "running,laundry,walk"
// 위치를 못 얻으면 종로구
private const val DEFAULT_REGION = "1111000000"
+ private const val LOCATION_TIMEOUT_SEC = 5L
/** 캐시가 refresh_at 전이면 캐시, 아니면 새로 받는다. 받기 실패하면 지난 캐시라도. 네트워크를 쓰니 메인 스레드에서 부르지 않는다. */
fun load(context: Context, force: Boolean = false): Summary? = fetch(context, force)?.let { s ->
@@ -117,7 +127,8 @@ object SummaryRepo {
val cached = prefs.getString("json", null)?.let { runCatching { parseSummary(it) }.getOrNull() }
if (!force && cached != null && Instant.now() < cached.refreshAt) return cached
return try {
- val region = prefs.getString("region", null) ?: nearestRegion(context)?.also { prefs.edit().putString("region", it).apply() } ?: DEFAULT_REGION
+ // 받을 때마다 지금 위치의 구를 다시 찾아, 옮겨 가면 날씨·각·축제가 따라온다. 위치를 못 얻으면 지난 구
+ val region = nearestRegion(context)?.also { prefs.edit().putString("region", it).apply() } ?: prefs.getString("region", null) ?: DEFAULT_REGION
val json = get("/v1/watch/summary?region=$region&pick=$PICKS")
val fresh = parseSummary(json)
prefs.edit().putString("json", json).apply()
@@ -134,7 +145,7 @@ object SummaryRepo {
private fun refreshSurfaces(context: Context) {
val sources = listOf(GakComplicationService::class.java, RainComplicationService::class.java, Rank1ComplicationService::class.java,
Rank2ComplicationService::class.java, Rank3ComplicationService::class.java, Rank4ComplicationService::class.java,
- Rank5ComplicationService::class.java, Rank6ComplicationService::class.java, Rank7ComplicationService::class.java)
+ Rank5ComplicationService::class.java, Rank6ComplicationService::class.java, Rank7ComplicationService::class.java, EventComplicationService::class.java)
sources.forEach { ComplicationDataSourceUpdateRequester.create(context, ComponentName(context, it)).requestUpdateAll() }
TileService.getUpdater(context).requestUpdate(GakTileService::class.java)
}
@@ -142,7 +153,8 @@ object SummaryRepo {
private fun nearestRegion(context: Context): String? {
if (context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) return null
val lm = context.getSystemService(LocationManager::class.java)
- val loc = lm.getProviders(true).firstNotNullOfOrNull { lm.getLastKnownLocation(it) } ?: return null
+ // 다른 앱이 위치를 갱신하지 않았으면 마지막 위치가 비어 있어, 먼저 지금 위치를 한 번 묻는다
+ val loc = currentLocation(lm) ?: lm.getProviders(true).firstNotNullOfOrNull { lm.getLastKnownLocation(it) } ?: return null
return try {
JSONObject(get("/v1/region/nearest?lat=${loc.latitude}&lon=${loc.longitude}")).getJSONObject("region").getString("code")
} catch (e: IOException) {
@@ -152,6 +164,19 @@ object SummaryRepo {
}
}
+ /** 지금 위치 한 번. 구 단위면 되니 대략 위치, 5초 안에 못 얻으면 null (백그라운드에선 시스템이 자주 거절한다) */
+ @RequiresPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
+ private fun currentLocation(lm: LocationManager): Location? {
+ val enabled = lm.getProviders(true)
+ val provider = listOf("fused", LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER).firstOrNull { it in enabled } ?: return null
+ val done = CountDownLatch(1)
+ val cancel = CancellationSignal()
+ var loc: Location? = null
+ lm.getCurrentLocation(provider, cancel, { it.run() }) { loc = it; done.countDown() }
+ if (!done.await(LOCATION_TIMEOUT_SEC, TimeUnit.SECONDS)) cancel.cancel()
+ return loc
+ }
+
private fun get(path: String): String {
val conn = URL(BuildConfig.API_BASE + path).openConnection() as HttpURLConnection
conn.connectTimeout = 5000
diff --git a/watch/watchface/gen_watchface.py b/watch/watchface/gen_watchface.py
index 4ca9f18..c7f6bb9 100644
--- a/watch/watchface/gen_watchface.py
+++ b/watch/watchface/gen_watchface.py
@@ -3,9 +3,11 @@ HERE = os.path.dirname(os.path.abspath(__file__))
# 각 이름 → 아이콘. 시계 런타임이 점수 링 안의 작은 이미지를 그려 주지 않아, 이름을 보고 스킨에 넣은 아이콘을 고른다
GAK_ICONS = [(d["name"], d["icon"]) for d in json.load(open(os.path.join(HERE, "../../backend/seed/index_definition.json"), encoding="utf-8"))]
W = 450
-CX, CY = 225, 235
-ORB = 162
-RING, RR = 68, 148
+# 해 구슬을 줄이고 조금 내려, 날짜 밑에 축제 줄 자리를 만든다
+CX, CY = 225, 252
+ORB = 136
+RING, RR = 68, 138
+CHIP_Y = 366
ANGLES = [210, 330, 150, 30, 180, 0]
APP = "kr.o2o.nalssigak"
INK, ORANGE, SHADE, CARD = "#FF28304A", "#FFFF7A45", "#FFD9E5F4", "#B8FFFFFF"
@@ -90,7 +92,7 @@ def text(x, y, w, h, family, size, color, expr, amb=False):
def orb_slot():
x, y = CX - ORB // 2, CY - ORB // 2
- body = text(0, 30, ORB, 74, "bagel_fat_one", 58, "#FFFFFFFF", "[COMPLICATION.TEXT]") + text(14, 100, ORB - 28, 30, "jua", 21, "#FFFFFFFF", "[COMPLICATION.TITLE]")
+ body = text(0, int(ORB * .19), ORB, int(ORB * .45), "bagel_fat_one", 50, "#FFFFFFFF", "[COMPLICATION.TEXT]") + text(14, int(ORB * .62), ORB - 28, 28, "jua", 19, "#FFFFFFFF", "[COMPLICATION.TITLE]")
return f'''
@@ -145,12 +147,12 @@ def ring_slot(i, angle):
WEEKDAY = " : ".join(f'[DAY_OF_WEEK] == {n + 1} ? "{d}"' for n, d in enumerate("일월화수목금")) + " : "토""
def chip(x, w, icon, expr):
- return f'''{AMB0}
+ return f'''{AMB0}
- {AMB0}
- {text(x + 32, 369, w - 38, 30, "jua", 21, INK, expr, amb=True)}'''
+ {AMB0}
+ {text(x + 32, CHIP_Y + 5, w - 38, 30, "jua", 21, INK, expr, amb=True)}'''
def precip_slot():
"""화면 전체를 덮는 숨은 칸. 날씨각 앱(RainComplicationService)이 글자 = 기온, 제목 = 비 소식을 주면
@@ -201,6 +203,24 @@ def precip_slot():
'''
+def event_slot():
+ """날짜 밑 축제 한 줄. 날씨각 앱(EventComplicationService)이 글자 = 이름, 제목 = 상태를 준다. 행사가 없으면 빈 칸이라 안 그린다.
+ 무엇인지 바로 알게 "주변 축제" 를 앞에 두고 긴 이름만 말줄임"""
+ x, y, w, h = 123, 124, 204, 30
+ return f'''
+
+
+
+ {AMB0}
+
+
+ {AMB0}
+
+
+
+
+ '''
+
def date_line(ink):
return f'''{AMB0}
@@ -210,7 +230,7 @@ exprs = "\n ".join(f'\n {mode_block(v[1], v[2], v[3])}\n ' for k, v in MODES.items())
xml = f'''
-
@@ -237,6 +257,7 @@ xml = f'''
{clock("#FFFFFFFF", ambient_visible=True)}
{orb_slot()}
{"".join(ring_slot(i, a) for i, a in enumerate(ANGLES))}
+ {event_slot()}
'''
diff --git a/watch/watchface/src/main/res/raw/watchface.xml b/watch/watchface/src/main/res/raw/watchface.xml
index 45ac98b..acc11d3 100644
--- a/watch/watchface/src/main/res/raw/watchface.xml
+++ b/watch/watchface/src/main/res/raw/watchface.xml
@@ -1,5 +1,5 @@
-
@@ -371,20 +371,20 @@
-
+
-
-
+
+
-
+
-
-
+
+
@@ -393,18 +393,18 @@
= 21]]>
-
-
-
+
+
+
-
-
+
+
-
-
-
-
+
+
+
+
@@ -412,26 +412,26 @@
-
+
-
+
-
-
-
-
+
+
+
+
-
-
-
-
+
+
+
+
-
+
@@ -458,7 +458,7 @@
-
+
@@ -485,7 +485,7 @@
-
+
@@ -512,7 +512,7 @@
-
+
@@ -539,7 +539,7 @@
-
+
@@ -566,7 +566,7 @@
-
+
@@ -594,5 +594,18 @@
+
+
+
+
+
+
+
+
+
+
+
+
+