Merge remote-tracking branch 'origin/main' into feat/share-image
This commit is contained in:
commit
794e70e419
15 files changed
+290
-77
No files matched your search
@@ -21,3 +21,5 @@ backend/openapi.json
|
||||
|
||||
# 디자인 도구(impeccable) 캐시
|
||||
.impeccable/
|
||||
|
||||
/zzz
|
||||
@@ -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점(정보 없음)이다.
|
||||
|
||||
@@ -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] = []
|
||||
@@ -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
|
||||
@@ -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":
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -140,6 +140,20 @@
|
||||
<meta-data android:name="android.support.wearable.complications.UPDATE_PERIOD_SECONDS" android:value="1800" />
|
||||
</service>
|
||||
|
||||
<!-- 워치 스킨 아래 축제 한 줄 -->
|
||||
<service
|
||||
android:name=".EventComplicationService"
|
||||
android:exported="true"
|
||||
android:icon="@drawable/ic_gak"
|
||||
android:label="날씨각 근처 축제"
|
||||
android:permission="com.google.android.wearable.permission.BIND_COMPLICATION_PROVIDER">
|
||||
<intent-filter>
|
||||
<action android:name="android.support.wearable.complications.ACTION_COMPLICATION_UPDATE_REQUEST" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.support.wearable.complications.SUPPORTED_TYPES" android:value="LONG_TEXT" />
|
||||
<meta-data android:name="android.support.wearable.complications.UPDATE_PERIOD_SECONDS" android:value="1800" />
|
||||
</service>
|
||||
|
||||
<service
|
||||
android:name=".GakTileService"
|
||||
android:exported="true"
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package kr.o2o.nalssigak
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.Intent
|
||||
import androidx.wear.watchface.complications.data.ComplicationData
|
||||
import androidx.wear.watchface.complications.data.ComplicationType
|
||||
import androidx.wear.watchface.complications.data.LongTextComplicationData
|
||||
import androidx.wear.watchface.complications.data.NoDataComplicationData
|
||||
import androidx.wear.watchface.complications.data.PlainComplicationText
|
||||
import androidx.wear.watchface.complications.datasource.ComplicationRequest
|
||||
import androidx.wear.watchface.complications.datasource.SuspendingComplicationDataSourceService
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** 워치 스킨 아래 축제 한 줄: 글자 = 이름, 제목 = 상태("진행 중"·"D-3"). 서버가 진행 중인 행사를 앞에 둔다. 누르면 앱이 열린다. */
|
||||
class EventComplicationService : SuspendingComplicationDataSourceService() {
|
||||
|
||||
override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData? {
|
||||
val s = withContext(Dispatchers.IO) { SummaryRepo.load(this@EventComplicationService) } ?: return null
|
||||
// 행사가 끝나 목록이 비면 지난 줄이 남지 않게 "데이터 없음"으로 (공급원은 EMPTY 를 보낼 수 없다)
|
||||
val e = s.events.firstOrNull() ?: return NoDataComplicationData()
|
||||
return data(e.name, e.status)
|
||||
}
|
||||
|
||||
override fun getPreviewData(type: ComplicationType): ComplicationData = data("불꽃축제", "진행 중")
|
||||
|
||||
private fun data(name: String, status: String): ComplicationData {
|
||||
val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE)
|
||||
return LongTextComplicationData.Builder(PlainComplicationText.Builder(name).build(), PlainComplicationText.Builder("$name $status").build())
|
||||
.setTitle(PlainComplicationText.Builder(status).build()).setTapAction(open).build()
|
||||
}
|
||||
}
|
||||
@@ -50,7 +50,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private enum class Page { DETAIL, SKY, TOP, PICKS, SUNSET, HOURS }
|
||||
private enum class Page { DETAIL, SKY, TOP, PICKS, EVENTS, SUNSET, HOURS }
|
||||
|
||||
@Composable
|
||||
private fun App(s: Summary?, loading: Boolean, opened: String?, onRetry: () -> 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)
|
||||
}
|
||||
|
||||
@@ -335,6 +335,30 @@ private fun GakRow(g: Gak, medal: String?, open: Boolean, modifier: Modifier, on
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun EventsPage(events: List<Event>, 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%)
|
||||
|
||||
@@ -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<Slot>,
|
||||
val timeline: List<Phase>,
|
||||
val events: List<Event>,
|
||||
) {
|
||||
/** 컴플리케이션·타일에 올릴 각: 내 각 첫 번째, 없으면 오늘 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
|
||||
|
||||
@@ -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'''<ComplicationSlot slotId="0" x="{x}" y="{y}" width="{ORB}" height="{ORB}" displayName="slot_rank1" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="{APP}/{APP}.Rank1ComplicationService" primaryProviderType="RANGED_VALUE"/>
|
||||
<BoundingOval x="0" y="0" width="{ORB}" height="{ORB}"/>
|
||||
@@ -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'''<PartDraw x="{x}" y="364" width="{w}" height="40">{AMB0}
|
||||
return f'''<PartDraw x="{x}" y="{CHIP_Y}" width="{w}" height="40">{AMB0}
|
||||
<RoundRectangle x="0" y="0" width="{w}" height="40" cornerRadiusX="20" cornerRadiusY="20"><Fill color="{CARD}"/></RoundRectangle>
|
||||
<RoundRectangle x="0" y="35" width="{w}" height="5" cornerRadiusX="2" cornerRadiusY="2"><Fill color="#E6D9E5F4"/></RoundRectangle>
|
||||
</PartDraw>
|
||||
<PartImage x="{x + 8}" y="370" width="26" height="26">{AMB0}<Image resource="e_{icon}"/></PartImage>
|
||||
{text(x + 32, 369, w - 38, 30, "jua", 21, INK, expr, amb=True)}'''
|
||||
<PartImage x="{x + 8}" y="{CHIP_Y + 6}" width="26" height="26">{AMB0}<Image resource="e_{icon}"/></PartImage>
|
||||
{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():
|
||||
<Complication type="EMPTY"/>
|
||||
</ComplicationSlot>'''
|
||||
|
||||
def event_slot():
|
||||
"""날짜 밑 축제 한 줄. 날씨각 앱(EventComplicationService)이 글자 = 이름, 제목 = 상태를 준다. 행사가 없으면 빈 칸이라 안 그린다.
|
||||
무엇인지 바로 알게 "주변 축제" 를 앞에 두고 긴 이름만 말줄임"""
|
||||
x, y, w, h = 123, 124, 204, 30
|
||||
return f'''<ComplicationSlot slotId="8" x="{x}" y="{y}" width="{w}" height="{h}" displayName="slot_event" supportedTypes="LONG_TEXT EMPTY" isCustomizable="FALSE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="{APP}/{APP}.EventComplicationService" primaryProviderType="LONG_TEXT"/>
|
||||
<BoundingOval x="0" y="0" width="{w}" height="{h}"/>
|
||||
<Complication type="LONG_TEXT">
|
||||
<PartDraw x="0" y="0" width="{w}" height="{h}">{AMB0}
|
||||
<RoundRectangle x="0" y="0" width="{w}" height="{h}" cornerRadiusX="{h // 2}" cornerRadiusY="{h // 2}"><Fill color="{CARD}"/></RoundRectangle>
|
||||
</PartDraw>
|
||||
<PartText x="8" y="2" width="{w - 16}" height="{h - 4}">{AMB0}
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="17" color="{INK}"><Template><![CDATA[🎉 주변 축제 · %s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
|
||||
</PartText>
|
||||
</Complication>
|
||||
<Complication type="EMPTY"/>
|
||||
</ComplicationSlot>'''
|
||||
|
||||
def date_line(ink):
|
||||
return f'''<PartText x="0" y="92" width="{W}" height="30">{AMB0}
|
||||
<Text align="CENTER"><Font family="jua" size="23" color="{ink}"><Template><![CDATA[%d월 %d일 %s요일]]><Parameter expression="[MONTH]"/><Parameter expression="[DAY]"/><Parameter expression="{WEEKDAY}"/></Template></Font></Text>
|
||||
@@ -210,7 +230,7 @@ exprs = "\n ".join(f'<Expression name="{k}"><![CDATA[{v[0].replace(">
|
||||
compares = "\n ".join(f'<Compare expression="{k}">\n {mode_block(v[1], v[2], v[3])}\n </Compare>' for k, v in MODES.items())
|
||||
|
||||
xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- 날씨각 워치 스킨: 시간대 하늘, 해 구슬(1위), 둘레 링(2~7위), 아래 기온·비 칩. 링을 누르면 앱이 그 각 상세로 열린다. 점수는 날씨각 앱의 RankNComplicationService 가 공급한다.
|
||||
<!-- 날씨각 워치 스킨: 시간대 하늘, 해 구슬(1위), 둘레 링(2~7위), 날짜 밑 근처 축제 한 줄, 아래 기온·비 칩. 링을 누르면 앱이 그 각 상세로 열린다. 점수는 날씨각 앱의 RankNComplicationService 가 공급한다.
|
||||
직접 고치지 말고 watch/watchface/gen_watchface.py 를 고친 뒤 다시 만든다: python3 gen_watchface.py src/main/res/raw/watchface.xml -->
|
||||
<WatchFace width="{W}" height="{W}">
|
||||
<Metadata key="CLOCK_TYPE" value="DIGITAL"/>
|
||||
@@ -237,6 +257,7 @@ xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
{clock("#FFFFFFFF", ambient_visible=True)}
|
||||
{orb_slot()}
|
||||
{"".join(ring_slot(i, a) for i, a in enumerate(ANGLES))}
|
||||
{event_slot()}
|
||||
</Scene>
|
||||
</WatchFace>
|
||||
'''
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- 날씨각 워치 스킨: 시간대 하늘, 해 구슬(1위), 둘레 링(2~7위), 아래 기온·비 칩. 링을 누르면 앱이 그 각 상세로 열린다. 점수는 날씨각 앱의 RankNComplicationService 가 공급한다.
|
||||
<!-- 날씨각 워치 스킨: 시간대 하늘, 해 구슬(1위), 둘레 링(2~7위), 날짜 밑 근처 축제 한 줄, 아래 기온·비 칩. 링을 누르면 앱이 그 각 상세로 열린다. 점수는 날씨각 앱의 RankNComplicationService 가 공급한다.
|
||||
직접 고치지 말고 watch/watchface/gen_watchface.py 를 고친 뒤 다시 만든다: python3 gen_watchface.py src/main/res/raw/watchface.xml -->
|
||||
<WatchFace width="450" height="450">
|
||||
<Metadata key="CLOCK_TYPE" value="DIGITAL"/>
|
||||
@@ -371,20 +371,20 @@
|
||||
</PartDraw>
|
||||
</Compare>
|
||||
</Condition>
|
||||
<PartDraw x="108" y="364" width="104" height="40"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<PartDraw x="108" y="366" width="104" height="40"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<RoundRectangle x="0" y="0" width="104" height="40" cornerRadiusX="20" cornerRadiusY="20"><Fill color="#B8FFFFFF"/></RoundRectangle>
|
||||
<RoundRectangle x="0" y="35" width="104" height="5" cornerRadiusX="2" cornerRadiusY="2"><Fill color="#E6D9E5F4"/></RoundRectangle>
|
||||
</PartDraw>
|
||||
<PartImage x="116" y="370" width="26" height="26"><Variant mode="AMBIENT" target="alpha" value="0"/><Image resource="e_thermo"/></PartImage>
|
||||
<PartText x="140" y="369" width="66" height="30"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<PartImage x="116" y="372" width="26" height="26"><Variant mode="AMBIENT" target="alpha" value="0"/><Image resource="e_thermo"/></PartImage>
|
||||
<PartText x="140" y="371" width="66" height="30"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="21" color="#FF28304A"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
|
||||
</PartText>
|
||||
<PartDraw x="220" y="364" width="122" height="40"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<PartDraw x="220" y="366" width="122" height="40"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<RoundRectangle x="0" y="0" width="122" height="40" cornerRadiusX="20" cornerRadiusY="20"><Fill color="#B8FFFFFF"/></RoundRectangle>
|
||||
<RoundRectangle x="0" y="35" width="122" height="5" cornerRadiusX="2" cornerRadiusY="2"><Fill color="#E6D9E5F4"/></RoundRectangle>
|
||||
</PartDraw>
|
||||
<PartImage x="228" y="370" width="26" height="26"><Variant mode="AMBIENT" target="alpha" value="0"/><Image resource="e_umbrella"/></PartImage>
|
||||
<PartText x="252" y="369" width="84" height="30"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<PartImage x="228" y="372" width="26" height="26"><Variant mode="AMBIENT" target="alpha" value="0"/><Image resource="e_umbrella"/></PartImage>
|
||||
<PartText x="252" y="371" width="84" height="30"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="21" color="#FF28304A"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TITLE]"/></Template></Font></Text>
|
||||
</PartText>
|
||||
</Complication>
|
||||
@@ -393,18 +393,18 @@
|
||||
<!-- 해 구슬은 비 막 위에 (밤엔 달빛) -->
|
||||
<Condition>
|
||||
<Expressions><Expression name="night"><![CDATA[[HOUR_0_23] < 5 || [HOUR_0_23] >= 21]]></Expression></Expressions>
|
||||
<Compare expression="night"><PartDraw x="144" y="154" width="162" height="162"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<Ellipse x="0" y="0" width="162" height="162"><Fill color="#FFFF8E4E"><RadialGradient centerX="55" centerY="48" radius="155" colors="#FFFFFFFF #FFD9D3FF #FFA99FEA #FF7F75CC" positions="0 0.3 0.68 1"/></Fill></Ellipse>
|
||||
<Ellipse x="0" y="0" width="162" height="162"><Fill color="#00000000"><LinearGradient startX="72" startY="72" endX="162" endY="162" colors="#00AA3214 #57AA3214" positions="0 1"/></Fill></Ellipse>
|
||||
<Compare expression="night"><PartDraw x="157" y="184" width="136" height="136"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<Ellipse x="0" y="0" width="136" height="136"><Fill color="#FFFF8E4E"><RadialGradient centerX="46" centerY="40" radius="130" colors="#FFFFFFFF #FFD9D3FF #FFA99FEA #FF7F75CC" positions="0 0.3 0.68 1"/></Fill></Ellipse>
|
||||
<Ellipse x="0" y="0" width="136" height="136"><Fill color="#00000000"><LinearGradient startX="61" startY="61" endX="136" endY="136" colors="#00AA3214 #57AA3214" positions="0 1"/></Fill></Ellipse>
|
||||
|
||||
</PartDraw></Compare>
|
||||
<Default><PartDraw x="113" y="123" width="225" height="225"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<Line startX="202.5" startY="112.5" endX="216.4" endY="112.5"><Stroke thickness="9.9" color="#FFFFB347" cap="ROUND"/></Line><Line startX="190.4" startY="157.5" endX="202.5" endY="164.5"><Stroke thickness="9.9" color="#FFFFB347" cap="ROUND"/></Line><Line startX="157.5" startY="190.4" endX="164.5" endY="202.5"><Stroke thickness="9.9" color="#FFFFB347" cap="ROUND"/></Line><Line startX="112.5" startY="202.5" endX="112.5" endY="216.4"><Stroke thickness="9.9" color="#FFFFB347" cap="ROUND"/></Line><Line startX="67.5" startY="190.4" endX="60.5" endY="202.5"><Stroke thickness="9.9" color="#FFFFB347" cap="ROUND"/></Line><Line startX="34.6" startY="157.5" endX="22.5" endY="164.5"><Stroke thickness="9.9" color="#FFFFB347" cap="ROUND"/></Line><Line startX="22.5" startY="112.5" endX="8.5" endY="112.5"><Stroke thickness="9.9" color="#FFFFB347" cap="ROUND"/></Line><Line startX="34.6" startY="67.5" endX="22.5" endY="60.5"><Stroke thickness="9.9" color="#FFFFB347" cap="ROUND"/></Line><Line startX="67.5" startY="34.6" endX="60.5" endY="22.5"><Stroke thickness="9.9" color="#FFFFB347" cap="ROUND"/></Line><Line startX="112.5" startY="22.5" endX="112.5" endY="8.5"><Stroke thickness="9.9" color="#FFFFB347" cap="ROUND"/></Line><Line startX="157.5" startY="34.6" endX="164.5" endY="22.5"><Stroke thickness="9.9" color="#FFFFB347" cap="ROUND"/></Line><Line startX="190.4" startY="67.5" endX="202.5" endY="60.5"><Stroke thickness="9.9" color="#FFFFB347" cap="ROUND"/></Line>
|
||||
<Default><PartDraw x="131" y="158" width="188" height="188"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<Line startX="169.2" startY="94.0" endX="180.9" endY="94.0"><Stroke thickness="8.3" color="#FFFFB347" cap="ROUND"/></Line><Line startX="159.1" startY="131.6" endX="169.2" endY="137.4"><Stroke thickness="8.3" color="#FFFFB347" cap="ROUND"/></Line><Line startX="131.6" startY="159.1" endX="137.4" endY="169.2"><Stroke thickness="8.3" color="#FFFFB347" cap="ROUND"/></Line><Line startX="94.0" startY="169.2" endX="94.0" endY="180.9"><Stroke thickness="8.3" color="#FFFFB347" cap="ROUND"/></Line><Line startX="56.4" startY="159.1" endX="50.6" endY="169.2"><Stroke thickness="8.3" color="#FFFFB347" cap="ROUND"/></Line><Line startX="28.9" startY="131.6" endX="18.8" endY="137.4"><Stroke thickness="8.3" color="#FFFFB347" cap="ROUND"/></Line><Line startX="18.8" startY="94.0" endX="7.1" endY="94.0"><Stroke thickness="8.3" color="#FFFFB347" cap="ROUND"/></Line><Line startX="28.9" startY="56.4" endX="18.8" endY="50.6"><Stroke thickness="8.3" color="#FFFFB347" cap="ROUND"/></Line><Line startX="56.4" startY="28.9" endX="50.6" endY="18.8"><Stroke thickness="8.3" color="#FFFFB347" cap="ROUND"/></Line><Line startX="94.0" startY="18.8" endX="94.0" endY="7.1"><Stroke thickness="8.3" color="#FFFFB347" cap="ROUND"/></Line><Line startX="131.6" startY="28.9" endX="137.4" endY="18.8"><Stroke thickness="8.3" color="#FFFFB347" cap="ROUND"/></Line><Line startX="159.1" startY="56.4" endX="169.2" endY="50.6"><Stroke thickness="8.3" color="#FFFFB347" cap="ROUND"/></Line>
|
||||
<Transform target="angle" value="360 * fract([SECOND_MILLISECOND] / 60)"/>
|
||||
</PartDraw><PartDraw x="144" y="154" width="162" height="162"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<Ellipse x="0" y="0" width="162" height="162"><Fill color="#FFFF8E4E"><RadialGradient centerX="55" centerY="48" radius="155" colors="#FFFFF5CF #FFFFC86E #FFFF8E4E #FFEE6436" positions="0 0.3 0.68 1"/></Fill></Ellipse>
|
||||
<Ellipse x="0" y="0" width="162" height="162"><Fill color="#00000000"><LinearGradient startX="72" startY="72" endX="162" endY="162" colors="#00AA3214 #57AA3214" positions="0 1"/></Fill></Ellipse>
|
||||
<Ellipse x="19" y="100" width="25" height="14"><Fill color="#73FF7A8A"/></Ellipse><Ellipse x="116" y="100" width="25" height="14"><Fill color="#73FF7A8A"/></Ellipse>
|
||||
</PartDraw><PartDraw x="157" y="184" width="136" height="136"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<Ellipse x="0" y="0" width="136" height="136"><Fill color="#FFFF8E4E"><RadialGradient centerX="46" centerY="40" radius="130" colors="#FFFFF5CF #FFFFC86E #FFFF8E4E #FFEE6436" positions="0 0.3 0.68 1"/></Fill></Ellipse>
|
||||
<Ellipse x="0" y="0" width="136" height="136"><Fill color="#00000000"><LinearGradient startX="61" startY="61" endX="136" endY="136" colors="#00AA3214 #57AA3214" positions="0 1"/></Fill></Ellipse>
|
||||
<Ellipse x="16" y="84" width="21" height="12"><Fill color="#73FF7A8A"/></Ellipse><Ellipse x="97" y="84" width="21" height="12"><Fill color="#73FF7A8A"/></Ellipse>
|
||||
</PartDraw></Default>
|
||||
</Condition>
|
||||
<DigitalClock x="0" y="18" width="450" height="84">
|
||||
@@ -412,26 +412,26 @@
|
||||
<Font family="bagel_fat_one" size="68" color="#FFFFFFFF"/>
|
||||
</TimeText>
|
||||
</DigitalClock>
|
||||
<ComplicationSlot slotId="0" x="144" y="154" width="162" height="162" displayName="slot_rank1" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
<ComplicationSlot slotId="0" x="157" y="184" width="136" height="136" displayName="slot_rank1" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.Rank1ComplicationService" primaryProviderType="RANGED_VALUE"/>
|
||||
<BoundingOval x="0" y="0" width="162" height="162"/>
|
||||
<BoundingOval x="0" y="0" width="136" height="136"/>
|
||||
<Complication type="RANGED_VALUE">
|
||||
<PartText x="0" y="30" width="162" height="74">
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="bagel_fat_one" size="58" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
|
||||
</PartText><PartText x="14" y="100" width="134" height="30">
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="21" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TITLE]"/></Template></Font></Text>
|
||||
<PartText x="0" y="25" width="136" height="61">
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="bagel_fat_one" size="50" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
|
||||
</PartText><PartText x="14" y="84" width="108" height="28">
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="19" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TITLE]"/></Template></Font></Text>
|
||||
</PartText>
|
||||
</Complication>
|
||||
<Complication type="SHORT_TEXT">
|
||||
<PartText x="0" y="30" width="162" height="74">
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="bagel_fat_one" size="58" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
|
||||
</PartText><PartText x="14" y="100" width="134" height="30">
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="21" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TITLE]"/></Template></Font></Text>
|
||||
<PartText x="0" y="25" width="136" height="61">
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="bagel_fat_one" size="50" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
|
||||
</PartText><PartText x="14" y="84" width="108" height="28">
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="19" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TITLE]"/></Template></Font></Text>
|
||||
</PartText>
|
||||
</Complication>
|
||||
<Complication type="EMPTY"/>
|
||||
</ComplicationSlot>
|
||||
<ComplicationSlot slotId="1" x="62" y="127" width="68" height="68" displayName="slot_ring" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
<ComplicationSlot slotId="1" x="71" y="149" width="68" height="68" displayName="slot_ring" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.Rank2ComplicationService" primaryProviderType="RANGED_VALUE"/>
|
||||
<BoundingOval x="0" y="0" width="68" height="68"/>
|
||||
<Complication type="RANGED_VALUE">
|
||||
@@ -458,7 +458,7 @@
|
||||
</PartText>
|
||||
</Complication>
|
||||
<Complication type="EMPTY"/>
|
||||
</ComplicationSlot><ComplicationSlot slotId="2" x="319" y="126" width="68" height="68" displayName="slot_ring" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
</ComplicationSlot><ComplicationSlot slotId="2" x="310" y="148" width="68" height="68" displayName="slot_ring" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.Rank3ComplicationService" primaryProviderType="RANGED_VALUE"/>
|
||||
<BoundingOval x="0" y="0" width="68" height="68"/>
|
||||
<Complication type="RANGED_VALUE">
|
||||
@@ -485,7 +485,7 @@
|
||||
</PartText>
|
||||
</Complication>
|
||||
<Complication type="EMPTY"/>
|
||||
</ComplicationSlot><ComplicationSlot slotId="3" x="62" y="275" width="68" height="68" displayName="slot_ring" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
</ComplicationSlot><ComplicationSlot slotId="3" x="71" y="287" width="68" height="68" displayName="slot_ring" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.Rank4ComplicationService" primaryProviderType="RANGED_VALUE"/>
|
||||
<BoundingOval x="0" y="0" width="68" height="68"/>
|
||||
<Complication type="RANGED_VALUE">
|
||||
@@ -512,7 +512,7 @@
|
||||
</PartText>
|
||||
</Complication>
|
||||
<Complication type="EMPTY"/>
|
||||
</ComplicationSlot><ComplicationSlot slotId="4" x="319" y="275" width="68" height="68" displayName="slot_ring" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
</ComplicationSlot><ComplicationSlot slotId="4" x="310" y="287" width="68" height="68" displayName="slot_ring" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.Rank5ComplicationService" primaryProviderType="RANGED_VALUE"/>
|
||||
<BoundingOval x="0" y="0" width="68" height="68"/>
|
||||
<Complication type="RANGED_VALUE">
|
||||
@@ -539,7 +539,7 @@
|
||||
</PartText>
|
||||
</Complication>
|
||||
<Complication type="EMPTY"/>
|
||||
</ComplicationSlot><ComplicationSlot slotId="5" x="43" y="201" width="68" height="68" displayName="slot_ring" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
</ComplicationSlot><ComplicationSlot slotId="5" x="53" y="218" width="68" height="68" displayName="slot_ring" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.Rank6ComplicationService" primaryProviderType="RANGED_VALUE"/>
|
||||
<BoundingOval x="0" y="0" width="68" height="68"/>
|
||||
<Complication type="RANGED_VALUE">
|
||||
@@ -566,7 +566,7 @@
|
||||
</PartText>
|
||||
</Complication>
|
||||
<Complication type="EMPTY"/>
|
||||
</ComplicationSlot><ComplicationSlot slotId="6" x="339" y="201" width="68" height="68" displayName="slot_ring" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
</ComplicationSlot><ComplicationSlot slotId="6" x="329" y="218" width="68" height="68" displayName="slot_ring" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.Rank7ComplicationService" primaryProviderType="RANGED_VALUE"/>
|
||||
<BoundingOval x="0" y="0" width="68" height="68"/>
|
||||
<Complication type="RANGED_VALUE">
|
||||
@@ -594,5 +594,18 @@
|
||||
</Complication>
|
||||
<Complication type="EMPTY"/>
|
||||
</ComplicationSlot>
|
||||
<ComplicationSlot slotId="8" x="123" y="124" width="204" height="30" displayName="slot_event" supportedTypes="LONG_TEXT EMPTY" isCustomizable="FALSE">
|
||||
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.EventComplicationService" primaryProviderType="LONG_TEXT"/>
|
||||
<BoundingOval x="0" y="0" width="204" height="30"/>
|
||||
<Complication type="LONG_TEXT">
|
||||
<PartDraw x="0" y="0" width="204" height="30"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<RoundRectangle x="0" y="0" width="204" height="30" cornerRadiusX="15" cornerRadiusY="15"><Fill color="#B8FFFFFF"/></RoundRectangle>
|
||||
</PartDraw>
|
||||
<PartText x="8" y="2" width="188" height="26"><Variant mode="AMBIENT" target="alpha" value="0"/>
|
||||
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="17" color="#FF28304A"><Template><![CDATA[🎉 주변 축제 · %s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
|
||||
</PartText>
|
||||
</Complication>
|
||||
<Complication type="EMPTY"/>
|
||||
</ComplicationSlot>
|
||||
</Scene>
|
||||
</WatchFace>
|
||||
Reference in new issue
Block a user