"""Where the ISS is right now: a dotted world map with day and night, its ground track and the next pass.""" import math from datetime import datetime from functools import lru_cache from pathlib import Path from PIL import Image, ImageDraw import astro import skykit from astro import Pass, direction from poller import Poller from sky_data import CloudHour, Tle, cloud_at from skykit import H, W, hm from view import Patch from weather_data import LAT, LON BG, ACCENT, TEXT, DIM = (3, 8, 7), (120, 236, 206), (232, 240, 236), (110, 140, 130) MARKER, HOME = (255, 255, 255), (255, 110, 100) LAND_DAY, LAND_NIGHT, SEA_DAY, SEA_NIGHT = (70, 168, 120), (26, 66, 50), (16, 32, 28), (8, 15, 13) PAST, AHEAD = (50, 110, 96), ACCENT STALE_BG = (240, 200, 90) CLEAR_SKY, SOME_CLOUD, OVERCAST = (120, 236, 160), (240, 200, 90), (255, 120, 100) # The map leaves out the polar caps (the ISS stays within 51.6° of the equator) to make room for the next pass. LAT_TOP, LAT_BOTTOM = 75, -60 MAP_TOP, MAP_H, DOT = 40, 180, 4 # 4/3 px per degree, the same scale as across PANEL_TOP = MAP_TOP + MAP_H GRID_X = (214, 344) # the two columns of height, direction, brightness and clouds LAND_PATH = Path(__file__).parent / "assets" / "world_land.png" EARTH_KM, GM = 6371.0, 398600.4418 # radius, and the gravitational parameter in km³/s² def map_xy(lat: float, lon: float) -> tuple[float, float]: return (lon + 180) / 360 * W, MAP_TOP + (LAT_TOP - lat) / (LAT_TOP - LAT_BOTTOM) * MAP_H def is_day(lat: float, lon: float, subsolar: tuple[float, float]) -> bool: """Whether the sun is above the horizon at lat/lon, given where it stands overhead.""" sun_lat, sun_lon = (math.radians(v) for v in subsolar) lat, lon = math.radians(lat), math.radians(lon) return math.sin(lat) * math.sin(sun_lat) + math.cos(lat) * math.cos(sun_lat) * math.cos(lon - sun_lon) > 0 @lru_cache(maxsize=1) def _land() -> Image.Image: return Image.open(LAND_PATH).convert("L") def _fmt(value: float) -> str: return f"{abs(value):.1f}".replace(".", ",") def mag_colour(mag: float): """How inviting a pass of this brightness is, as a colour (like the cloud cover).""" # TODO(owner): pick the thresholds, e.g. CLEAR_SKY for a pass worth going out for. return TEXT def pass_cells(p: Pass, clouds: tuple[CloudHour, ...]) -> list[tuple[str, str, tuple]]: """(label, value, colour) for the grid beside the time of the next pass.""" pct = cloud_at(clouds, p.start) if pct is None: cloud = ("--", DIM) else: cloud = (f"{pct} %", OVERCAST if pct >= 60 else SOME_CLOUD if pct >= 25 else CLEAR_SKY) return [ ("VÝŠKA", f"{p.max_alt:.0f}°", TEXT), ("SMĚR", f"{direction(p.az_from)} → {direction(p.az_to)}", TEXT), ("JASNOST", f"{p.mag:.1f} mag".replace("-", "−").replace(".", ","), mag_colour(p.mag)), ("MRAKY", *cloud), ] class IssView: name = "iss" TLE_STALE_AFTER = 3 * 86400.0 FRAME_EVERY_S = 10 # the ISS moves about one pixel of this map in 10 s def __init__(self, tle: Poller[Tle], clouds: Poller[tuple[CloudHour, ...]]) -> None: self._tle = tle self._clouds = clouds def start(self) -> None: self._tle.start() self._clouds.start() def stop(self) -> None: self._tle.stop() self._clouds.stop() def _stale(self) -> bool: age = self._tle.age() return age is not None and age > self.TLE_STALE_AFTER def frame_key(self, now: datetime): tick = now.replace(second=now.second - now.second % self.FRAME_EVERY_S, microsecond=0) return (tick, self._tle.version, self._clouds.version, self._stale()) def patch(self, now: datetime) -> Patch | None: return None def render(self, now: datetime) -> Image.Image: img = Image.new("RGB", (W, H), BG) d = ImageDraw.Draw(img) self._map(d, now) zx, zy = map_xy(LAT, LON) d.ellipse((zx - 3, zy - 3, zx + 3, zy + 3), outline=HOME, width=2) d.text((zx + 6, zy - 4), "Zlín", font=skykit.font(10, 700), fill=HOME, anchor="ls") d.text((14, 28), "ISS", font=skykit.font(22, 800), fill=ACCENT, anchor="ls") tle: Tle | None = self._tle.value if tle is None: d.text((240, MAP_TOP + MAP_H / 2), "Čekám na dráhu ISS…", font=skykit.font(16, 600), fill=TEXT, anchor="mm") return img for minutes, lat, lon in astro.iss_track(tle, now): x, y = map_xy(lat, lon) if minutes < 0: d.point((x, y), fill=PAST) else: d.ellipse((x - 1, y - 1, x + 1, y + 1), fill=AHEAD) fix = astro.iss_fix(tle, now) x, y = map_xy(fix.lat, fix.lon) d.ellipse((x - 7, y - 7, x + 7, y + 7), outline=MARKER, width=2) d.ellipse((x - 2, y - 2, x + 2, y + 2), fill=MARKER) speed = math.sqrt(GM / (EARTH_KM + fix.km)) * 3600 header = f"{fix.km:.0f} km · {speed:,.0f} km/h".replace(",", " ") end = d.textlength(header, font=skykit.font(13, 500)) + 62 d.text((62, 27), header, font=skykit.font(13, 500), fill=DIM, anchor="ls") if self._stale(): skykit.tag(d, (end + 8, 27), "STARÉ", skykit.font(10, 700), STALE_BG, BG) coords = (f"{_fmt(fix.lat)}° {'s' if fix.lat >= 0 else 'j'}. š. " f"{_fmt(fix.lon)}° {'v' if fix.lon >= 0 else 'z'}. d.") d.text((466, 27), coords, font=skykit.font(12, 500), fill=DIM, anchor="rs") self._next_pass(d, tle, now) return img @staticmethod def _map(d: ImageDraw.ImageDraw, now: datetime) -> None: land = _land().load() skip = round((90 - LAT_TOP) / 180 * _land().height) # rows of the whole-world mask above the map sun = astro.subsolar(now) for gy in range(DOT // 2, MAP_H, DOT): lat = LAT_TOP - (gy + 1) / MAP_H * (LAT_TOP - LAT_BOTTOM) for gx in range(DOT // 2, W, DOT): day = is_day(lat, (gx + 1) / W * 360 - 180, sun) if land[gx, gy + skip]: colour = LAND_DAY if day else LAND_NIGHT else: colour = SEA_DAY if day else SEA_NIGHT d.rectangle((gx, MAP_TOP + gy, gx + 1, MAP_TOP + gy + 1), fill=colour) def _next_pass(self, d: ImageDraw.ImageDraw, tle: Tle, now: datetime) -> None: y = PANEL_TOP + 20 skykit.tracked(d, (14, y), "DALŠÍ VIDITELNÝ PŘELET", skykit.font(12, 650), ACCENT) p = astro.next_visible_pass(tle, now) if p is None: d.text((14, y + 40), "v příštích 3 dnech žádný", font=skykit.font(24, 700), fill=TEXT, anchor="ls") return d.text((12, y + 50), hm(p.start), font=skykit.font(48, 800), fill=TEXT, anchor="ls") d.text((14, y + 74), f"{skykit.WEEKDAYS[p.start.weekday()]} {p.start.day}. {p.start.month}.", font=skykit.font(18, 650), fill=TEXT, anchor="ls") for i, (label, value, colour) in enumerate(pass_cells(p, self._clouds.value or ())): x, top = GRID_X[i % 2], y + i // 2 * 48 skykit.tracked(d, (x, top), label, skykit.font(12, 650), DIM) d.text((x, top + 26), value, font=skykit.font(24, 750), fill=colour, anchor="ls")