Sky and ISS views
Two new views, picked from mockups. `sky`: a star chart of the sky over Zlín as seen lying on your back, with the planets, the moon in its phase, tonight's darkness, cloud for the next 12 hours and the next visible ISS pass. `iss`: a dotted world map with day and night, the ISS and its ground track, and the next pass over Zlín with the cloud cover for that hour. Positions are calculated locally with ephem; only the ISS orbit (CelesTrak, every 6 h, retried gently) and cloud cover (Open-Meteo) are fetched. The poller gained a per-source retry delay for that. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
6c9a1420d2
commit
2132262896
28 files changed
+1342
-18
No files matched your search
@@ -2,12 +2,14 @@
|
|||||||
|
|
||||||
A second 3.5" Turing Smart Screen (Rev A) on the Coolify home server, next to the bus board
|
A second 3.5" Turing Smart Screen (Rev A) on the Coolify home server, next to the bus board
|
||||||
(`bus-department-schedule`). One Docker container shows **one view at a time**: a Casio digital watch (slanted
|
(`bus-department-schedule`). One Docker container shows **one view at a time**: a Casio digital watch (slanted
|
||||||
7-segment digits, pale LCD green) for the weather, and a Cyberpunk 2077 look (yellow/cyan on black, chamfered
|
7-segment digits, pale LCD green) for the weather, a Cyberpunk 2077 look (yellow/cyan on black, chamfered
|
||||||
shapes, glitch numbers) for the server stats:
|
shapes, glitch numbers) for the server stats, a star chart of tonight's sky and an ISS tracker:
|
||||||
|
|
||||||
| `VIEW` | Shows |
|
| `VIEW` | Shows |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `weather` | The week ahead in the Czech weekday strip (today first and inverted: icon, max and min for each day), big `HH:MM` with seconds, date, current temperature and feels-like (`POCIT`) for Zlín, and a 12-hour rain probability bar graph with the hour under every bar and the total mm. From sunset to sunrise the whole screen turns into a reverse LCD (light segments on black) |
|
| `weather` | The week ahead in the Czech weekday strip (today first and inverted: icon, max and min for each day), big `HH:MM` with seconds, date, current temperature and feels-like (`POCIT`) for Zlín, and a 12-hour rain probability bar graph with the hour under every bar and the total mm. From sunset to sunrise the whole screen turns into a reverse LCD (light segments on black) |
|
||||||
|
| `sky` | Star chart of the sky over Zlín right now, as seen lying on your back (north up, east left): bright stars, a few constellations, the planets, the Moon in its real phase, and the sun by day. Beside it: the clock, tonight's full darkness, what is up (height and direction) or rising soon, the next 12 hours of cloud with a one-line summary, and the next visible ISS pass. Redrawn every minute |
|
||||||
|
| `iss` | Dotted world map with day and night: where the ISS is now, its ground track 40 minutes back and 95 ahead, Zlín, height, speed and position, and the next pass visible from Zlín with the cloud cover for that hour. Redrawn every 10 s |
|
||||||
| `server` | Cyberpunk style: CPU / RAM / disk gauges (red from 80 %), load, CPU temperature, uptime, Docker containers (readable names and status chips) and the busiest processes. Refreshed every second; the container list every 5 s and the process ranking over 3 s windows |
|
| `server` | Cyberpunk style: CPU / RAM / disk gauges (red from 80 %), load, CPU temperature, uptime, Docker containers (readable names and status chips) and the busiest processes. Refreshed every second; the container list every 5 s and the process ranking over 3 s windows |
|
||||||
|
|
||||||
Design: `docs/superpowers/specs/2026-10-22-second-screen-design.md`.
|
Design: `docs/superpowers/specs/2026-10-22-second-screen-design.md`.
|
||||||
@@ -30,7 +32,7 @@ Edit `VIEW:` in `docker-compose.yml`, commit, `git push`, then in Coolify press
|
|||||||
|
|
||||||
python3 -m venv .venv && .venv/bin/pip install -r requirements-dev.txt
|
python3 -m venv .venv && .venv/bin/pip install -r requirements-dev.txt
|
||||||
.venv/bin/pytest
|
.venv/bin/pytest
|
||||||
.venv/bin/python preview.py # writes docs/previews/weather.png and server.png
|
.venv/bin/python preview.py # writes docs/previews/weather.png, server.png, sky.png and iss.png
|
||||||
|
|
||||||
## Deployment (Coolify)
|
## Deployment (Coolify)
|
||||||
|
|
||||||
@@ -64,14 +66,15 @@ else keeps working.
|
|||||||
(the screen library's own exit is caught); if the port disappears mid-run the app exits after about a minute of
|
(the screen library's own exit is caught); if the port disappears mid-run the app exits after about a minute of
|
||||||
failed draws and Docker restarts it. With the cable out *before* the container starts, Docker itself refuses to
|
failed draws and Docker restarts it. With the cable out *before* the container starts, Docker itself refuses to
|
||||||
start it (the compose `devices:` entry). Check the cable and `ls -l /dev/serial/by-id/`. ModemManager can interfere (`systemctl status ModemManager`).
|
start it (the compose `devices:` entry). Check the cable and `ls -l /dev/serial/by-id/`. ModemManager can interfere (`systemctl status ModemManager`).
|
||||||
- **`STARÉ` tag:** the data is old (weather older than 1 h, server stats older than 30 s). The clock keeps running.
|
- **`STARÉ` tag:** the data is old (weather or clouds older than 1 h, server stats older than 30 s, the ISS orbit
|
||||||
|
older than 3 days). The clock keeps running.
|
||||||
- **Error screen at startup:** `VIEW` is not one of the valid views.
|
- **Error screen at startup:** `VIEW` is not one of the valid views.
|
||||||
|
|
||||||
## Config (env vars)
|
## Config (env vars)
|
||||||
|
|
||||||
| Variable | Default | |
|
| Variable | Default | |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `VIEW` | none (must be set) | `weather` or `server` |
|
| `VIEW` | none (must be set) | `weather`, `server`, `sky` or `iss` |
|
||||||
| `SCREEN_DEVICE` | `/dev/serial/by-id/usb-Turing_UsbMonitor_USB35INCHIPSV2-if00` | serial device, also passed into the container |
|
| `SCREEN_DEVICE` | `/dev/serial/by-id/usb-Turing_UsbMonitor_USB35INCHIPSV2-if00` | serial device, also passed into the container |
|
||||||
| `SCREEN_ORIENTATION` | `LANDSCAPE` | `REVERSE_LANDSCAPE` flips it |
|
| `SCREEN_ORIENTATION` | `LANDSCAPE` | `REVERSE_LANDSCAPE` flips it |
|
||||||
| `SCREEN_BRIGHTNESS` | `50` | 0–100 |
|
| `SCREEN_BRIGHTNESS` | `50` | 0–100 |
|
||||||
@@ -87,6 +90,11 @@ The screen library is pinned to one upstream commit in the `Dockerfile` (`LCD_CO
|
|||||||
days), the closest day's times are used; with no forecast at all (right after a start) the screen stays in day
|
days), the closest day's times are used; with no forecast at all (right after a start) the screen stays in day
|
||||||
mode. Switching day/night redraws the whole screen once (about 2 s).
|
mode. Switching day/night redraws the whole screen once (about 2 s).
|
||||||
- The weather graph is the next 12 hours from now, so late in the day it runs into tomorrow.
|
- The weather graph is the next 12 hours from now, so late in the day it runs into tomorrow.
|
||||||
|
- Sky and ISS: positions of the sun, moon, planets, stars and the ISS are calculated in the container (`ephem`,
|
||||||
|
`astro.py`), nothing is asked of a service. Only the ISS orbit (CelesTrak, every 6 hours, a failed download is
|
||||||
|
retried after 30 minutes because CelesTrak blocks eager clients) and the cloud cover (Open-Meteo, every 15 minutes)
|
||||||
|
come from the network. An ISS pass counts as visible when the station is sunlit while the sun here is more than 6°
|
||||||
|
below the horizon. By day the star chart still shows the stars where they stand.
|
||||||
- Server stats: process CPU is a share of the whole machine and grouped by command name; temperature is the CPU
|
- Server stats: process CPU is a share of the whole machine and grouped by command name; temperature is the CPU
|
||||||
package sensor if the host has one, else the hottest thermal zone.
|
package sensor if the host has one, else the hottest thermal zone.
|
||||||
- The screen's link moves about 150 KB/s (measured 2026-10-22: a full 480x320 frame takes 1.96 s, a 96x52 box 65 ms),
|
- The screen's link moves about 150 KB/s (measured 2026-10-22: a full 480x320 frame takes 1.96 s, a 96x52 box 65 ms),
|
||||||
@@ -97,4 +105,8 @@ The screen library is pinned to one upstream commit in the `Dockerfile` (`LCD_CO
|
|||||||
## Fonts
|
## Fonts
|
||||||
|
|
||||||
`assets/fonts/Roboto-Bold.ttf` (Apache 2.0, from the screen library) is used by the weather view;
|
`assets/fonts/Roboto-Bold.ttf` (Apache 2.0, from the screen library) is used by the weather view;
|
||||||
`Rajdhani-Bold.ttf` / `Rajdhani-SemiBold.ttf` (SIL Open Font License, see `Rajdhani-OFL.txt`) by the server view.
|
`Rajdhani-Bold.ttf` / `Rajdhani-SemiBold.ttf` (SIL Open Font License, see `Rajdhani-OFL.txt`) by the server view;
|
||||||
|
`Inter.ttf` (SIL Open Font License, see `Inter-OFL.txt`) by the sky and ISS views.
|
||||||
|
|
||||||
|
`assets/world_land.png` (the ISS map) is baked from Natural Earth's 1:110m land polygons (public domain) by
|
||||||
|
`tools/bake_world_map.py`.
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
Copyright 2020 The Inter Project Authors (https://github.com/rsms/inter)
|
||||||
|
|
||||||
|
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||||
|
This license is copied below, and is also available with a FAQ at:
|
||||||
|
https://scripts.sil.org/OFL
|
||||||
|
|
||||||
|
|
||||||
|
-----------------------------------------------------------
|
||||||
|
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||||
|
-----------------------------------------------------------
|
||||||
|
|
||||||
|
PREAMBLE
|
||||||
|
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||||
|
development of collaborative font projects, to support the font creation
|
||||||
|
efforts of academic and linguistic communities, and to provide a free and
|
||||||
|
open framework in which fonts may be shared and improved in partnership
|
||||||
|
with others.
|
||||||
|
|
||||||
|
The OFL allows the licensed fonts to be used, studied, modified and
|
||||||
|
redistributed freely as long as they are not sold by themselves. The
|
||||||
|
fonts, including any derivative works, can be bundled, embedded,
|
||||||
|
redistributed and/or sold with any software provided that any reserved
|
||||||
|
names are not used by derivative works. The fonts and derivatives,
|
||||||
|
however, cannot be released under any other type of license. The
|
||||||
|
requirement for fonts to remain under this license does not apply
|
||||||
|
to any document created using the fonts or their derivatives.
|
||||||
|
|
||||||
|
DEFINITIONS
|
||||||
|
"Font Software" refers to the set of files released by the Copyright
|
||||||
|
Holder(s) under this license and clearly marked as such. This may
|
||||||
|
include source files, build scripts and documentation.
|
||||||
|
|
||||||
|
"Reserved Font Name" refers to any names specified as such after the
|
||||||
|
copyright statement(s).
|
||||||
|
|
||||||
|
"Original Version" refers to the collection of Font Software components as
|
||||||
|
distributed by the Copyright Holder(s).
|
||||||
|
|
||||||
|
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||||
|
or substituting -- in part or in whole -- any of the components of the
|
||||||
|
Original Version, by changing formats or by porting the Font Software to a
|
||||||
|
new environment.
|
||||||
|
|
||||||
|
"Author" refers to any designer, engineer, programmer, technical
|
||||||
|
writer or other person who contributed to the Font Software.
|
||||||
|
|
||||||
|
PERMISSION & CONDITIONS
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||||
|
redistribute, and sell modified and unmodified copies of the Font
|
||||||
|
Software, subject to the following conditions:
|
||||||
|
|
||||||
|
1) Neither the Font Software nor any of its individual components,
|
||||||
|
in Original or Modified Versions, may be sold by itself.
|
||||||
|
|
||||||
|
2) Original or Modified Versions of the Font Software may be bundled,
|
||||||
|
redistributed and/or sold with any software, provided that each copy
|
||||||
|
contains the above copyright notice and this license. These can be
|
||||||
|
included either as stand-alone text files, human-readable headers or
|
||||||
|
in the appropriate machine-readable metadata fields within text or
|
||||||
|
binary files as long as those fields can be easily viewed by the user.
|
||||||
|
|
||||||
|
3) No Modified Version of the Font Software may use the Reserved Font
|
||||||
|
Name(s) unless explicit written permission is granted by the corresponding
|
||||||
|
Copyright Holder. This restriction only applies to the primary font name as
|
||||||
|
presented to the users.
|
||||||
|
|
||||||
|
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||||
|
Software shall not be used to promote, endorse or advertise any
|
||||||
|
Modified Version, except to acknowledge the contribution(s) of the
|
||||||
|
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||||
|
permission.
|
||||||
|
|
||||||
|
5) The Font Software, modified or unmodified, in part or in whole,
|
||||||
|
must be distributed entirely under this license, and must not be
|
||||||
|
distributed under any other license. The requirement for fonts to
|
||||||
|
remain under this license does not apply to any document created
|
||||||
|
using the Font Software.
|
||||||
|
|
||||||
|
TERMINATION
|
||||||
|
This license becomes null and void if any of the above conditions are
|
||||||
|
not met.
|
||||||
|
|
||||||
|
DISCLAIMER
|
||||||
|
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||||
|
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||||
|
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||||
|
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||||
|
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||||
|
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 2.8 KiB |
@@ -0,0 +1,168 @@
|
|||||||
|
"""The sky over Zlín, calculated locally (ephem): sun, moon, planets, bright stars and the ISS. No drawing.
|
||||||
|
|
||||||
|
Every time in and out is naive local wall-clock time (BOARD_TZ); ephem itself works in UTC.
|
||||||
|
"""
|
||||||
|
import math
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
import ephem
|
||||||
|
import ephem.stars
|
||||||
|
|
||||||
|
from sky_data import Tle
|
||||||
|
from timeutil import from_utc, to_utc
|
||||||
|
from weather_data import LAT, LON
|
||||||
|
|
||||||
|
ELEVATION_M = 230
|
||||||
|
DIRECTIONS = ["S", "SV", "V", "JV", "J", "JZ", "Z", "SZ"] # Czech: S = sever (north), J = jih (south)
|
||||||
|
BODIES = (("Měsíc", ephem.Moon), ("Merkur", ephem.Mercury), ("Venuše", ephem.Venus), ("Mars", ephem.Mars),
|
||||||
|
("Jupiter", ephem.Jupiter), ("Saturn", ephem.Saturn))
|
||||||
|
DARK_SUN_ALT = "-18" # astronomical darkness
|
||||||
|
VISIBLE_SUN_ALT = -6 # a satellite pass is visible once the sky is at least this dark
|
||||||
|
TRACK_BACK, TRACK_AHEAD = 40, 95 # minutes of ISS ground track around now
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Body:
|
||||||
|
name: str
|
||||||
|
alt: float # degrees above the horizon, negative below
|
||||||
|
az: float # degrees clockwise from north
|
||||||
|
rise: datetime | None # next rising, None when it does not rise or set
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Star:
|
||||||
|
name: str
|
||||||
|
mag: float
|
||||||
|
alt: float
|
||||||
|
az: float
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Pass:
|
||||||
|
start: datetime
|
||||||
|
max_alt: float
|
||||||
|
az_from: float
|
||||||
|
az_to: float
|
||||||
|
visible: bool # the ISS is sunlit while the sky here is dark
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Fix:
|
||||||
|
lat: float
|
||||||
|
lon: float
|
||||||
|
km: float # height above the ground
|
||||||
|
|
||||||
|
|
||||||
|
def direction(az: float) -> str:
|
||||||
|
return DIRECTIONS[round(az / 45) % 8]
|
||||||
|
|
||||||
|
|
||||||
|
def _observer(when: datetime, horizon: str = "0") -> ephem.Observer:
|
||||||
|
o = ephem.Observer()
|
||||||
|
o.lat, o.lon, o.elevation, o.horizon = str(LAT), str(LON), ELEVATION_M, horizon
|
||||||
|
o.date = to_utc(when)
|
||||||
|
return o
|
||||||
|
|
||||||
|
|
||||||
|
def _local(date: ephem.Date) -> datetime:
|
||||||
|
return from_utc(ephem.Date(date).datetime())
|
||||||
|
|
||||||
|
|
||||||
|
def bodies(now: datetime) -> tuple[Body, ...]:
|
||||||
|
"""Moon first, then the planets in order from the sun."""
|
||||||
|
out = []
|
||||||
|
for name, cls in BODIES:
|
||||||
|
body = cls()
|
||||||
|
o = _observer(now)
|
||||||
|
try:
|
||||||
|
rise = _local(o.next_rising(body))
|
||||||
|
except (ephem.AlwaysUpError, ephem.NeverUpError):
|
||||||
|
rise = None
|
||||||
|
body.compute(_observer(now))
|
||||||
|
out.append(Body(name, math.degrees(body.alt), math.degrees(body.az), rise))
|
||||||
|
return tuple(out)
|
||||||
|
|
||||||
|
|
||||||
|
def sun(now: datetime) -> Body:
|
||||||
|
s = ephem.Sun(_observer(now))
|
||||||
|
return Body("Slunce", math.degrees(s.alt), math.degrees(s.az), None)
|
||||||
|
|
||||||
|
|
||||||
|
def moon_phase(now: datetime) -> tuple[float, bool]:
|
||||||
|
"""Illuminated percentage and whether it is waxing."""
|
||||||
|
moon = ephem.Moon(_observer(now))
|
||||||
|
utc = to_utc(now)
|
||||||
|
return moon.phase, ephem.next_full_moon(utc) < ephem.next_new_moon(utc)
|
||||||
|
|
||||||
|
|
||||||
|
def darkness(now: datetime) -> tuple[datetime, datetime] | None:
|
||||||
|
"""Astronomical darkness of tonight (before noon: of the night now ending); None if the sun never sinks enough."""
|
||||||
|
evening = now.date() - timedelta(days=1) if now.hour < 12 else now.date()
|
||||||
|
o = _observer(datetime.combine(evening, datetime.min.time()).replace(hour=12), DARK_SUN_ALT)
|
||||||
|
sun = ephem.Sun()
|
||||||
|
try:
|
||||||
|
start = o.next_setting(sun, use_center=True)
|
||||||
|
o.date = start
|
||||||
|
end = o.next_rising(sun, use_center=True)
|
||||||
|
except (ephem.AlwaysUpError, ephem.NeverUpError):
|
||||||
|
return None
|
||||||
|
return _local(start), _local(end)
|
||||||
|
|
||||||
|
|
||||||
|
def stars(now: datetime, brighter_than: float = 3.4) -> tuple[Star, ...]:
|
||||||
|
"""Named stars above the horizon, brightest first."""
|
||||||
|
o = _observer(now)
|
||||||
|
out = []
|
||||||
|
for name in ephem.stars.stars:
|
||||||
|
star = ephem.star(name)
|
||||||
|
star.compute(o)
|
||||||
|
if star.alt > 0 and star.mag < brighter_than:
|
||||||
|
out.append(Star(name, star.mag, math.degrees(star.alt), math.degrees(star.az)))
|
||||||
|
return tuple(sorted(out, key=lambda s: s.mag))
|
||||||
|
|
||||||
|
|
||||||
|
def _iss(tle: Tle) -> ephem.EarthSatellite:
|
||||||
|
return ephem.readtle(tle.name, tle.line1, tle.line2)
|
||||||
|
|
||||||
|
|
||||||
|
def iss_fix(tle: Tle, when: datetime) -> Fix:
|
||||||
|
iss = _iss(tle)
|
||||||
|
iss.compute(to_utc(when))
|
||||||
|
return Fix(math.degrees(iss.sublat), math.degrees(iss.sublong), iss.elevation / 1000)
|
||||||
|
|
||||||
|
|
||||||
|
def iss_track(tle: Tle, now: datetime) -> tuple[tuple[int, float, float], ...]:
|
||||||
|
"""(minutes from now, lat, lon) for every minute from TRACK_BACK before to TRACK_AHEAD after now."""
|
||||||
|
iss = _iss(tle)
|
||||||
|
track = []
|
||||||
|
for m in range(-TRACK_BACK, TRACK_AHEAD + 1):
|
||||||
|
iss.compute(to_utc(now + timedelta(minutes=m)))
|
||||||
|
track.append((m, math.degrees(iss.sublat), math.degrees(iss.sublong)))
|
||||||
|
return tuple(track)
|
||||||
|
|
||||||
|
|
||||||
|
def next_visible_pass(tle: Tle, now: datetime, within_hours: float = 72) -> Pass | None:
|
||||||
|
iss, sun = _iss(tle), ephem.Sun()
|
||||||
|
o = _observer(now)
|
||||||
|
limit = ephem.Date(to_utc(now + timedelta(hours=within_hours)))
|
||||||
|
while o.date < limit:
|
||||||
|
rise, az_rise, top, top_alt, set_, az_set = o.next_pass(iss)
|
||||||
|
if rise is None or rise > limit:
|
||||||
|
return None
|
||||||
|
o.date = top
|
||||||
|
iss.compute(o)
|
||||||
|
sun.compute(o)
|
||||||
|
if not iss.eclipsed and math.degrees(sun.alt) < VISIBLE_SUN_ALT:
|
||||||
|
return Pass(_local(rise), math.degrees(top_alt), math.degrees(az_rise), math.degrees(az_set), True)
|
||||||
|
o.date = set_ + ephem.minute
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def subsolar(now: datetime) -> tuple[float, float]:
|
||||||
|
"""Latitude and longitude where the sun is straight overhead."""
|
||||||
|
o = ephem.Observer()
|
||||||
|
o.lat, o.lon, o.date = "0", "0", to_utc(now)
|
||||||
|
sun = ephem.Sun(o)
|
||||||
|
lon = math.degrees(sun.ra - o.sidereal_time())
|
||||||
|
return math.degrees(sun.dec), (lon + 540) % 360 - 180
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 40 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 59 KiB |
@@ -180,3 +180,16 @@ faster refresh than 5 s. The screen link moves about 150 KB/s (measured), so the
|
|||||||
rectangles of each frame (`regions.py`), which makes a 1 s refresh cost about 4 % of the link. The weather view
|
rectangles of each frame (`regions.py`), which makes a 1 s refresh cost about 4 % of the link. The weather view
|
||||||
keeps its Casio style. Stats are read every second; Docker is asked every 5 s and processes are ranked over 3 s
|
keeps its Casio style. Stats are read every second; Docker is asked every 5 s and processes are ranked over 3 s
|
||||||
windows to stop the list flickering. The server view is marked stale after 10 s.
|
windows to stop the list flickering. The server view is marked stale after 10 s.
|
||||||
|
|
||||||
|
## Addendum 2026-10-29: week ahead, night mode, sky and ISS views
|
||||||
|
|
||||||
|
- **Weather view** (owner picked it from Casio-style mockups): the weekday strip shows today and the next six days
|
||||||
|
(icon, max, min), the current temperature and feels-like sit beside the clock, and the rain graph spans the full
|
||||||
|
width with the hour under every bar. From sunset to sunrise the frame is a reverse LCD. Without today's sun times the
|
||||||
|
closest day's are used; with no forecast at all it stays day (designer's call, owner asked to deploy without
|
||||||
|
choosing).
|
||||||
|
- **Two new views, `sky` and `iss`**, approved from mockups as two separate screens switched with `VIEW` (owner
|
||||||
|
declined combining them into one day/night view). Everything is calculated locally with `ephem`; only the ISS orbit
|
||||||
|
(CelesTrak, 6 h) and cloud cover (Open-Meteo, 15 min) are fetched. Designer's calls: by day the star chart still
|
||||||
|
draws the stars, with the sun on it; the orbit is marked old after 3 days; the panel lists at most four bodies, up
|
||||||
|
ones first.
|
||||||
+143
@@ -0,0 +1,143 @@
|
|||||||
|
"""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 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)
|
||||||
|
MAP_TOP, MAP_H, DOT = 40, 240, 4
|
||||||
|
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 + (90 - lat) / 180 * 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(".", ",")
|
||||||
|
|
||||||
|
|
||||||
|
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()
|
||||||
|
sun = astro.subsolar(now)
|
||||||
|
for gy in range(DOT // 2, MAP_H, DOT):
|
||||||
|
lat = 90 - (gy + 1) / MAP_H * 180
|
||||||
|
for gx in range(DOT // 2, W, DOT):
|
||||||
|
day = is_day(lat, (gx + 1) / W * 360 - 180, sun)
|
||||||
|
if land[gx, gy]:
|
||||||
|
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:
|
||||||
|
skykit.tracked(d, (14, 298), "DALŠÍ VIDITELNÝ PŘELET", skykit.font(10, 650), ACCENT)
|
||||||
|
p = astro.next_visible_pass(tle, now)
|
||||||
|
if p is None:
|
||||||
|
d.text((14, 316), "v příštích 3 dnech žádný", font=skykit.font(15, 700), fill=TEXT, anchor="ls")
|
||||||
|
return
|
||||||
|
d.text((14, 316), f"{skykit.WEEKDAYS[p.start.weekday()]} {p.start.day}. {p.start.month}. v {hm(p.start)} · "
|
||||||
|
f"{p.max_alt:.0f}° · z {direction(p.az_from)} na {direction(p.az_to)}", font=skykit.font(15, 700),
|
||||||
|
fill=TEXT, anchor="ls")
|
||||||
|
pct = cloud_at(self._clouds.value or (), p.start)
|
||||||
|
if pct is not None:
|
||||||
|
label = f"mraky {pct} %"
|
||||||
|
colour = (255, 120, 100) if pct >= 60 else (240, 200, 90) if pct >= 25 else (120, 236, 160)
|
||||||
|
width = d.textlength(label, font=skykit.font(11, 700))
|
||||||
|
d.rounded_rectangle((466 - width - 16, 290, 466, 310), 10, fill=colour)
|
||||||
|
d.text((458, 304), label, font=skykit.font(11, 700), fill=BG, anchor="rs")
|
||||||
@@ -12,9 +12,10 @@ MAX_RETRY_S = 60.0
|
|||||||
|
|
||||||
class Poller(Generic[T]):
|
class Poller(Generic[T]):
|
||||||
def __init__(self, fetch: Callable[[], T], interval: float,
|
def __init__(self, fetch: Callable[[], T], interval: float,
|
||||||
clock: Callable[[], float] = time.monotonic) -> None:
|
clock: Callable[[], float] = time.monotonic, retry: float = MAX_RETRY_S) -> None:
|
||||||
self._fetch = fetch
|
self._fetch = fetch
|
||||||
self._interval = interval
|
self._interval = interval
|
||||||
|
self._retry = retry
|
||||||
self._clock = clock
|
self._clock = clock
|
||||||
self._lock = threading.Lock()
|
self._lock = threading.Lock()
|
||||||
self._value: T | None = None
|
self._value: T | None = None
|
||||||
@@ -76,7 +77,10 @@ class Poller(Generic[T]):
|
|||||||
if self._thread is not None:
|
if self._thread is not None:
|
||||||
self._thread.join(timeout=1)
|
self._thread.join(timeout=1)
|
||||||
|
|
||||||
|
def wait_after(self, ok: bool) -> float:
|
||||||
|
"""Seconds until the next fetch: the interval, or the (shorter) retry delay after a failure."""
|
||||||
|
return self._interval if ok else min(self._interval, self._retry)
|
||||||
|
|
||||||
def _loop(self) -> None:
|
def _loop(self) -> None:
|
||||||
while not self._stop.is_set():
|
while not self._stop.is_set():
|
||||||
ok = self.poll_once()
|
self._stop.wait(self.wait_after(self.poll_once()))
|
||||||
self._stop.wait(self._interval if ok else min(self._interval, MAX_RETRY_S))
|
|
||||||
+26
-1
@@ -1,16 +1,22 @@
|
|||||||
"""Render every view with fake data to docs/previews/*.png (no screen, no network needed)."""
|
"""Render every view with fake data to docs/previews/*.png (no screen, no network needed)."""
|
||||||
|
import json
|
||||||
from datetime import date, datetime, time, timedelta
|
from datetime import date, datetime, time, timedelta
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
|
from iss_view import IssView
|
||||||
from lcdkit import H, W
|
from lcdkit import H, W
|
||||||
|
from sky_data import parse_clouds, parse_tle
|
||||||
|
from sky_view import SkyView
|
||||||
from weather_data import Day, Hour, Weather
|
from weather_data import Day, Hour, Weather
|
||||||
from server_view import ServerView
|
from server_view import ServerView
|
||||||
from stats_data import Container, Proc, Stats
|
from stats_data import Container, Proc, Stats
|
||||||
from weather_view import WeatherView
|
from weather_view import WeatherView
|
||||||
|
|
||||||
OUT = Path(__file__).parent / "docs" / "previews"
|
OUT = Path(__file__).parent / "docs" / "previews"
|
||||||
|
FIXTURES = Path(__file__).parent / "tests" / "fixtures"
|
||||||
|
EVENING = datetime(2026, 10, 28, 19, 30, 8) # the evening the saved orbit and cloud forecast are from
|
||||||
NOW = datetime(2026, 10, 22, 14, 32, 8) # a Thursday afternoon
|
NOW = datetime(2026, 10, 22, 14, 32, 8) # a Thursday afternoon
|
||||||
|
|
||||||
|
|
||||||
@@ -88,9 +94,28 @@ def server_previews() -> Image.Image:
|
|||||||
return sheet([ServerView(p).render(NOW) for p in cases])
|
return sheet([ServerView(p).render(NOW) for p in cases])
|
||||||
|
|
||||||
|
|
||||||
|
def sky_previews() -> Image.Image:
|
||||||
|
tle = FakePoller(parse_tle((FIXTURES / "celestrak-iss.tle").read_text()), age=3600.0)
|
||||||
|
clouds = FakePoller(parse_clouds(json.loads((FIXTURES / "open-meteo-clouds.json").read_text())))
|
||||||
|
old = FakePoller(tle.value, age=4 * 86400.0)
|
||||||
|
nothing = FakePoller(None, age=None)
|
||||||
|
return sheet([SkyView(tle, clouds).render(EVENING), SkyView(tle, clouds).render(EVENING.replace(hour=12)),
|
||||||
|
SkyView(nothing, nothing).render(EVENING), SkyView(old, clouds).render(EVENING)])
|
||||||
|
|
||||||
|
|
||||||
|
def iss_previews() -> Image.Image:
|
||||||
|
tle = FakePoller(parse_tle((FIXTURES / "celestrak-iss.tle").read_text()), age=3600.0)
|
||||||
|
clouds = FakePoller(parse_clouds(json.loads((FIXTURES / "open-meteo-clouds.json").read_text())))
|
||||||
|
nothing = FakePoller(None, age=None)
|
||||||
|
return sheet([IssView(tle, clouds).render(EVENING), IssView(tle, clouds).render(EVENING + timedelta(minutes=50)),
|
||||||
|
IssView(nothing, nothing).render(EVENING), IssView(FakePoller(tle.value, age=4 * 86400.0),
|
||||||
|
clouds).render(EVENING)])
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
OUT.mkdir(parents=True, exist_ok=True)
|
OUT.mkdir(parents=True, exist_ok=True)
|
||||||
for name, image in (("weather", weather_previews()), ("server", server_previews())):
|
for name, image in (("weather", weather_previews()), ("server", server_previews()), ("sky", sky_previews()),
|
||||||
|
("iss", iss_previews())):
|
||||||
image.save(OUT / f"{name}.png")
|
image.save(OUT / f"{name}.png")
|
||||||
print(OUT / f"{name}.png")
|
print(OUT / f"{name}.png")
|
||||||
|
|
||||||
|
|||||||
+21
@@ -1,8 +1,11 @@
|
|||||||
"""The views the container can show, selected by the VIEW env var."""
|
"""The views the container can show, selected by the VIEW env var."""
|
||||||
from typing import Callable
|
from typing import Callable
|
||||||
|
|
||||||
|
from iss_view import IssView
|
||||||
from poller import Poller
|
from poller import Poller
|
||||||
from server_view import ServerView
|
from server_view import ServerView
|
||||||
|
from sky_data import fetch_clouds, fetch_tle
|
||||||
|
from sky_view import SkyView
|
||||||
from stats_data import StatsReader
|
from stats_data import StatsReader
|
||||||
from timeutil import local_now
|
from timeutil import local_now
|
||||||
from view import View
|
from view import View
|
||||||
@@ -11,6 +14,9 @@ from weather_view import WeatherView
|
|||||||
|
|
||||||
WEATHER_REFRESH_S = 15 * 60
|
WEATHER_REFRESH_S = 15 * 60
|
||||||
SERVER_REFRESH_S = 1
|
SERVER_REFRESH_S = 1
|
||||||
|
TLE_REFRESH_S = 6 * 3600 # CelesTrak updates the elements a few times a day and asks not to be polled hard
|
||||||
|
TLE_RETRY_S = 30 * 60
|
||||||
|
CLOUDS_REFRESH_S = 15 * 60
|
||||||
|
|
||||||
|
|
||||||
class UnknownView(Exception):
|
class UnknownView(Exception):
|
||||||
@@ -28,10 +34,25 @@ def _server() -> View:
|
|||||||
return ServerView(Poller(StatsReader().read, SERVER_REFRESH_S))
|
return ServerView(Poller(StatsReader().read, SERVER_REFRESH_S))
|
||||||
|
|
||||||
|
|
||||||
|
def _sky_pollers() -> tuple[Poller, Poller]:
|
||||||
|
return (Poller(fetch_tle, TLE_REFRESH_S, retry=TLE_RETRY_S),
|
||||||
|
Poller(fetch_clouds, CLOUDS_REFRESH_S))
|
||||||
|
|
||||||
|
|
||||||
|
def _sky() -> View:
|
||||||
|
return SkyView(*_sky_pollers())
|
||||||
|
|
||||||
|
|
||||||
|
def _iss() -> View:
|
||||||
|
return IssView(*_sky_pollers())
|
||||||
|
|
||||||
|
|
||||||
# To add a view: write the module, add one entry here, add a README line.
|
# To add a view: write the module, add one entry here, add a README line.
|
||||||
REGISTRY: dict[str, Callable[[], View]] = {
|
REGISTRY: dict[str, Callable[[], View]] = {
|
||||||
"weather": _weather,
|
"weather": _weather,
|
||||||
"server": _server,
|
"server": _server,
|
||||||
|
"sky": _sky,
|
||||||
|
"iss": _iss,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -2,3 +2,4 @@ Pillow>=11.0
|
|||||||
numpy>=2.0
|
numpy>=2.0
|
||||||
pyserial~=3.5
|
pyserial~=3.5
|
||||||
requests>=2.32
|
requests>=2.32
|
||||||
|
ephem~=4.2
|
||||||
+79
@@ -0,0 +1,79 @@
|
|||||||
|
"""ISS orbit from CelesTrak and cloud cover from Open-Meteo for Zlín: fetching and parsing (no drawing)."""
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
import ephem
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from weather_data import LAT, LON, TIMEZONE, URL as OPEN_METEO_URL
|
||||||
|
|
||||||
|
CELESTRAK_URL = "https://celestrak.org/NORAD/elements/gp.php"
|
||||||
|
ISS_CATALOG_NUMBER = 25544
|
||||||
|
STORY_HOURS = 12
|
||||||
|
SOME_CLOUD, OVERCAST = 25, 60 # percent
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Tle:
|
||||||
|
"""Two-line orbital elements: what ephem needs to place a satellite at any moment."""
|
||||||
|
name: str
|
||||||
|
line1: str
|
||||||
|
line2: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class CloudHour:
|
||||||
|
time: datetime # naive local time, on the hour
|
||||||
|
pct: int | None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_tle(text: str) -> Tle:
|
||||||
|
lines = [line.strip() for line in text.strip().splitlines()]
|
||||||
|
if len(lines) < 3 or not lines[1].startswith("1 ") or not lines[2].startswith("2 "):
|
||||||
|
raise ValueError(f"not a TLE: {text[:60]!r}")
|
||||||
|
try:
|
||||||
|
ephem.readtle(*lines[:3])
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValueError(f"unreadable TLE: {exc}") from None
|
||||||
|
return Tle(*lines[:3])
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_tle(get=requests.get) -> Tle:
|
||||||
|
response = get(CELESTRAK_URL, params={"CATNR": ISS_CATALOG_NUMBER, "FORMAT": "TLE"}, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
return parse_tle(response.text)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_clouds(payload: dict) -> tuple[CloudHour, ...]:
|
||||||
|
hourly = payload.get("hourly") or {}
|
||||||
|
pcts = hourly.get("cloud_cover") or []
|
||||||
|
return tuple(CloudHour(datetime.fromisoformat(t), pcts[i] if i < len(pcts) else None)
|
||||||
|
for i, t in enumerate(hourly.get("time") or []))
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_clouds(get=requests.get) -> tuple[CloudHour, ...]:
|
||||||
|
params = {"latitude": LAT, "longitude": LON, "hourly": "cloud_cover", "timezone": TIMEZONE, "forecast_days": 2}
|
||||||
|
response = get(OPEN_METEO_URL, params=params, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
return parse_clouds(response.json())
|
||||||
|
|
||||||
|
|
||||||
|
def cloud_at(clouds: tuple[CloudHour, ...], when: datetime) -> int | None:
|
||||||
|
"""Cloud cover for the hour containing `when`, None if the forecast does not reach it."""
|
||||||
|
hour = when.replace(minute=0, second=0, microsecond=0)
|
||||||
|
return next((c.pct for c in clouds if c.time == hour), None)
|
||||||
|
|
||||||
|
|
||||||
|
def cloud_story(clouds: tuple[CloudHour, ...], now: datetime) -> str | None:
|
||||||
|
"""The next 12 hours in a few words: `Jasno`, `Polojasno`, `Zataženo` or `Jasno do 20 h, od 22 h zataženo`."""
|
||||||
|
start = now.replace(minute=0, second=0, microsecond=0)
|
||||||
|
hours = [c for c in clouds if start <= c.time <= start + timedelta(hours=STORY_HOURS)]
|
||||||
|
if not hours:
|
||||||
|
return None
|
||||||
|
some = next((c for c in hours if (c.pct or 0) >= SOME_CLOUD), None)
|
||||||
|
full = next((c for c in hours if (c.pct or 0) >= OVERCAST), None)
|
||||||
|
if some is None:
|
||||||
|
return "Jasno"
|
||||||
|
if some is hours[0]:
|
||||||
|
return "Zataženo" if full is some else "Polojasno"
|
||||||
|
return f"Jasno do {some.time.hour} h" + (f", od {full.time.hour} h zataženo" if full else ", pak polojasno")
|
||||||
+171
@@ -0,0 +1,171 @@
|
|||||||
|
"""The sky over Zlín right now: a star chart as seen lying on your back, and what is up tonight."""
|
||||||
|
import math
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
import astro
|
||||||
|
import skykit
|
||||||
|
from astro import Body, direction
|
||||||
|
from poller import Poller
|
||||||
|
from sky_data import CloudHour, Tle, cloud_at, cloud_story
|
||||||
|
from skykit import H, W, hm, mix, tracked
|
||||||
|
from view import Patch
|
||||||
|
|
||||||
|
BG, RING, LINE, LABEL = (7, 10, 24), (30, 42, 72), (46, 62, 100), (120, 140, 182)
|
||||||
|
TEXT, SUB, STAR, ISS = (236, 238, 246), (150, 165, 200), (214, 222, 242), (130, 220, 230)
|
||||||
|
DOME_NIGHT, DOME_TWILIGHT, DOME_DAY = (12, 19, 42), (17, 28, 60), (26, 46, 90)
|
||||||
|
CLEAR, CLOUDY = (40, 120, 90), (120, 124, 140)
|
||||||
|
STALE_BG, STALE_INK = (240, 200, 90), BG
|
||||||
|
COLOURS = {"Měsíc": (235, 235, 220), "Merkur": (180, 170, 160), "Venuše": (255, 248, 220), "Mars": (255, 120, 80),
|
||||||
|
"Jupiter": (245, 222, 180), "Saturn": (240, 200, 110), "Slunce": (255, 214, 90)}
|
||||||
|
LINES = (("Vega", "Deneb"), ("Deneb", "Altair"), ("Altair", "Vega"),
|
||||||
|
("Dubhe", "Merak"), ("Merak", "Phecda"), ("Phecda", "Megrez"), ("Megrez", "Dubhe"),
|
||||||
|
("Megrez", "Alioth"), ("Alioth", "Mizar"), ("Mizar", "Alkaid"),
|
||||||
|
("Markab", "Scheat"), ("Scheat", "Alpheratz"), ("Alpheratz", "Algenib"), ("Algenib", "Markab"),
|
||||||
|
("Alpheratz", "Mirach"), ("Mirach", "Almach"), ("Deneb", "Sadr"), ("Sadr", "Albireo"), ("Mirfak", "Algol"),
|
||||||
|
("Betelgeuse", "Bellatrix"), ("Bellatrix", "Mintaka"), ("Mintaka", "Alnilam"), ("Alnilam", "Alnitak"),
|
||||||
|
("Alnitak", "Saiph"), ("Saiph", "Rigel"), ("Rigel", "Mintaka"), ("Alnitak", "Betelgeuse"))
|
||||||
|
CX, CY, R = 162, 162, 150 # the dome
|
||||||
|
PANEL_X = 326
|
||||||
|
RISING_WITHIN = timedelta(hours=10)
|
||||||
|
MAX_ROWS = 4
|
||||||
|
|
||||||
|
|
||||||
|
def dome_xy(alt: float, az: float) -> tuple[float, float]:
|
||||||
|
"""Zenith in the centre, horizon on the rim, north up and east on the left (a chart held overhead)."""
|
||||||
|
r = R * (90 - alt) / 90
|
||||||
|
return CX - r * math.sin(math.radians(az)), CY - r * math.cos(math.radians(az))
|
||||||
|
|
||||||
|
|
||||||
|
def panel_rows(bodies: tuple[Body, ...], moon_pct: float, now: datetime) -> list[tuple[str, str]]:
|
||||||
|
"""What is up (highest first), then what rises in the next hours (soonest first); at most MAX_ROWS."""
|
||||||
|
up = sorted((b for b in bodies if b.alt > 0), key=lambda b: -b.alt)
|
||||||
|
rising = sorted((b for b in bodies if b.alt <= 0 and b.rise is not None and b.rise - now <= RISING_WITHIN),
|
||||||
|
key=lambda b: b.rise)
|
||||||
|
rows = [(b.name, f"{moon_pct:.0f} % · {direction(b.az)}" if b.name == "Měsíc" else f"{b.alt:.0f}° {direction(b.az)}")
|
||||||
|
for b in up]
|
||||||
|
rows += [(b.name, f"↑ {hm(b.rise)}") for b in rising]
|
||||||
|
return rows[:MAX_ROWS]
|
||||||
|
|
||||||
|
|
||||||
|
class SkyView:
|
||||||
|
name = "sky"
|
||||||
|
TLE_STALE_AFTER = 3 * 86400.0 # ISS predictions drift once the orbit is days old
|
||||||
|
CLOUDS_STALE_AFTER = 3600.0
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _old(poller: Poller, limit: float) -> bool:
|
||||||
|
age = poller.age()
|
||||||
|
return age is not None and age > limit
|
||||||
|
|
||||||
|
def frame_key(self, now: datetime):
|
||||||
|
return (now.strftime("%Y%m%d%H%M"), self._tle.version, self._clouds.version,
|
||||||
|
self._old(self._tle, self.TLE_STALE_AFTER), self._old(self._clouds, self.CLOUDS_STALE_AFTER))
|
||||||
|
|
||||||
|
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)
|
||||||
|
bodies = astro.bodies(now)
|
||||||
|
moon_pct, waxing = astro.moon_phase(now)
|
||||||
|
self._dome(img, d, now, bodies, moon_pct, waxing)
|
||||||
|
self._panel(d, now, bodies, moon_pct)
|
||||||
|
return img
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _dome(img, d, now, bodies, moon_pct, waxing) -> None:
|
||||||
|
sun = astro.sun(now)
|
||||||
|
fill = DOME_DAY if sun.alt > 0 else DOME_TWILIGHT if sun.alt > -12 else DOME_NIGHT
|
||||||
|
d.ellipse((CX - R, CY - R, CX + R, CY + R), fill=fill, outline=RING, width=2)
|
||||||
|
for alt in (30, 60):
|
||||||
|
r = R * (90 - alt) / 90
|
||||||
|
for k in range(0, 360, 4):
|
||||||
|
d.point((CX + r * math.cos(math.radians(k)), CY + r * math.sin(math.radians(k))), fill=RING)
|
||||||
|
|
||||||
|
stars = {s.name: s for s in astro.stars(now)}
|
||||||
|
for a, b in LINES:
|
||||||
|
if a in stars and b in stars:
|
||||||
|
d.line((*dome_xy(stars[a].alt, stars[a].az), *dome_xy(stars[b].alt, stars[b].az)), fill=LINE)
|
||||||
|
for s in stars.values():
|
||||||
|
x, y = dome_xy(s.alt, s.az)
|
||||||
|
r = max(0.8, 2.8 - 0.8 * s.mag)
|
||||||
|
d.ellipse((x - r, y - r, x + r, y + r), fill=STAR)
|
||||||
|
|
||||||
|
visible = [b for b in (sun, *bodies) if b.alt > 0] # the sun and moon claim their label space first
|
||||||
|
for b in visible:
|
||||||
|
x, y = dome_xy(b.alt, b.az)
|
||||||
|
if b.name == "Měsíc":
|
||||||
|
skykit.moon_disc(img, x, y, 9, moon_pct, waxing, lit=COLOURS[b.name], dark=(40, 44, 60))
|
||||||
|
else:
|
||||||
|
r = 7 if b.name == "Slunce" else 4
|
||||||
|
d.ellipse((x - r, y - r, x + r, y + r), fill=COLOURS[b.name])
|
||||||
|
labels: list[tuple[float, float, float, float]] = []
|
||||||
|
for b in visible:
|
||||||
|
x, y = dome_xy(b.alt, b.az)
|
||||||
|
colour = COLOURS[b.name]
|
||||||
|
f = skykit.font(11, 600)
|
||||||
|
right = x + 12 + d.textlength(b.name, font=f) <= CX + R # else put the label on the left
|
||||||
|
at, anchor = ((x + 12, y + 4), "ls") if right else ((x - 12, y + 4), "rs")
|
||||||
|
box = d.textbbox(at, b.name, font=f, anchor=anchor)
|
||||||
|
if not any(box[0] < o[2] and o[0] < box[2] and box[1] < o[3] and o[1] < box[3] for o in labels):
|
||||||
|
d.text(at, b.name, font=f, fill=colour, anchor=anchor)
|
||||||
|
labels.append(box)
|
||||||
|
for text, (x, y) in (("S", (CX, 24)), ("J", (CX, 300)), ("V", (24, CY)), ("Z", (300, CY))):
|
||||||
|
d.text((x, y), text, font=skykit.font(12, 700), fill=LABEL, anchor="mm")
|
||||||
|
|
||||||
|
def _panel(self, d, now, bodies, moon_pct) -> None:
|
||||||
|
x0, x1 = PANEL_X, 468
|
||||||
|
tracked(d, (x0, 24), "OBLOHA · ZLÍN", skykit.font(10, 650), LABEL)
|
||||||
|
d.text((x0, 60), hm(now), font=skykit.font(30, 700), fill=TEXT, anchor="ls")
|
||||||
|
dark = astro.darkness(now)
|
||||||
|
d.text((x0, 78), f"tma {hm(dark[0])}–{hm(dark[1])}" if dark else "bez úplné tmy", font=skykit.font(12, 500),
|
||||||
|
fill=SUB, anchor="ls")
|
||||||
|
d.line((x0, 90, x1, 90), fill=RING)
|
||||||
|
|
||||||
|
rows = panel_rows(bodies, moon_pct, now)
|
||||||
|
for i, (name, info) in enumerate(rows):
|
||||||
|
y = 112 + i * 24
|
||||||
|
d.ellipse((x0, y - 8, x0 + 7, y - 1), fill=COLOURS[name])
|
||||||
|
d.text((x0 + 14, y), name, font=skykit.font(13, 600), fill=TEXT, anchor="ls")
|
||||||
|
d.text((x1, y), info, font=skykit.font(12, 500), fill=SUB, anchor="rs")
|
||||||
|
y = 112 + len(rows) * 24 - 8
|
||||||
|
d.line((x0, y, x1, y), fill=RING)
|
||||||
|
|
||||||
|
clouds: tuple[CloudHour, ...] = self._clouds.value or ()
|
||||||
|
end = tracked(d, (x0, y + 20), "MRAKY", skykit.font(10, 650), LABEL)
|
||||||
|
if self._old(self._clouds, self.CLOUDS_STALE_AFTER):
|
||||||
|
skykit.tag(d, (end + 8, y + 20), "STARÉ", skykit.font(10, 700), STALE_BG, STALE_INK)
|
||||||
|
for i in range(12):
|
||||||
|
pct = cloud_at(clouds, now + timedelta(hours=i))
|
||||||
|
colour = RING if pct is None else mix(CLEAR, CLOUDY, pct / 100)
|
||||||
|
d.rectangle((x0 + i * 12, y + 28, x0 + i * 12 + 9, y + 44), fill=colour)
|
||||||
|
story = cloud_story(clouds, now) or "--"
|
||||||
|
for k, line in enumerate(story.split(", ")):
|
||||||
|
d.text((x0, y + 60 + k * 15), line, font=skykit.font(11, 600), fill=TEXT, anchor="ls")
|
||||||
|
|
||||||
|
tle: Tle | None = self._tle.value
|
||||||
|
if tle is None:
|
||||||
|
text = "ISS --"
|
||||||
|
else:
|
||||||
|
p = astro.next_visible_pass(tle, now)
|
||||||
|
text = f"ISS {skykit.WEEKDAYS[p.start.weekday()]} {hm(p.start)} · {p.max_alt:.0f}°" if p else \
|
||||||
|
"ISS: nic do 3 dnů"
|
||||||
|
end = d.textlength(text, font=skykit.font(12, 600)) + x0
|
||||||
|
d.text((x0, 304), text, font=skykit.font(12, 600), fill=ISS, anchor="ls")
|
||||||
|
if self._old(self._tle, self.TLE_STALE_AFTER):
|
||||||
|
skykit.tag(d, (end + 8, 304), "STARÉ", skykit.font(10, 700), STALE_BG, STALE_INK)
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""Night-sky drawing kit for the sky and ISS views: Inter type, letter-spaced labels, colour mixing, moon phase."""
|
||||||
|
import math
|
||||||
|
from functools import lru_cache
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PIL import Image, ImageChops, ImageDraw, ImageFont
|
||||||
|
|
||||||
|
W, H = 480, 320
|
||||||
|
FONT_PATH = Path(__file__).parent / "assets" / "fonts" / "Inter.ttf"
|
||||||
|
WEEKDAYS = ["po", "út", "st", "čt", "pá", "so", "ne"]
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=None)
|
||||||
|
def font(size: int, weight: int = 500) -> ImageFont.FreeTypeFont:
|
||||||
|
f = ImageFont.truetype(str(FONT_PATH), size)
|
||||||
|
f.set_variation_by_axes([14 if size < 20 else 32, weight]) # optical size, weight
|
||||||
|
return f
|
||||||
|
|
||||||
|
|
||||||
|
def mix(a, b, t: float):
|
||||||
|
t = max(0.0, min(1.0, t))
|
||||||
|
return tuple(round(x + (y - x) * t) for x, y in zip(a, b))
|
||||||
|
|
||||||
|
|
||||||
|
def hm(t) -> str:
|
||||||
|
return "--:--" if t is None else f"{t.hour}:{t.minute:02d}"
|
||||||
|
|
||||||
|
|
||||||
|
def tracked(d: ImageDraw.ImageDraw, xy, text: str, f, fill, track: float = 1.2, right: bool = False) -> float:
|
||||||
|
"""Letter-spaced text on baseline xy[1]; returns the end x."""
|
||||||
|
width = sum(d.textlength(ch, font=f) for ch in text) + track * (len(text) - 1)
|
||||||
|
x = xy[0] - width if right else xy[0]
|
||||||
|
for ch in text:
|
||||||
|
d.text((x, xy[1]), ch, font=f, fill=fill, anchor="ls")
|
||||||
|
x += d.textlength(ch, font=f) + track
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
|
def tag(d: ImageDraw.ImageDraw, xy, text: str, f, fill, ink) -> None:
|
||||||
|
"""A pill-shaped label with its text baseline at xy[1]."""
|
||||||
|
x, y = xy
|
||||||
|
width = d.textlength(text, font=f)
|
||||||
|
d.rounded_rectangle((x, y - 13, x + width + 12, y + 4), 8, fill=fill)
|
||||||
|
d.text((x + 6, y), text, font=f, fill=ink, anchor="ls")
|
||||||
|
|
||||||
|
|
||||||
|
def moon_disc(img: Image.Image, cx: float, cy: float, r: int, pct: float, waxing: bool, lit, dark) -> None:
|
||||||
|
"""The moon as seen from the northern hemisphere: lit on the right while waxing, on the left while waning."""
|
||||||
|
p = math.acos(max(-1.0, min(1.0, 1 - 2 * pct / 100))) / (2 * math.pi) # 0 new .. 0.5 full
|
||||||
|
p = p if waxing else 1 - p
|
||||||
|
s = 2 * r * 4 # drawn 4x larger, then scaled down for smooth edges
|
||||||
|
disc = Image.new("L", (s, s), 0)
|
||||||
|
ImageDraw.Draw(disc).ellipse((0, 0, s - 1, s - 1), fill=255)
|
||||||
|
half = Image.new("L", (s, s), 0)
|
||||||
|
ImageDraw.Draw(half).rectangle((s // 2, 0, s, s) if p < 0.5 else (0, 0, s // 2, s), fill=255)
|
||||||
|
lit_mask = ImageChops.multiply(half, disc)
|
||||||
|
ew = s * abs(math.cos(2 * math.pi * p)) / 2 # half-width of the terminator ellipse
|
||||||
|
terminator = Image.new("L", (s, s), 0)
|
||||||
|
ImageDraw.Draw(terminator).ellipse((s / 2 - ew, 0, s / 2 + ew, s - 1), fill=255)
|
||||||
|
if pct < 50:
|
||||||
|
lit_mask = ImageChops.subtract(lit_mask, terminator)
|
||||||
|
else:
|
||||||
|
lit_mask = ImageChops.lighter(lit_mask, ImageChops.multiply(terminator, disc))
|
||||||
|
x0, y0 = round(cx - r), round(cy - r)
|
||||||
|
box = (x0, y0, x0 + 2 * r, y0 + 2 * r)
|
||||||
|
img.paste(dark, box, disc.resize((2 * r, 2 * r), Image.LANCZOS))
|
||||||
|
if pct > 0:
|
||||||
|
img.paste(lit, box, lit_mask.resize((2 * r, 2 * r), Image.LANCZOS).point(lambda v: 255 if v > 127 else 0))
|
||||||
Vendored
+3
@@ -0,0 +1,3 @@
|
|||||||
|
ISS (ZARYA)
|
||||||
|
1 25544U 98067A 26301.46699108 .00005372 00000+0 10526-3 0 9998
|
||||||
|
2 25544 51.6335 0.5562 0007038 319.9799 40.0670 15.49088092592412
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
{"latitude":49.23005,"longitude":17.657297,"generationtime_ms":0.030279159545898438,"utc_offset_seconds":3600,"timezone":"Europe/Prague","timezone_abbreviation":"GMT+1","elevation":221.0,"hourly_units":{"time":"iso8601","cloud_cover":"%"},"hourly":{"time":["2026-10-28T00:00","2026-10-28T01:00","2026-10-28T02:00","2026-10-28T03:00","2026-10-28T04:00","2026-10-28T05:00","2026-10-28T06:00","2026-10-28T07:00","2026-10-28T08:00","2026-10-28T09:00","2026-10-28T10:00","2026-10-28T11:00","2026-10-28T12:00","2026-10-28T13:00","2026-10-28T14:00","2026-10-28T15:00","2026-10-28T16:00","2026-10-28T17:00","2026-10-28T18:00","2026-10-28T19:00","2026-10-28T20:00","2026-10-28T21:00","2026-10-28T22:00","2026-10-28T23:00","2026-10-29T00:00","2026-10-29T01:00","2026-10-29T02:00","2026-10-29T03:00","2026-10-29T04:00","2026-10-29T05:00","2026-10-29T06:00","2026-10-29T07:00","2026-10-29T08:00","2026-10-29T09:00","2026-10-29T10:00","2026-10-29T11:00","2026-10-29T12:00","2026-10-29T13:00","2026-10-29T14:00","2026-10-29T15:00","2026-10-29T16:00","2026-10-29T17:00","2026-10-29T18:00","2026-10-29T19:00","2026-10-29T20:00","2026-10-29T21:00","2026-10-29T22:00","2026-10-29T23:00"],"cloud_cover":[0,0,0,4,0,0,44,100,18,0,0,0,0,0,0,0,0,0,0,0,31,36,82,100,99,98,99,100,100,100,99,95,94,69,74,83,79,84,91,86,91,93,76,68,82,96,96,99]}}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
from datetime import datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import astro
|
||||||
|
from astro import direction
|
||||||
|
from sky_data import parse_tle
|
||||||
|
|
||||||
|
TLE = parse_tle((Path(__file__).parent / "fixtures" / "celestrak-iss.tle").read_text()) # epoch 28 Oct 2026
|
||||||
|
EVENING = datetime(2026, 10, 28, 19, 30) # local time in Zlín (CET)
|
||||||
|
|
||||||
|
|
||||||
|
def near(actual: datetime, expected: datetime, minutes: float = 4) -> bool:
|
||||||
|
return abs(actual - expected) <= timedelta(minutes=minutes)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("az, name", [(0, "S"), (22, "S"), (23, "SV"), (90, "V"), (135, "JV"), (180, "J"),
|
||||||
|
(270, "Z"), (315, "SZ"), (359, "S")])
|
||||||
|
def test_direction_uses_czech_compass_letters(az, name):
|
||||||
|
assert direction(az) == name
|
||||||
|
|
||||||
|
|
||||||
|
def test_moon_is_waning_two_days_after_full_moon():
|
||||||
|
pct, waxing = astro.moon_phase(EVENING) # full moon was on 26 Oct
|
||||||
|
assert 85 < pct < 96
|
||||||
|
assert not waxing
|
||||||
|
|
||||||
|
|
||||||
|
def test_darkness_tonight():
|
||||||
|
start, end = astro.darkness(EVENING)
|
||||||
|
assert near(start, datetime(2026, 10, 28, 18, 22))
|
||||||
|
assert near(end, datetime(2026, 10, 29, 4, 44))
|
||||||
|
|
||||||
|
|
||||||
|
def test_after_midnight_darkness_is_the_current_night():
|
||||||
|
assert astro.darkness(datetime(2026, 10, 29, 2, 0)) == astro.darkness(EVENING)
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_full_darkness_around_midsummer():
|
||||||
|
# at 49.2° N the sun sinks at most 90 - 49.2 - 23.4 = 17.4° below the horizon, never the 18° of full darkness
|
||||||
|
assert astro.darkness(datetime(2026, 6, 21, 23, 0)) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_polaris_stands_at_our_latitude_due_north():
|
||||||
|
polaris = next(s for s in astro.stars(EVENING) if s.name == "Polaris")
|
||||||
|
assert abs(polaris.alt - 49.2) < 1.2
|
||||||
|
assert min(polaris.az, 360 - polaris.az) < 1.5
|
||||||
|
|
||||||
|
|
||||||
|
def test_only_stars_above_the_horizon():
|
||||||
|
names = {s.name for s in astro.stars(EVENING)}
|
||||||
|
assert {"Vega", "Deneb", "Altair", "Capella"} <= names
|
||||||
|
assert "Sirius" not in names # an evening in October: below the horizon
|
||||||
|
assert all(s.alt > 0 for s in astro.stars(EVENING))
|
||||||
|
|
||||||
|
|
||||||
|
def test_planets_tonight():
|
||||||
|
bodies = {b.name: b for b in astro.bodies(EVENING)}
|
||||||
|
assert list(bodies) == ["Měsíc", "Merkur", "Venuše", "Mars", "Jupiter", "Saturn"]
|
||||||
|
assert 25 < bodies["Saturn"].alt < 40 and direction(bodies["Saturn"].az) == "JV"
|
||||||
|
assert bodies["Měsíc"].alt > 0 and direction(bodies["Měsíc"].az) == "V"
|
||||||
|
assert bodies["Mars"].alt < 0 and near(bodies["Mars"].rise, datetime(2026, 10, 28, 23, 12), 5)
|
||||||
|
assert near(bodies["Jupiter"].rise, datetime(2026, 10, 28, 23, 54), 5)
|
||||||
|
|
||||||
|
|
||||||
|
def test_iss_stays_within_its_orbit():
|
||||||
|
fix = astro.iss_fix(TLE, EVENING)
|
||||||
|
assert abs(fix.lat) <= 51.7 # orbit inclination 51.6°
|
||||||
|
assert 370 < fix.km < 460
|
||||||
|
|
||||||
|
|
||||||
|
def test_iss_track_runs_east_minute_by_minute():
|
||||||
|
track = astro.iss_track(TLE, EVENING)
|
||||||
|
assert [m for m, _, _ in track] == list(range(-40, 96))
|
||||||
|
for (_, lat0, lon0), (_, lat1, lon1) in zip(track, track[1:]):
|
||||||
|
assert abs(lat1) <= 51.7
|
||||||
|
assert 2 < (lon1 - lon0) % 360 < 6 # one orbit in ~93 min, minus the earth turning under it
|
||||||
|
|
||||||
|
|
||||||
|
def test_next_visible_iss_pass():
|
||||||
|
p = astro.next_visible_pass(TLE, EVENING)
|
||||||
|
assert near(p.start, datetime(2026, 10, 29, 5, 38), 2)
|
||||||
|
assert 35 < p.max_alt < 45
|
||||||
|
assert (direction(p.az_from), direction(p.az_to)) == ("Z", "JV")
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_visible_pass_within_the_window():
|
||||||
|
assert astro.next_visible_pass(TLE, EVENING, within_hours=6) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_subsolar_point():
|
||||||
|
# 18:30 UTC on 28 Oct: declination about -13.3°; the sundial runs 16 minutes ahead of the clock in late
|
||||||
|
# October, so it is 18:46 apparent time at Greenwich and the sun stands 6.77 h * 15° = 101.5° west
|
||||||
|
lat, lon = astro.subsolar(EVENING)
|
||||||
|
assert abs(lat - -13.3) < 1
|
||||||
|
assert abs(lon - -101.5) < 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_noon_sun_stands_due_south_at_90_minus_latitude_plus_declination():
|
||||||
|
# solar noon in Zlín on 28 Oct: 12:00 CET - 10.6 min (17.66° east of 15°) - 16 min equation of time = 11:33
|
||||||
|
sun = astro.sun(datetime(2026, 10, 28, 11, 33))
|
||||||
|
assert abs(sun.alt - (90 - 49.2 - 13.0)) < 1
|
||||||
|
assert abs(sun.az - 180) < 3
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import json
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from PIL import ImageChops
|
||||||
|
|
||||||
|
import astro
|
||||||
|
from iss_view import MAP_TOP, MARKER, IssView, is_day, map_xy
|
||||||
|
from sky_data import parse_clouds, parse_tle
|
||||||
|
from tests.helpers import count_near
|
||||||
|
|
||||||
|
FIXTURES = Path(__file__).parent / "fixtures"
|
||||||
|
TLE = parse_tle((FIXTURES / "celestrak-iss.tle").read_text())
|
||||||
|
CLOUDS = parse_clouds(json.loads((FIXTURES / "open-meteo-clouds.json").read_text()))
|
||||||
|
NOW = datetime(2026, 10, 28, 19, 30, 8)
|
||||||
|
NIGHT_IN_ZLIN = (-13.3, -101.5) # subsolar point at that moment
|
||||||
|
|
||||||
|
|
||||||
|
class StubPoller:
|
||||||
|
def __init__(self, value=None, version=1, age=60.0):
|
||||||
|
self.value, self.version, self._age = value, version, age
|
||||||
|
self.failures = 0
|
||||||
|
|
||||||
|
def age(self):
|
||||||
|
return self._age
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def view(tle=TLE, clouds=CLOUDS, tle_age=3600.0):
|
||||||
|
return IssView(StubPoller(tle, age=tle_age), StubPoller(clouds))
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_size_is_480x320():
|
||||||
|
assert view().render(NOW).size == (480, 320)
|
||||||
|
|
||||||
|
|
||||||
|
def test_frame_key_changes_every_ten_seconds():
|
||||||
|
v = view()
|
||||||
|
assert v.frame_key(datetime(2026, 10, 28, 19, 30, 0)) == v.frame_key(datetime(2026, 10, 28, 19, 30, 9))
|
||||||
|
assert v.frame_key(datetime(2026, 10, 28, 19, 30, 9)) != v.frame_key(datetime(2026, 10, 28, 19, 30, 10))
|
||||||
|
|
||||||
|
|
||||||
|
def test_frame_key_changes_when_the_orbit_updates():
|
||||||
|
tle = StubPoller(TLE)
|
||||||
|
v = IssView(tle, StubPoller(CLOUDS))
|
||||||
|
before = v.frame_key(NOW)
|
||||||
|
tle.version = 2
|
||||||
|
assert v.frame_key(NOW) != before
|
||||||
|
|
||||||
|
|
||||||
|
def test_nothing_to_patch_between_frames():
|
||||||
|
assert view().patch(NOW) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_map_is_equirectangular_under_the_header():
|
||||||
|
assert map_xy(0, 0) == pytest.approx((240, MAP_TOP + 120))
|
||||||
|
assert map_xy(90, -180) == pytest.approx((0, MAP_TOP))
|
||||||
|
assert map_xy(-90, 180) == pytest.approx((480, MAP_TOP + 240))
|
||||||
|
|
||||||
|
|
||||||
|
def test_day_and_night():
|
||||||
|
assert is_day(0, 0, (0, 0))
|
||||||
|
assert not is_day(0, 180, (0, 0))
|
||||||
|
assert not is_day(49.2, 17.7, NIGHT_IN_ZLIN) # Zlín at 19:30 in October
|
||||||
|
assert is_day(-10, -50, NIGHT_IN_ZLIN) # Brazil in the afternoon
|
||||||
|
|
||||||
|
|
||||||
|
def test_marker_is_where_the_iss_is():
|
||||||
|
img = view().render(NOW)
|
||||||
|
fix = astro.iss_fix(TLE, NOW)
|
||||||
|
x, y = map_xy(fix.lat, fix.lon)
|
||||||
|
assert count_near(img, MARKER, 40, (int(x) - 9, int(y) - 9, int(x) + 10, int(y) + 10)) > 20
|
||||||
|
|
||||||
|
|
||||||
|
def test_without_an_orbit_there_is_no_marker():
|
||||||
|
with_orbit, without = view().render(NOW), view(tle=None).render(NOW)
|
||||||
|
fix = astro.iss_fix(TLE, NOW)
|
||||||
|
x, y = map_xy(fix.lat, fix.lon)
|
||||||
|
box = (int(x) - 9, int(y) - 9, int(x) + 10, int(y) + 10)
|
||||||
|
assert count_near(without, MARKER, 40, box) < count_near(with_orbit, MARKER, 40, box) / 4
|
||||||
|
|
||||||
|
|
||||||
|
def test_stale_tag_only_when_the_orbit_is_old_and_only_in_the_header():
|
||||||
|
fresh = view().render(NOW)
|
||||||
|
old = view(tle_age=4 * 86400).render(NOW)
|
||||||
|
bbox = ImageChops.difference(fresh, old).getbbox()
|
||||||
|
assert bbox is not None and bbox[3] <= MAP_TOP
|
||||||
@@ -81,3 +81,18 @@ def test_slow_fetch_does_not_block_reader():
|
|||||||
finally:
|
finally:
|
||||||
release.set()
|
release.set()
|
||||||
p.stop()
|
p.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_failed_fetch_retries_within_a_minute_by_default():
|
||||||
|
p = Poller(lambda: 1, interval=6 * 3600)
|
||||||
|
assert p.wait_after(ok=True) == 6 * 3600
|
||||||
|
assert p.wait_after(ok=False) == 60
|
||||||
|
|
||||||
|
|
||||||
|
def test_retry_can_be_slower_for_sources_that_ban_eager_clients():
|
||||||
|
p = Poller(lambda: 1, interval=6 * 3600, retry=15 * 60)
|
||||||
|
assert p.wait_after(ok=False) == 15 * 60
|
||||||
|
|
||||||
|
|
||||||
|
def test_retry_never_waits_longer_than_the_interval():
|
||||||
|
assert Poller(lambda: 1, interval=30, retry=15 * 60).wait_after(ok=False) == 30
|
||||||
+12
-5
@@ -3,20 +3,20 @@ import pytest
|
|||||||
from registry import REGISTRY, UnknownView, make_view
|
from registry import REGISTRY, UnknownView, make_view
|
||||||
|
|
||||||
|
|
||||||
def test_registry_has_both_views():
|
def test_registry_has_all_views():
|
||||||
assert sorted(REGISTRY) == ["server", "weather"]
|
assert sorted(REGISTRY) == ["iss", "server", "sky", "weather"]
|
||||||
|
|
||||||
|
|
||||||
def test_make_view_builds_named_views():
|
def test_make_view_builds_named_views():
|
||||||
assert make_view("weather").name == "weather"
|
for name in ("weather", "server", "sky", "iss"):
|
||||||
assert make_view("server").name == "server"
|
assert make_view(name).name == name
|
||||||
|
|
||||||
|
|
||||||
def test_make_view_unknown_lists_valid_names():
|
def test_make_view_unknown_lists_valid_names():
|
||||||
with pytest.raises(UnknownView) as err:
|
with pytest.raises(UnknownView) as err:
|
||||||
make_view("bogus")
|
make_view("bogus")
|
||||||
assert err.value.name == "bogus"
|
assert err.value.name == "bogus"
|
||||||
assert err.value.valid == ["server", "weather"]
|
assert err.value.valid == ["iss", "server", "sky", "weather"]
|
||||||
|
|
||||||
|
|
||||||
def test_make_view_empty_name_is_unknown():
|
def test_make_view_empty_name_is_unknown():
|
||||||
@@ -28,3 +28,10 @@ def test_server_view_polls_every_second_and_weather_every_quarter_hour():
|
|||||||
import registry
|
import registry
|
||||||
assert registry.SERVER_REFRESH_S == 1
|
assert registry.SERVER_REFRESH_S == 1
|
||||||
assert registry.WEATHER_REFRESH_S == 15 * 60
|
assert registry.WEATHER_REFRESH_S == 15 * 60
|
||||||
|
|
||||||
|
|
||||||
|
def test_sky_views_fetch_the_orbit_gently_and_clouds_every_quarter_hour():
|
||||||
|
import registry
|
||||||
|
assert registry.TLE_REFRESH_S == 6 * 3600
|
||||||
|
assert registry.TLE_RETRY_S >= 15 * 60 # CelesTrak blocks clients that retry eagerly
|
||||||
|
assert registry.CLOUDS_REFRESH_S == 15 * 60
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import copy
|
||||||
|
import json
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import sky_data
|
||||||
|
from sky_data import CloudHour, Tle, cloud_at, cloud_story, parse_clouds, parse_tle
|
||||||
|
|
||||||
|
FIXTURES = Path(__file__).parent / "fixtures"
|
||||||
|
TLE_TEXT = (FIXTURES / "celestrak-iss.tle").read_text()
|
||||||
|
CLOUDS = json.loads((FIXTURES / "open-meteo-clouds.json").read_text())
|
||||||
|
|
||||||
|
|
||||||
|
def clouds_payload():
|
||||||
|
return copy.deepcopy(CLOUDS)
|
||||||
|
|
||||||
|
|
||||||
|
class Response:
|
||||||
|
def __init__(self, text="", payload=None):
|
||||||
|
self.text, self._payload = text, payload
|
||||||
|
|
||||||
|
def raise_for_status(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return self._payload
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_tle_from_celestrak():
|
||||||
|
tle = parse_tle(TLE_TEXT)
|
||||||
|
assert tle.name == "ISS (ZARYA)"
|
||||||
|
assert tle.line1.startswith("1 25544U")
|
||||||
|
assert tle.line2.startswith("2 25544 ")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("text", ["", "<html>Too many requests</html>", "ISS\n1 nonsense\n2 nonsense\n",
|
||||||
|
"No GP data found"])
|
||||||
|
def test_parse_tle_rejects_anything_else(text):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
parse_tle(text)
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_tle_asks_for_the_iss_only():
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_get(url, params=None, timeout=None):
|
||||||
|
calls.append((url, params, timeout))
|
||||||
|
return Response(text=TLE_TEXT)
|
||||||
|
|
||||||
|
assert isinstance(sky_data.fetch_tle(get=fake_get), Tle)
|
||||||
|
url, params, timeout = calls[0]
|
||||||
|
assert url.startswith("https://celestrak.org/")
|
||||||
|
assert params == {"CATNR": 25544, "FORMAT": "TLE"}
|
||||||
|
assert timeout == 10
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_clouds():
|
||||||
|
clouds = parse_clouds(clouds_payload())
|
||||||
|
assert len(clouds) == 48
|
||||||
|
assert clouds[0] == CloudHour(datetime(2026, 10, 28, 0, 0), 0)
|
||||||
|
assert clouds[22] == CloudHour(datetime(2026, 10, 28, 22, 0), 82)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_clouds_keeps_nulls_as_none_and_survives_missing_sections():
|
||||||
|
p = clouds_payload()
|
||||||
|
p["hourly"]["cloud_cover"][5] = None
|
||||||
|
assert parse_clouds(p)[5].pct is None
|
||||||
|
assert parse_clouds({}) == ()
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_clouds_asks_for_hourly_cloud_cover_in_zlin():
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_get(url, params=None, timeout=None):
|
||||||
|
calls.append(params)
|
||||||
|
return Response(payload=clouds_payload())
|
||||||
|
|
||||||
|
assert len(sky_data.fetch_clouds(get=fake_get)) == 48
|
||||||
|
params = calls[0]
|
||||||
|
assert (params["latitude"], params["longitude"]) == (49.2265, 17.6627)
|
||||||
|
assert params["hourly"] == "cloud_cover"
|
||||||
|
assert params["timezone"] == "Europe/Prague"
|
||||||
|
|
||||||
|
|
||||||
|
def test_cloud_at_matches_the_hour_containing_the_moment():
|
||||||
|
clouds = parse_clouds(clouds_payload())
|
||||||
|
assert cloud_at(clouds, datetime(2026, 10, 29, 5, 38, 12, 345678)) == 100
|
||||||
|
assert cloud_at(clouds, datetime(2026, 10, 28, 20, 0)) == 31
|
||||||
|
assert cloud_at(clouds, datetime(2026, 11, 5, 20, 0)) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_cloud_story_tonight():
|
||||||
|
clouds = parse_clouds(clouds_payload()) # clear until 19 h, 31 % at 20 h, 82 % at 22 h
|
||||||
|
assert cloud_story(clouds, datetime(2026, 10, 28, 19, 30)) == "Jasno do 20 h, od 22 h zataženo"
|
||||||
|
|
||||||
|
|
||||||
|
def test_cloud_story_other_skies():
|
||||||
|
def flat(pct):
|
||||||
|
return tuple(CloudHour(datetime(2026, 10, 28, h, 0), pct) for h in range(24))
|
||||||
|
|
||||||
|
at = datetime(2026, 10, 28, 8, 15)
|
||||||
|
assert cloud_story(flat(5), at) == "Jasno"
|
||||||
|
assert cloud_story(flat(40), at) == "Polojasno"
|
||||||
|
assert cloud_story(flat(90), at) == "Zataženo"
|
||||||
|
clearing = tuple(CloudHour(datetime(2026, 10, 28, h, 0), 30 if h < 10 else 0) for h in range(24))
|
||||||
|
assert cloud_story(clearing, at) == "Polojasno"
|
||||||
|
assert cloud_story((), at) is None
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import json
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
from PIL import ImageChops
|
||||||
|
|
||||||
|
from astro import Body
|
||||||
|
from sky_data import parse_clouds, parse_tle
|
||||||
|
from sky_view import CX, CY, R, SkyView, dome_xy, panel_rows
|
||||||
|
|
||||||
|
FIXTURES = Path(__file__).parent / "fixtures"
|
||||||
|
TLE = parse_tle((FIXTURES / "celestrak-iss.tle").read_text())
|
||||||
|
CLOUDS = parse_clouds(json.loads((FIXTURES / "open-meteo-clouds.json").read_text()))
|
||||||
|
NOW = datetime(2026, 10, 28, 19, 30, 8)
|
||||||
|
|
||||||
|
|
||||||
|
class StubPoller:
|
||||||
|
def __init__(self, value=None, version=1, age=60.0):
|
||||||
|
self.value, self.version, self._age = value, version, age
|
||||||
|
self.failures = 0
|
||||||
|
|
||||||
|
def age(self):
|
||||||
|
return self._age
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def view(tle=TLE, clouds=CLOUDS, tle_age=3600.0, clouds_age=60.0):
|
||||||
|
return SkyView(StubPoller(tle, age=tle_age), StubPoller(clouds, age=clouds_age))
|
||||||
|
|
||||||
|
|
||||||
|
def brightness(img, box):
|
||||||
|
return float(np.asarray(img.crop(box).convert("L")).mean())
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_size_is_480x320():
|
||||||
|
assert view().render(NOW).size == (480, 320)
|
||||||
|
|
||||||
|
|
||||||
|
def test_frame_key_changes_each_minute_not_each_second():
|
||||||
|
v = view()
|
||||||
|
assert v.frame_key(datetime(2026, 10, 28, 19, 30, 0)) == v.frame_key(datetime(2026, 10, 28, 19, 30, 59))
|
||||||
|
assert v.frame_key(datetime(2026, 10, 28, 19, 30, 59)) != v.frame_key(datetime(2026, 10, 28, 19, 31, 0))
|
||||||
|
|
||||||
|
|
||||||
|
def test_frame_key_changes_when_orbit_or_clouds_update():
|
||||||
|
tle, clouds = StubPoller(TLE), StubPoller(CLOUDS)
|
||||||
|
v = SkyView(tle, clouds)
|
||||||
|
before = v.frame_key(NOW)
|
||||||
|
tle.version = 2
|
||||||
|
assert v.frame_key(NOW) != before
|
||||||
|
before = v.frame_key(NOW)
|
||||||
|
clouds.version = 2
|
||||||
|
assert v.frame_key(NOW) != before
|
||||||
|
|
||||||
|
|
||||||
|
def test_nothing_to_patch_between_minutes():
|
||||||
|
assert view().patch(NOW) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_dome_has_north_up_and_east_on_the_left_like_looking_up():
|
||||||
|
assert dome_xy(90, 0) == pytest.approx((CX, CY))
|
||||||
|
assert dome_xy(0, 0) == pytest.approx((CX, CY - R))
|
||||||
|
assert dome_xy(0, 90) == pytest.approx((CX - R, CY))
|
||||||
|
assert dome_xy(0, 180) == pytest.approx((CX, CY + R))
|
||||||
|
assert dome_xy(45, 270) == pytest.approx((CX + R / 2, CY))
|
||||||
|
|
||||||
|
|
||||||
|
def test_panel_lists_what_is_up_and_what_rises_soon():
|
||||||
|
bodies = (Body("Měsíc", 10.0, 95.0, None), Body("Merkur", -20.0, 250.0, NOW + timedelta(hours=12)),
|
||||||
|
Body("Venuše", -30.0, 270.0, datetime(2026, 10, 29, 6, 6)),
|
||||||
|
Body("Mars", -10.0, 30.0, datetime(2026, 10, 28, 23, 12)),
|
||||||
|
Body("Jupiter", -25.0, 14.0, datetime(2026, 10, 28, 23, 54)), Body("Saturn", 32.4, 140.0, None))
|
||||||
|
assert panel_rows(bodies, 91.2, NOW) == [("Saturn", "32° JV"), ("Měsíc", "91 % · V"), ("Mars", "↑ 23:12"),
|
||||||
|
("Jupiter", "↑ 23:54")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_panel_keeps_the_four_most_useful_rows():
|
||||||
|
up = tuple(Body(name, alt, 180.0, None) for name, alt in (("Merkur", 5.0), ("Venuše", 30.0), ("Mars", 12.0)))
|
||||||
|
rising = (Body("Jupiter", -5.0, 90.0, datetime(2026, 10, 28, 21, 0)),
|
||||||
|
Body("Saturn", -5.0, 90.0, datetime(2026, 10, 28, 20, 0)))
|
||||||
|
assert [name for name, _ in panel_rows(up + rising, 50.0, NOW)] == ["Venuše", "Mars", "Merkur", "Saturn"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_renders_without_orbit_or_clouds_and_still_shows_the_stars():
|
||||||
|
img = view(tle=None, clouds=None).render(NOW)
|
||||||
|
assert img.size == (480, 320)
|
||||||
|
stars = np.asarray(img.crop((CX - R, CY - R, CX + R, CY + R)).convert("L")) > 180
|
||||||
|
assert stars.sum() > 60
|
||||||
|
|
||||||
|
|
||||||
|
def test_stale_tags_only_when_old_and_only_in_the_panel():
|
||||||
|
fresh = view().render(NOW)
|
||||||
|
old = view(tle_age=4 * 86400, clouds_age=2 * 3600).render(NOW)
|
||||||
|
bbox = ImageChops.difference(fresh, old).getbbox()
|
||||||
|
assert bbox is not None and bbox[0] >= 320
|
||||||
|
|
||||||
|
|
||||||
|
def test_daytime_sky_is_lighter_than_the_night():
|
||||||
|
day = view().render(datetime(2026, 10, 28, 12, 0))
|
||||||
|
night = view().render(NOW)
|
||||||
|
box = (CX - 100, CY - 100, CX + 100, CY + 100)
|
||||||
|
assert brightness(day, box) > brightness(night, box) + 10
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
import skykit
|
||||||
|
from tests.helpers import count_colour
|
||||||
|
|
||||||
|
LIT, DARK, BG = (255, 255, 255), (40, 40, 40), (0, 0, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def moon(pct, waxing):
|
||||||
|
img = Image.new("RGB", (40, 40), BG)
|
||||||
|
skykit.moon_disc(img, 20, 20, 16, pct, waxing, lit=LIT, dark=DARK)
|
||||||
|
return img
|
||||||
|
|
||||||
|
|
||||||
|
def lit(img, box=None):
|
||||||
|
return count_colour(img, LIT, box)
|
||||||
|
|
||||||
|
|
||||||
|
def test_waxing_moon_is_lit_on_the_right_waning_on_the_left():
|
||||||
|
waxing, waning = moon(50, True), moon(50, False)
|
||||||
|
assert lit(waxing, (20, 0, 40, 40)) > 10 * max(1, lit(waxing, (0, 0, 20, 40)))
|
||||||
|
assert lit(waning, (0, 0, 20, 40)) > 10 * max(1, lit(waning, (20, 0, 40, 40)))
|
||||||
|
|
||||||
|
|
||||||
|
def test_lit_area_grows_with_illumination():
|
||||||
|
areas = [lit(moon(pct, True)) for pct in (0, 10, 50, 90, 100)]
|
||||||
|
assert areas == sorted(areas)
|
||||||
|
assert areas[0] == 0
|
||||||
|
assert areas[-1] > 0.9 * 3.14 * 16 * 16
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from timeutil import from_utc, to_utc
|
||||||
|
|
||||||
|
|
||||||
|
def test_to_utc_in_winter_and_summer_time():
|
||||||
|
assert to_utc(datetime(2026, 10, 28, 19, 30), "Europe/Prague") == datetime(2026, 10, 28, 18, 30)
|
||||||
|
assert to_utc(datetime(2026, 10, 22, 12, 0), "Europe/Prague") == datetime(2026, 10, 22, 10, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_from_utc_in_winter_and_summer_time():
|
||||||
|
assert from_utc(datetime(2026, 10, 28, 18, 30), "Europe/Prague") == datetime(2026, 10, 28, 19, 30)
|
||||||
|
assert from_utc(datetime(2026, 10, 22, 10, 0), "Europe/Prague") == datetime(2026, 10, 22, 12, 0)
|
||||||
+16
-3
@@ -1,12 +1,25 @@
|
|||||||
"""Wall-clock time independent of the container's own TZ."""
|
"""Wall-clock time independent of the container's own TZ."""
|
||||||
import os
|
import os
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
from zoneinfo import ZoneInfo
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
DEFAULT_TZ = "Europe/Prague"
|
DEFAULT_TZ = "Europe/Prague"
|
||||||
|
|
||||||
|
|
||||||
|
def _zone(tz_name: str | None) -> ZoneInfo:
|
||||||
|
return ZoneInfo(tz_name or os.environ.get("BOARD_TZ", DEFAULT_TZ))
|
||||||
|
|
||||||
|
|
||||||
def local_now(tz_name: str | None = None) -> datetime:
|
def local_now(tz_name: str | None = None) -> datetime:
|
||||||
"""Naive wall-clock time in `tz_name` (default: env BOARD_TZ, else Europe/Prague)."""
|
"""Naive wall-clock time in `tz_name` (default: env BOARD_TZ, else Europe/Prague)."""
|
||||||
name = tz_name or os.environ.get("BOARD_TZ", DEFAULT_TZ)
|
return datetime.now(_zone(tz_name)).replace(tzinfo=None)
|
||||||
return datetime.now(ZoneInfo(name)).replace(tzinfo=None)
|
|
||||||
|
|
||||||
|
def to_utc(local: datetime, tz_name: str | None = None) -> datetime:
|
||||||
|
"""Naive wall-clock time in `tz_name` as naive UTC."""
|
||||||
|
return local.replace(tzinfo=_zone(tz_name)).astimezone(timezone.utc).replace(tzinfo=None)
|
||||||
|
|
||||||
|
|
||||||
|
def from_utc(utc: datetime, tz_name: str | None = None) -> datetime:
|
||||||
|
"""Naive UTC as naive wall-clock time in `tz_name`."""
|
||||||
|
return utc.replace(tzinfo=timezone.utc).astimezone(_zone(tz_name)).replace(tzinfo=None)
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""Bake assets/world_land.png (480x240, white = land) from Natural Earth's 1:110m land polygons (public domain).
|
||||||
|
|
||||||
|
Run once by hand: .venv/bin/python tools/bake_world_map.py
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import requests
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
SOURCE = "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_110m_land.geojson"
|
||||||
|
OUT = Path(__file__).resolve().parent.parent / "assets" / "world_land.png"
|
||||||
|
W, H = 480, 240 # equirectangular: 0.75° per pixel
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
features = requests.get(SOURCE, timeout=30).json()["features"]
|
||||||
|
mask = Image.new("1", (W, H), 0)
|
||||||
|
d = ImageDraw.Draw(mask)
|
||||||
|
for feature in features:
|
||||||
|
geometry = feature["geometry"]
|
||||||
|
polygons = geometry["coordinates"] if geometry["type"] == "MultiPolygon" else [geometry["coordinates"]]
|
||||||
|
for polygon in polygons:
|
||||||
|
d.polygon([((lon + 180) / 360 * W, (90 - lat) / 180 * H) for lon, lat in polygon[0]], fill=1)
|
||||||
|
mask.save(OUT, optimize=True)
|
||||||
|
print(OUT, OUT.stat().st_size, "bytes")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in new issue
Block a user