Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
472fe84d1b | ||
|
|
581d12324d | ||
|
|
70b02f865d | ||
|
|
0289150361 | ||
|
|
d093a8747e | ||
|
|
72e8a69b02 | ||
|
|
d0adefe954 | ||
|
|
517f0868db | ||
|
|
0de68bfce0 | ||
|
|
2132262896 | ||
|
|
6c9a1420d2 | ||
|
|
45508b1b68 | ||
|
|
5e64bfb64e | ||
|
|
edba341f30 | ||
|
|
c3a42cf35b |
No files matched your search
@@ -1,20 +1,24 @@
|
|||||||
# second-screen
|
# second-screen
|
||||||
|
|
||||||
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**, drawn in the style of a
|
(`bus-department-schedule`). One Docker container shows **one view at a time**: a Casio digital watch (slanted
|
||||||
Casio digital watch (slanted 7-segment digits, pale LCD green):
|
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, a star chart of tonight's sky and an ISS tracker:
|
||||||
|
|
||||||
| `VIEW` | Shows |
|
| `VIEW` | Shows |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `weather` | Czech weekday strip, big `HH:MM` with seconds, date, current weather for Zlín, today's max/min, highest rain chance and a 12-hour rain probability bar graph with the total mm |
|
| `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) |
|
||||||
| `server` | CPU / RAM / disk bars, load, CPU temperature, uptime, Docker containers (readable names and status) and the busiest processes |
|
| `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 (75° N to 60° S, the ISS never leaves ±51.6°): where the ISS is now, its ground track 40 minutes back and 95 ahead, Zlín, height, speed and position. Below it, in large type, the next pass visible from Zlín: time and date, highest point, direction, estimated brightness (magnitude) and 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 |
|
||||||
|
|
||||||
Design: `docs/superpowers/specs/2026-10-22-second-screen-design.md`.
|
Design: `docs/superpowers/specs/2026-10-22-second-screen-design.md`.
|
||||||
Plan: `docs/superpowers/plans/2026-10-22-second-screen.md`. Previews: `docs/previews/`.
|
Plan: `docs/superpowers/plans/2026-10-22-second-screen.md`. Previews: `docs/previews/`.
|
||||||
|
|
||||||
## Switching views
|
## Switching views
|
||||||
|
|
||||||
Edit `VIEW:` in `docker-compose.yml`, commit, `git push`, press **Deploy** in Coolify. An unknown or missing
|
Edit `VIEW:` in `docker-compose.yml`, commit and `git push`. Coolify deploys every push to `main` by itself and
|
||||||
|
reads `docker-compose.yml` from the repository again on each deploy (see Deployment). An unknown or missing
|
||||||
`VIEW` shows an error screen naming the valid views and keeps the container idle (no restart loop).
|
`VIEW` shows an error screen naming the valid views and keeps the container idle (no restart loop).
|
||||||
|
|
||||||
## Add a view
|
## Add a view
|
||||||
@@ -28,7 +32,7 @@ Edit `VIEW:` in `docker-compose.yml`, commit, `git push`, press **Deploy** in Co
|
|||||||
|
|
||||||
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)
|
||||||
|
|
||||||
@@ -36,7 +40,13 @@ Edit `VIEW:` in `docker-compose.yml`, commit, `git push`, press **Deploy** in Co
|
|||||||
so Coolify cannot use a deploy key.
|
so Coolify cannot use a deploy key.
|
||||||
- Build pack **Docker Compose**, base directory `/`, **Docker Compose Location `/docker-compose.yml`**.
|
- Build pack **Docker Compose**, base directory `/`, **Docker Compose Location `/docker-compose.yml`**.
|
||||||
- No domain and no environment variables: the defaults in `docker-compose.yml` fit this server.
|
- No domain and no environment variables: the defaults in `docker-compose.yml` fit this server.
|
||||||
- **Update:** commit, `git push`, press **Deploy** (no webhook).
|
- **Update:** commit and `git push`. A Gitea webhook (repository → Settings → Webhooks, "Coolify second-screen
|
||||||
|
deploy main") posts every push to `main` to `https://coolify.madeinzlin.cz/webhooks/source/gitea/events/manual`,
|
||||||
|
signed with the app's Gitea secret from Coolify (application → Webhooks → Manual Git webhooks → Gitea). Coolify
|
||||||
|
checks the signature and deploys. Since Coolify 4.5.3 every deploy reads `docker-compose.yml` from the repository
|
||||||
|
again, so **Reload Compose** is no longer needed. Check a deploy in Coolify → Deployment Logs (it says
|
||||||
|
**Webhook**) or with `ssh coolify 'docker ps'`. **Redeploy** in Coolify still works by hand.
|
||||||
|
- A push deploys nothing when every commit in it has `[skip ci]` or `[skip cd]` in its message.
|
||||||
- **Logs:** Coolify → the application → Logs, or `ssh coolify 'docker logs --tail 30 <container>'`.
|
- **Logs:** Coolify → the application → Logs, or `ssh coolify 'docker logs --tail 30 <container>'`.
|
||||||
- Only one container can hold a screen's serial port. Stop manual copies before deploying.
|
- Only one container can hold a screen's serial port. Stop manual copies before deploying.
|
||||||
|
|
||||||
@@ -62,14 +72,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 |
|
||||||
@@ -81,7 +92,31 @@ The screen library is pinned to one upstream commit in the `Dockerfile` (`LCD_CO
|
|||||||
## Known limitations
|
## Known limitations
|
||||||
|
|
||||||
- Weather comes from Open-Meteo for Zlín only (coordinates in `weather_data.py`), refreshed every 15 minutes.
|
- Weather comes from Open-Meteo for Zlín only (coordinates in `weather_data.py`), refreshed every 15 minutes.
|
||||||
|
- Night mode uses the forecast's sunrise and sunset for today. If the forecast has no today (fetches failing for
|
||||||
|
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).
|
||||||
- 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.
|
||||||
|
- ISS brightness is an estimate: the brightest moment of the pass by Robert Matson's formula for a diffusely
|
||||||
|
reflecting sphere, from the distance and the sun–ISS–observer angle, with a standard magnitude of −1.8 at 1000 km
|
||||||
|
(`ISS_STD_MAG` in `astro.py`, observers quote −1.3 to −1.8). The real ISS is not a sphere and the angle of its
|
||||||
|
solar panels changes, so a pass can differ by about a magnitude.
|
||||||
- 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.
|
||||||
- Seconds are redrawn once per second with a small partial update.
|
- 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),
|
||||||
|
and time grows with the bytes sent. So after the first frame the runner sends only the rectangles that changed
|
||||||
|
(`regions.py`), a full frame when more than 60 % of the screen changed or after any failed push, and a full refresh
|
||||||
|
every 15 minutes. The weather seconds are a small patch once per second.
|
||||||
|
|
||||||
|
## Fonts
|
||||||
|
|
||||||
|
`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;
|
||||||
|
`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.
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
Copyright (c) 2014, Indian Type Foundry ([email protected]).
|
||||||
|
|
||||||
|
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:
|
||||||
|
http://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.
|
||||||
|
After Width: | Height: | Size: 2.8 KiB |
@@ -0,0 +1,211 @@
|
|||||||
|
"""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
|
||||||
|
ISS_STD_MAG = -1.8 # brightness at 1000 km and a 90° phase angle; observers quote -1.3 to -1.8
|
||||||
|
PASS_STEP_S = 10 # how finely a pass is sampled to find when it is visible and how bright
|
||||||
|
PASS_MIN_ALT = 10 # degrees; a pass counts from here up, as on Heavens-Above and Clear Outside
|
||||||
|
|
||||||
|
|
||||||
|
@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
|
||||||
|
mag: float # estimated magnitude at the brightest moment (lower is brighter)
|
||||||
|
|
||||||
|
|
||||||
|
@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, _, _, _, set_, _ = o.next_pass(iss)
|
||||||
|
if rise is None or set_ is None or rise > limit:
|
||||||
|
return None
|
||||||
|
seen = _visible_part(iss, sun, o, rise, set_)
|
||||||
|
if seen:
|
||||||
|
start, end = seen[0], seen[-1]
|
||||||
|
return Pass(_local(start[0]), max(alt for _, alt, _, _ in seen), start[2], end[2], True,
|
||||||
|
min(mag for *_, mag in seen))
|
||||||
|
o.date = set_ + ephem.minute
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _visible_part(iss: ephem.EarthSatellite, sun: ephem.Sun, o: ephem.Observer, rise,
|
||||||
|
set_) -> list[tuple[ephem.Date, float, float, float]]:
|
||||||
|
"""(date, alt, az, magnitude) every PASS_STEP_S while the ISS is high enough, sunlit and the sky here dark.
|
||||||
|
|
||||||
|
A pass often starts in daylight or ends in the earth's shadow well before it sets, so only this part is seen.
|
||||||
|
"""
|
||||||
|
seen = []
|
||||||
|
t = rise
|
||||||
|
while t <= set_:
|
||||||
|
o.date = t
|
||||||
|
iss.compute(o)
|
||||||
|
sun.compute(o)
|
||||||
|
if math.degrees(iss.alt) >= PASS_MIN_ALT and not iss.eclipsed and math.degrees(sun.alt) < VISIBLE_SUN_ALT:
|
||||||
|
seen.append((ephem.Date(t), math.degrees(iss.alt), math.degrees(iss.az),
|
||||||
|
magnitude(iss.range / 1000, _phase(iss, sun))))
|
||||||
|
t += PASS_STEP_S * ephem.second
|
||||||
|
return seen
|
||||||
|
|
||||||
|
|
||||||
|
def magnitude(range_km: float, phase: float, std_mag: float = ISS_STD_MAG) -> float:
|
||||||
|
"""Estimated magnitude of a satellite seen as a diffusely reflecting sphere (Robert Matson's formula).
|
||||||
|
|
||||||
|
`phase` is the sun–satellite–observer angle in radians: 0 when fully lit as seen from here, π when only its
|
||||||
|
unlit side faces us.
|
||||||
|
"""
|
||||||
|
lit = max(1e-6, math.sin(phase) + (math.pi - phase) * math.cos(phase))
|
||||||
|
return std_mag - 15 + 5 * math.log10(range_km) - 2.5 * math.log10(lit)
|
||||||
|
|
||||||
|
|
||||||
|
def _unit(alt: float, az: float) -> tuple[float, float, float]:
|
||||||
|
return math.cos(alt) * math.sin(az), math.cos(alt) * math.cos(az), math.sin(alt)
|
||||||
|
|
||||||
|
|
||||||
|
def _phase(sat: ephem.EarthSatellite, sun: ephem.Sun) -> float:
|
||||||
|
"""The sun is so far away that its direction from the satellite is the same as from here."""
|
||||||
|
cos = -sum(a * b for a, b in zip(_unit(sat.alt, sat.az), _unit(sun.alt, sun.az)))
|
||||||
|
return math.acos(max(-1.0, min(1.0, cos)))
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""Cyberpunk-2077-style drawing kit: black scanlined background, yellow/cyan/red, chamfered shapes, glitch text."""
|
||||||
|
from functools import lru_cache
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Sequence
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
|
|
||||||
|
W, H = 480, 320
|
||||||
|
BG = (9, 9, 14)
|
||||||
|
SCAN = (13, 13, 20)
|
||||||
|
YELLOW = (252, 238, 10)
|
||||||
|
CYAN = (0, 240, 255)
|
||||||
|
RED = (255, 38, 74)
|
||||||
|
MAGENTA = (255, 0, 160)
|
||||||
|
DIM = (38, 38, 52)
|
||||||
|
TEXT = (226, 226, 232)
|
||||||
|
GREY = (120, 120, 140)
|
||||||
|
INK = (10, 10, 10)
|
||||||
|
|
||||||
|
FONT_DIR = Path(__file__).parent / "assets" / "fonts"
|
||||||
|
HOT_FROM = 80 # gauges turn red at this percentage
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=None)
|
||||||
|
def font(size: int, bold: bool = True) -> ImageFont.FreeTypeFont:
|
||||||
|
return ImageFont.truetype(str(FONT_DIR / ("Rajdhani-Bold.ttf" if bold else "Rajdhani-SemiBold.ttf")), size)
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def _background() -> Image.Image:
|
||||||
|
img = Image.new("RGB", (W, H), BG)
|
||||||
|
d = ImageDraw.Draw(img)
|
||||||
|
for y in range(0, H, 3):
|
||||||
|
d.line((0, y, W, y), fill=SCAN)
|
||||||
|
return img
|
||||||
|
|
||||||
|
|
||||||
|
def background() -> Image.Image:
|
||||||
|
"""A fresh copy of the scanlined black background."""
|
||||||
|
return _background().copy()
|
||||||
|
|
||||||
|
|
||||||
|
def chamfer(d: ImageDraw.ImageDraw, box: tuple[int, int, int, int], cut: int, outline=None, fill=None,
|
||||||
|
width: int = 1, cuts: str = "tl br") -> None:
|
||||||
|
"""A rectangle with the named corners (tl tr br bl) cut off at 45 degrees."""
|
||||||
|
x0, y0, x1, y1 = box
|
||||||
|
c = cut
|
||||||
|
pts: list[tuple[int, int]] = []
|
||||||
|
pts.append((x0 + c, y0) if "tl" in cuts else (x0, y0))
|
||||||
|
pts.append((x1 - c, y0) if "tr" in cuts else (x1, y0))
|
||||||
|
if "tr" in cuts:
|
||||||
|
pts.append((x1, y0 + c))
|
||||||
|
pts.append((x1, y1 - c) if "br" in cuts else (x1, y1))
|
||||||
|
if "br" in cuts:
|
||||||
|
pts.append((x1 - c, y1))
|
||||||
|
pts.append((x0 + c, y1) if "bl" in cuts else (x0, y1))
|
||||||
|
if "bl" in cuts:
|
||||||
|
pts.append((x0, y1 - c))
|
||||||
|
if "tl" in cuts:
|
||||||
|
pts.append((x0, y0 + c))
|
||||||
|
if fill is not None:
|
||||||
|
d.polygon(pts, fill=fill)
|
||||||
|
if outline is not None:
|
||||||
|
d.line(pts + [pts[0]], fill=outline, width=width)
|
||||||
|
|
||||||
|
|
||||||
|
def glitch_text(d: ImageDraw.ImageDraw, xy: tuple[float, float], text: str, f, main=YELLOW) -> None:
|
||||||
|
"""Text with a cyan and a red copy offset to either side (chromatic aberration)."""
|
||||||
|
x, y = xy
|
||||||
|
d.text((x - 1.5, y), text, font=f, fill=CYAN)
|
||||||
|
d.text((x + 1.5, y), text, font=f, fill=RED)
|
||||||
|
d.text((x, y), text, font=f, fill=main)
|
||||||
|
|
||||||
|
|
||||||
|
def slanted_bar(d: ImageDraw.ImageDraw, x: float, y: float, pct: float | None, h: float, n: int,
|
||||||
|
seg_w: float, gap: float, slant: float = 5, hot: float = HOT_FROM) -> None:
|
||||||
|
"""Segmented bar of slanted parallelograms: yellow, red from `hot` percent, unlit segments dark."""
|
||||||
|
lit = 0 if pct is None else max(0, min(n, round(pct / 100 * n)))
|
||||||
|
colour = RED if pct is not None and pct >= hot else YELLOW
|
||||||
|
for i in range(n):
|
||||||
|
x0 = x + i * (seg_w + gap)
|
||||||
|
d.polygon([(x0 + slant, y), (x0 + seg_w + slant, y), (x0 + seg_w, y + h), (x0, y + h)],
|
||||||
|
fill=colour if i < lit else DIM)
|
||||||
|
|
||||||
|
|
||||||
|
def tag(d: ImageDraw.ImageDraw, xy: tuple[int, int], text: str, f, colour=YELLOW, ink=INK) -> tuple[int, int, int, int]:
|
||||||
|
"""A chamfered label sized from its text; returns its box."""
|
||||||
|
left, top, right, bottom = d.textbbox((0, 0), text, font=f)
|
||||||
|
x, y = xy
|
||||||
|
box = (x, y, x + (right - left) + 20, y + (bottom - top) + 8)
|
||||||
|
chamfer(d, box, 7, fill=colour, cuts="tl br")
|
||||||
|
d.text((x + 10 - left, y + 4 - top), text, font=f, fill=ink)
|
||||||
|
return box
|
||||||
|
|
||||||
|
|
||||||
|
def fit(d: ImageDraw.ImageDraw, text: str, f, max_w: float) -> str:
|
||||||
|
"""`text`, shortened with an ellipsis until it is at most max_w pixels wide."""
|
||||||
|
if d.textlength(text, font=f) <= max_w:
|
||||||
|
return text
|
||||||
|
while text and d.textlength(text + "…", font=f) > max_w:
|
||||||
|
text = text[:-1]
|
||||||
|
return text + "…"
|
||||||
|
|
||||||
|
|
||||||
|
def hazard_stripe(d: ImageDraw.ImageDraw, x: int, y: int, length: int, h: int = 6, step: int = 12) -> None:
|
||||||
|
"""Yellow diagonal hazard stripes."""
|
||||||
|
for i in range(0, length, step * 2):
|
||||||
|
d.polygon([(x + i, y), (x + i + step, y), (x + i + step - h, y + h), (x + i - h, y + h)], fill=YELLOW)
|
||||||
@@ -3,7 +3,7 @@ services:
|
|||||||
build: .
|
build: .
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
# Which view to show: weather | server. To switch: edit, commit, push, press Deploy in Coolify.
|
# Which view to show: weather | server | sky | iss. To switch: edit, commit, push (Coolify deploys on push).
|
||||||
VIEW: weather
|
VIEW: weather
|
||||||
# Prefer the stable by-id path (see README); /dev/ttyACM1 can change after replug/reboot.
|
# Prefer the stable by-id path (see README); /dev/ttyACM1 can change after replug/reboot.
|
||||||
SCREEN_DEVICE: ${SCREEN_DEVICE:-/dev/serial/by-id/usb-Turing_UsbMonitor_USB35INCHIPSV2-if00}
|
SCREEN_DEVICE: ${SCREEN_DEVICE:-/dev/serial/by-id/usb-Turing_UsbMonitor_USB35INCHIPSV2-if00}
|
||||||
|
|||||||
|
After Width: | Height: | Size: 57 KiB |
|
Before Width: | Height: | Size: 64 KiB After Width: | Height: | Size: 91 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
Before Width: | Height: | Size: 31 KiB After Width: | Height: | Size: 51 KiB |
@@ -171,3 +171,25 @@ Reading host processes may need `pid: host`; builder decides the narrowest setup
|
|||||||
dropping the top-processes section.
|
dropping the top-processes section.
|
||||||
- **Gitea repo creation and removal of the `apod-test` leftovers** are not yet answered by the
|
- **Gitea repo creation and removal of the `apod-test` leftovers** are not yet answered by the
|
||||||
owner: do not create the remote repo, push, or delete anything on the server without asking.
|
owner: do not create the remote repo, push, or delete anything on the server without asking.
|
||||||
|
|
||||||
|
## Addendum 2026-10-22: server view restyle and refresh rate
|
||||||
|
|
||||||
|
After deployment the owner asked for the server view in a **Cyberpunk 2077** style (approved from a mockup:
|
||||||
|
black scanlined background, yellow/cyan/red, chamfered shapes, glitch-offset numbers, Rajdhani font) and a
|
||||||
|
faster refresh than 5 s. The screen link moves about 150 KB/s (measured), so the runner now sends only the changed
|
||||||
|
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
|
||||||
|
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.
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
"""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")
|
||||||
@@ -3,13 +3,16 @@ from functools import lru_cache
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Sequence
|
from typing import Sequence
|
||||||
|
|
||||||
from PIL import ImageDraw, ImageFont
|
import numpy as np
|
||||||
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
|
|
||||||
W, H = 480, 320
|
W, H = 480, 320
|
||||||
BG = (170, 184, 154)
|
BG = (170, 184, 154)
|
||||||
INK = (28, 36, 24)
|
INK = (28, 36, 24)
|
||||||
GHOST = (158, 172, 143) # unlit segments, barely darker than the background
|
GHOST = (158, 172, 143) # unlit segments, barely darker than the background
|
||||||
SLANT = 0.14
|
SLANT = 0.14
|
||||||
|
NIGHT_BG = (12, 15, 12) # reverse LCD: light segments on black
|
||||||
|
NIGHT_INK = (196, 214, 184)
|
||||||
|
|
||||||
FONT_PATH = Path(__file__).parent / "assets" / "fonts" / "Roboto-Bold.ttf"
|
FONT_PATH = Path(__file__).parent / "assets" / "fonts" / "Roboto-Bold.ttf"
|
||||||
SEGMENT_GAP = 1.5
|
SEGMENT_GAP = 1.5
|
||||||
@@ -20,6 +23,14 @@ DIGIT_SEGMENTS = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def night(img: Image.Image) -> Image.Image:
|
||||||
|
"""The same frame as a reverse LCD: background becomes NIGHT_BG, ink NIGHT_INK, everything between in step."""
|
||||||
|
a = np.asarray(img.convert("RGB")).astype(np.float32)
|
||||||
|
t = np.clip((a[..., 0] - INK[0]) / (BG[0] - INK[0]), 0, 1)[..., None] # 0 at ink, 1 at background
|
||||||
|
ink, bg = np.array(NIGHT_INK, np.float32), np.array(NIGHT_BG, np.float32)
|
||||||
|
return Image.fromarray(np.round(ink + (bg - ink) * t).astype(np.uint8))
|
||||||
|
|
||||||
|
|
||||||
def _slant(points: Sequence[tuple[float, float]], base_y: float) -> list[tuple[float, float]]:
|
def _slant(points: Sequence[tuple[float, float]], base_y: float) -> list[tuple[float, float]]:
|
||||||
return [(x + SLANT * (base_y - y), y) for x, y in points]
|
return [(x + SLANT * (base_y - y), y) for x, y in points]
|
||||||
|
|
||||||
|
|||||||
@@ -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))
|
|
||||||
@@ -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)."""
|
||||||
from datetime import datetime
|
import json
|
||||||
|
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 weather_data import Hour, Weather
|
from sky_data import parse_clouds, parse_tle
|
||||||
|
from sky_view import SkyView
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
@@ -28,10 +34,18 @@ class FakePoller:
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
WEEK = ((2, 16.0, 7.0), (3, 13.0, 8.0), (61, 11.0, 6.0), (80, 9.0, 4.0), (0, 12.0, 2.0), (1, 14.0, 5.0),
|
||||||
|
(71, 4.0, -1.0))
|
||||||
|
|
||||||
|
|
||||||
def fake_weather(temp=14.2, rain=(0, 0, 10, 20, 40, 70, 60, 50, 30, 20, 10, 0), code=2) -> Weather:
|
def fake_weather(temp=14.2, rain=(0, 0, 10, 20, 40, 70, 60, 50, 30, 20, 10, 0), code=2) -> Weather:
|
||||||
hours = tuple(Hour(datetime(2026, 10, 22, 14 + i, 0) if 14 + i < 24 else datetime(2026, 10, 23, 14 + i - 24, 0),
|
hours = tuple(Hour(datetime(2026, 10, 22, 14 + i, 0) if 14 + i < 24 else datetime(2026, 10, 23, 14 + i - 24, 0),
|
||||||
p, 0.3) for i, p in enumerate(rain))
|
p, 0.3) for i, p in enumerate(rain))
|
||||||
return Weather(temp=temp, code=code, today_max=16.0, today_min=7.0, hours=hours)
|
days = tuple(Day(date(2026, 10, 22) + timedelta(days=i), c, hi, lo,
|
||||||
|
datetime.combine(date(2026, 10, 22) + timedelta(days=i), time(7, 20)),
|
||||||
|
datetime.combine(date(2026, 10, 22) + timedelta(days=i), time(17, 45)))
|
||||||
|
for i, (c, hi, lo) in enumerate(WEEK))
|
||||||
|
return Weather(temp=temp, feels=temp - 2.1, code=code, days=days, hours=hours)
|
||||||
|
|
||||||
|
|
||||||
def sheet(images: list[Image.Image], columns: int = 2) -> Image.Image:
|
def sheet(images: list[Image.Image], columns: int = 2) -> Image.Image:
|
||||||
@@ -44,12 +58,13 @@ def sheet(images: list[Image.Image], columns: int = 2) -> Image.Image:
|
|||||||
|
|
||||||
def weather_previews() -> Image.Image:
|
def weather_previews() -> Image.Image:
|
||||||
cases = [
|
cases = [
|
||||||
FakePoller(fake_weather()),
|
(FakePoller(fake_weather()), NOW),
|
||||||
FakePoller(fake_weather(temp=-3.4, rain=(100,) * 12, code=71)),
|
(FakePoller(fake_weather(temp=-3.4, rain=(100,) * 12, code=71)), NOW),
|
||||||
FakePoller(None, age=None),
|
(FakePoller(None, age=None), NOW),
|
||||||
FakePoller(fake_weather(code=95), age=7200.0),
|
(FakePoller(fake_weather(code=95), age=7200.0), NOW),
|
||||||
|
(FakePoller(fake_weather()), NOW.replace(hour=21, minute=7)), # after sunset: reverse LCD
|
||||||
]
|
]
|
||||||
return sheet([WeatherView(p).render(NOW) for p in cases])
|
return sheet([WeatherView(p).render(now) for p, now in cases])
|
||||||
|
|
||||||
|
|
||||||
REAL_NAMES = ["coolify", "coolify-db", "coolify-redis", "coolify-sentinel", "gitea", "jn5mdu87", "task-runners",
|
REAL_NAMES = ["coolify", "coolify-db", "coolify-redis", "coolify-sentinel", "gitea", "jn5mdu87", "task-runners",
|
||||||
@@ -79,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")
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""Find what changed between two frames, so only that is sent over the slow serial link."""
|
||||||
|
from PIL import Image, ImageChops
|
||||||
|
|
||||||
|
TILE = 32
|
||||||
|
|
||||||
|
Box = tuple[int, int, int, int] # x0, y0, x1, y1 (x1, y1 exclusive)
|
||||||
|
|
||||||
|
|
||||||
|
def changed_regions(old: Image.Image, new: Image.Image, tile: int = TILE) -> list[Box]:
|
||||||
|
"""Tight boxes around the pixels that differ.
|
||||||
|
|
||||||
|
The frame is cut into tiles; consecutive changed tiles in one tile row become a single box, trimmed to the
|
||||||
|
pixels that actually changed. The screen's link costs time per byte only, so many small boxes are fine.
|
||||||
|
"""
|
||||||
|
if old.size != new.size:
|
||||||
|
raise ValueError(f"size mismatch: {old.size} vs {new.size}")
|
||||||
|
diff = ImageChops.difference(old.convert("RGB"), new.convert("RGB"))
|
||||||
|
if diff.getbbox() is None:
|
||||||
|
return []
|
||||||
|
width, height = diff.size
|
||||||
|
boxes: list[Box] = []
|
||||||
|
for ty in range(0, height, tile):
|
||||||
|
run: Box | None = None
|
||||||
|
for tx in range(0, width, tile):
|
||||||
|
inner = diff.crop((tx, ty, min(tx + tile, width), min(ty + tile, height))).getbbox()
|
||||||
|
if inner is not None:
|
||||||
|
box = (tx + inner[0], ty + inner[1], tx + inner[2], ty + inner[3])
|
||||||
|
run = box if run is None else (min(run[0], box[0]), min(run[1], box[1]),
|
||||||
|
max(run[2], box[2]), max(run[3], box[3]))
|
||||||
|
elif run is not None:
|
||||||
|
boxes.append(run)
|
||||||
|
run = None
|
||||||
|
if run is not None:
|
||||||
|
boxes.append(run)
|
||||||
|
return boxes
|
||||||
@@ -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
|
||||||
@@ -10,7 +13,10 @@ from weather_data import fetch_weather
|
|||||||
from weather_view import WeatherView
|
from weather_view import WeatherView
|
||||||
|
|
||||||
WEATHER_REFRESH_S = 15 * 60
|
WEATHER_REFRESH_S = 15 * 60
|
||||||
SERVER_REFRESH_S = 5
|
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
|
||||||
@@ -8,12 +8,15 @@ from PIL import Image, ImageDraw
|
|||||||
|
|
||||||
import lcdkit
|
import lcdkit
|
||||||
from lcdkit import BG, H, INK, W
|
from lcdkit import BG, H, INK, W
|
||||||
|
from regions import changed_regions
|
||||||
from view import View
|
from view import View
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
TICK_S = 0.05
|
TICK_S = 0.05
|
||||||
OPEN_RETRY_S = 30.0
|
OPEN_RETRY_S = 30.0
|
||||||
|
FULL_REFRESH_S = 900.0 # resend the whole frame this often, so a glitch on the link cannot stay on the screen
|
||||||
|
FULL_FRAME_ABOVE = 0.6 # when more than this share of the screen changed, one full frame is simpler
|
||||||
|
|
||||||
|
|
||||||
def render_error(lines: Sequence[str]) -> Image.Image:
|
def render_error(lines: Sequence[str]) -> Image.Image:
|
||||||
@@ -55,28 +58,51 @@ def idle_with_message(lcd, lines: Sequence[str], *, running: Callable[[], bool],
|
|||||||
sleep(0.5)
|
sleep(0.5)
|
||||||
|
|
||||||
|
|
||||||
|
def _push_frame(lcd, shown: Image.Image | None, frame: Image.Image, force_full: bool) -> bool:
|
||||||
|
"""Bring the screen from `shown` (None: unknown) to `frame`. Returns True if a full frame was sent."""
|
||||||
|
if shown is not None and not force_full:
|
||||||
|
boxes = changed_regions(shown, frame)
|
||||||
|
changed = sum((x1 - x0) * (y1 - y0) for x0, y0, x1, y1 in boxes)
|
||||||
|
if changed <= FULL_FRAME_ABOVE * frame.width * frame.height:
|
||||||
|
for x0, y0, x1, y1 in boxes:
|
||||||
|
lcd.DisplayPILImage(frame.crop((x0, y0, x1, y1)), x0, y0)
|
||||||
|
return False
|
||||||
|
lcd.DisplayPILImage(frame, 0, 0)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
def run(view: View, lcd, *, now_fn: Callable[[], datetime], running: Callable[[], bool],
|
def run(view: View, lcd, *, now_fn: Callable[[], datetime], running: Callable[[], bool],
|
||||||
sleep: Callable[[float], None] = time.sleep, max_failures: int = 10) -> None:
|
sleep: Callable[[float], None] = time.sleep, max_failures: int = 10,
|
||||||
|
full_refresh_s: float = FULL_REFRESH_S, monotonic: Callable[[], float] = time.monotonic) -> None:
|
||||||
last_key = None
|
last_key = None
|
||||||
last_second = None
|
last_second = None
|
||||||
|
shown: Image.Image | None = None # what the screen is believed to show; None when unknown
|
||||||
|
last_full = 0.0
|
||||||
failures = 0
|
failures = 0
|
||||||
while running():
|
while running():
|
||||||
now = now_fn()
|
now = now_fn()
|
||||||
try:
|
try:
|
||||||
key = view.frame_key(now)
|
key = view.frame_key(now)
|
||||||
if key != last_key:
|
if key != last_key:
|
||||||
lcd.DisplayPILImage(view.render(now), 0, 0)
|
frame = view.render(now)
|
||||||
|
due = monotonic() - last_full >= full_refresh_s
|
||||||
|
if _push_frame(lcd, shown, frame, force_full=due):
|
||||||
|
last_full = monotonic()
|
||||||
|
shown = frame.copy()
|
||||||
last_key, last_second = key, now.second
|
last_key, last_second = key, now.second
|
||||||
elif now.second != last_second:
|
elif now.second != last_second:
|
||||||
patch = view.patch(now)
|
patch = view.patch(now)
|
||||||
if patch is not None:
|
if patch is not None:
|
||||||
lcd.DisplayPILImage(patch.image, patch.x, patch.y)
|
lcd.DisplayPILImage(patch.image, patch.x, patch.y)
|
||||||
|
if shown is not None:
|
||||||
|
shown.paste(patch.image, (patch.x, patch.y))
|
||||||
last_second = now.second
|
last_second = now.second
|
||||||
failures = 0
|
failures = 0
|
||||||
except (Exception, SystemExit): # SystemExit: the library exits when it cannot reopen the port
|
except (Exception, SystemExit): # SystemExit: the library exits when it cannot reopen the port
|
||||||
log.exception("draw failed")
|
log.exception("draw failed")
|
||||||
failures += 1
|
failures += 1
|
||||||
last_key = None # redraw everything on the next tick
|
last_key = None # redraw on the next tick
|
||||||
|
shown = None # a push may have been cut short: the screen's content is unknown
|
||||||
if failures >= max_failures:
|
if failures >= max_failures:
|
||||||
raise # let Docker restart the process and reopen the port
|
raise # let Docker restart the process and reopen the port
|
||||||
sleep(TICK_S)
|
sleep(TICK_S)
|
||||||
@@ -1,19 +1,18 @@
|
|||||||
"""Casio-style server stats: CPU/RAM/disk bars, load, temperature, uptime, containers, busiest processes."""
|
"""Cyberpunk-style server stats: CPU/RAM/disk gauges, load, temperature, uptime, containers, busiest processes."""
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from PIL import Image, ImageDraw
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
import lcdkit
|
import cyber
|
||||||
from lcdkit import BG, H, INK, W
|
from cyber import CYAN, GREY, INK, MAGENTA, RED, TEXT, W, H, YELLOW
|
||||||
from poller import Poller
|
from poller import Poller
|
||||||
from stats_data import Container, Stats, status_label
|
from stats_data import Container, Stats, status_label
|
||||||
from view import Patch
|
from view import Patch
|
||||||
|
|
||||||
|
TITLE = "HOME // SERVER"
|
||||||
ATTENTION = ("UNHEALTHY", "RESTART", "EXITED")
|
ATTENTION = ("UNHEALTHY", "RESTART", "EXITED")
|
||||||
CONTAINER_ROWS = 7
|
CONTAINER_ROWS = 5
|
||||||
ROW_STEP, ROWS_TOP = 17, 184
|
GAUGES = (("CPU", "cpu_pct", 54), ("RAM", "mem_pct", 94), ("DISK", "disk_pct", 134))
|
||||||
DIGITS = dict(w=16, h=26, t=3, gap=5) # small segment digits used for all numbers
|
|
||||||
BAR_ROWS = (("CPU", "cpu_pct", 54), ("RAM", "mem_pct", 88), ("DISK", "disk_pct", 122))
|
|
||||||
|
|
||||||
|
|
||||||
def fmt_uptime(seconds: float | None) -> str:
|
def fmt_uptime(seconds: float | None) -> str:
|
||||||
@@ -27,17 +26,9 @@ def fmt_uptime(seconds: float | None) -> str:
|
|||||||
return f"{hours}H {minutes}M" if hours else f"{minutes}M"
|
return f"{hours}H {minutes}M" if hours else f"{minutes}M"
|
||||||
|
|
||||||
|
|
||||||
def _fit(d: ImageDraw.ImageDraw, text: str, font, max_w: float) -> str:
|
|
||||||
if d.textlength(text, font=font) <= max_w:
|
|
||||||
return text
|
|
||||||
while text and d.textlength(text + "…", font=font) > max_w:
|
|
||||||
text = text[:-1]
|
|
||||||
return text + "…"
|
|
||||||
|
|
||||||
|
|
||||||
class ServerView:
|
class ServerView:
|
||||||
name = "server"
|
name = "server"
|
||||||
STALE_AFTER = 30.0 # seconds without a successful read before the numbers are marked old
|
STALE_AFTER = 10.0 # seconds without a successful read before the numbers are marked old
|
||||||
|
|
||||||
def __init__(self, poller: Poller[Stats]) -> None:
|
def __init__(self, poller: Poller[Stats]) -> None:
|
||||||
self._poller = poller
|
self._poller = poller
|
||||||
@@ -53,87 +44,106 @@ class ServerView:
|
|||||||
return age is not None and age > self.STALE_AFTER
|
return age is not None and age > self.STALE_AFTER
|
||||||
|
|
||||||
def frame_key(self, now: datetime):
|
def frame_key(self, now: datetime):
|
||||||
return (now.second // 5, self._poller.version, self._is_stale())
|
return (self._poller.version, self._is_stale())
|
||||||
|
|
||||||
def patch(self, now: datetime) -> Patch | None:
|
def patch(self, now: datetime) -> Patch | None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def render(self, now: datetime) -> Image.Image:
|
def render(self, now: datetime) -> Image.Image:
|
||||||
stats: Stats | None = self._poller.value
|
stats: Stats | None = self._poller.value
|
||||||
img = Image.new("RGB", (W, H), BG)
|
img = cyber.background()
|
||||||
d = ImageDraw.Draw(img)
|
d = ImageDraw.Draw(img)
|
||||||
f_small, f_tiny, f_row = lcdkit.load_font(15), lcdkit.load_font(12), lcdkit.load_font(14)
|
cyber.chamfer(d, (5, 5, W - 6, H - 6), 16, outline=YELLOW, width=2, cuts="tl br")
|
||||||
|
d.line((W - 26, 10, W - 10, 10), fill=CYAN, width=2) # corner brackets
|
||||||
|
d.line((W - 10, 10, W - 10, 26), fill=CYAN, width=2)
|
||||||
|
d.line((10, H - 26, 10, H - 10), fill=CYAN, width=2)
|
||||||
|
d.line((10, H - 10, 26, H - 10), fill=CYAN, width=2)
|
||||||
|
|
||||||
d.rectangle((6, 6, W - 7, H - 7), outline=INK, width=2)
|
self._header(d, stats)
|
||||||
self._header(d, stats, f_small, f_tiny)
|
self._gauges(d, stats)
|
||||||
d.line((12, 46, W - 13, 46), fill=INK, width=2)
|
self._load_and_temp(d, stats)
|
||||||
self._bars(d, stats, f_small)
|
d.line((22, 176, 318, 176), fill=YELLOW, width=1)
|
||||||
self._load_and_temp(d, stats, f_small, f_tiny)
|
self._docker(d, stats)
|
||||||
d.line((12, 160, W - 13, 160), fill=INK, width=2)
|
d.line((324, 190, 324, H - 22), fill=YELLOW, width=1)
|
||||||
self._docker(d, stats, f_tiny, f_row)
|
self._processes(d, stats)
|
||||||
d.line((306, 168, 306, H - 14), fill=INK, width=2)
|
|
||||||
self._processes(d, stats, f_tiny, f_row)
|
|
||||||
return img
|
return img
|
||||||
|
|
||||||
def _header(self, d, stats: Stats | None, f_small, f_tiny) -> None:
|
def _header(self, d: ImageDraw.ImageDraw, stats: Stats | None) -> None:
|
||||||
lcdkit.tag(d, (14, 14), "SERVER", f_small)
|
box = cyber.tag(d, (22, 14), TITLE, cyber.font(22))
|
||||||
d.text((100, 16), f"UP {fmt_uptime(stats.uptime_s if stats else None)}", font=f_small, fill=INK)
|
d.text((box[2] + 16, 17), "UP", font=cyber.font(13, False), fill=GREY)
|
||||||
|
d.text((box[2] + 36, 14), fmt_uptime(stats.uptime_s if stats else None), font=cyber.font(22), fill=CYAN)
|
||||||
if self._is_stale():
|
if self._is_stale():
|
||||||
width = d.textbbox((0, 0), "STARÉ", font=f_tiny)[2] + 6
|
cyber.tag(d, (W - 22 - 70, 14), "STARÉ", cyber.font(16), colour=RED)
|
||||||
lcdkit.tag(d, (W - 14 - width, 17), "STARÉ", f_tiny)
|
else:
|
||||||
|
tick = int(stats.uptime_s) & 0xFFFF if stats and stats.uptime_s is not None else 0
|
||||||
|
d.text((W - 22 - 92, 18), f"0x{tick:04X}", font=cyber.font(13, False), fill=MAGENTA)
|
||||||
|
d.rectangle((W - 22 - 40, 21, W - 22 - 36, 25), fill=CYAN)
|
||||||
|
d.text((W - 22 - 30, 17), "ON", font=cyber.font(13), fill=CYAN)
|
||||||
|
d.line((22, 46, W - 22, 46), fill=YELLOW, width=1)
|
||||||
|
d.line((22, 48, box[2], 48), fill=YELLOW, width=1)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _bars(d, stats: Stats | None, f_small) -> None:
|
def _gauges(d: ImageDraw.ImageDraw, stats: Stats | None) -> None:
|
||||||
for label, field, y in BAR_ROWS:
|
big = cyber.font(36)
|
||||||
|
for label, field, y in GAUGES:
|
||||||
pct = getattr(stats, field) if stats else None
|
pct = getattr(stats, field) if stats else None
|
||||||
d.text((18, y + 3), label, font=f_small, fill=INK)
|
d.text((24, y), label, font=cyber.font(15), fill=CYAN)
|
||||||
lcdkit.h_bar(d, 72, y, pct, 24, 16, 8, 2)
|
cyber.slanted_bar(d, 24, y + 22, pct, 10, 21, 7, 3)
|
||||||
text = "--" if pct is None else str(round(pct))
|
text = "--" if pct is None else str(round(pct))
|
||||||
x = lcdkit.number(d, text, 244, y - 1, **DIGITS, ghost=False)
|
cyber.glitch_text(d, (246, y - 4), text, big)
|
||||||
if pct is not None:
|
if pct is not None:
|
||||||
d.text((x + 2, y + 6), "%", font=f_small, fill=INK)
|
d.text((246 + d.textlength(text, font=big) + 4, y + 8), "%", font=cyber.font(16), fill=CYAN)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _load_and_temp(d, stats: Stats | None, f_small, f_tiny) -> None:
|
def _load_and_temp(d: ImageDraw.ImageDraw, stats: Stats | None) -> None:
|
||||||
load = stats.load if stats else None
|
load = stats.load if stats else None
|
||||||
d.text((336, 50), "LOAD", font=f_tiny, fill=INK)
|
cyber.chamfer(d, (330, 56, W - 22, 108), 8, outline=CYAN, cuts="tr bl")
|
||||||
lcdkit.number(d, f"{load[0]:.2f}" if load else "--", 336, 64, **DIGITS, ghost=False)
|
d.text((340, 58), "LOAD AVG", font=cyber.font(13, False), fill=GREY)
|
||||||
d.text((336, 96), f"{load[1]:.2f} {load[2]:.2f}" if load else "-- --", font=f_tiny, fill=INK)
|
d.text((340, 68), f"{load[0]:.2f}" if load else "--", font=cyber.font(30), fill=YELLOW)
|
||||||
|
d.text((410, 78), f"{load[1]:.2f} {load[2]:.2f}" if load else "", font=cyber.font(13, False), fill=CYAN)
|
||||||
temp = stats.temp_c if stats else None
|
temp = stats.temp_c if stats else None
|
||||||
x = lcdkit.number(d, lcdkit.fmt_temp(temp), 336, 116, **DIGITS, ghost=False)
|
cyber.chamfer(d, (330, 114, W - 22, 166), 8, outline=CYAN, cuts="tr bl")
|
||||||
d.text((x + 2, 126), "°C" if temp is not None else "", font=f_small, fill=INK)
|
d.text((340, 116), "CORE TEMP", font=cyber.font(13, False), fill=GREY)
|
||||||
|
d.text((340, 126), f"{round(temp)}°C" if temp is not None else "--", font=cyber.font(30), fill=YELLOW)
|
||||||
|
cyber.hazard_stripe(d, 336, 170, 118)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _docker(d, stats: Stats | None, f_tiny, f_row) -> None:
|
def _docker(d: ImageDraw.ImageDraw, stats: Stats | None) -> None:
|
||||||
|
d.text((24, 180), "DOCKER", font=cyber.font(16), fill=YELLOW)
|
||||||
containers = stats.containers if stats else None
|
containers = stats.containers if stats else None
|
||||||
if containers is None:
|
if containers is None:
|
||||||
d.text((14, 166), "DOCKER", font=f_tiny, fill=INK)
|
d.text((24, 226), "NO DOCKER", font=cyber.font(26), fill=RED)
|
||||||
d.text((22, 230), "NO DOCKER", font=lcdkit.load_font(18), fill=INK)
|
d.text((24, 256), "SOCKET UNAVAILABLE", font=cyber.font(13, False), fill=GREY)
|
||||||
return
|
return
|
||||||
running = sum(1 for c in containers if c.state == "running")
|
running = sum(1 for c in containers if c.state == "running")
|
||||||
d.text((14, 166), f"DOCKER {running}/{len(containers)}", font=f_tiny, fill=INK)
|
d.text((86, 183), f"{running}/{len(containers)} ACTIVE", font=cyber.font(13, False), fill=CYAN)
|
||||||
ordered = sorted(containers, key=lambda c: (status_label(c) not in ATTENTION, c.name))
|
ordered = sorted(containers, key=lambda c: (status_label(c) not in ATTENTION, c.name))
|
||||||
shown = ordered if len(ordered) <= CONTAINER_ROWS else ordered[:CONTAINER_ROWS - 1]
|
y = 202
|
||||||
for i, c in enumerate(shown):
|
for c in ordered[:CONTAINER_ROWS]:
|
||||||
ServerView._container_row(d, c, ROWS_TOP + i * ROW_STEP, f_tiny, f_row)
|
ServerView._container_row(d, c, y)
|
||||||
if len(shown) < len(ordered):
|
y += 17
|
||||||
d.text((14, ROWS_TOP + len(shown) * ROW_STEP), f"+{len(ordered) - len(shown)}", font=f_row, fill=INK)
|
if len(ordered) > CONTAINER_ROWS:
|
||||||
|
d.text((24, y + 1), f"+{len(ordered) - CONTAINER_ROWS} MORE", font=cyber.font(13, False), fill=GREY)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _container_row(d, c: Container, y: int, f_tiny, f_row) -> None:
|
def _container_row(d: ImageDraw.ImageDraw, c: Container, y: int) -> None:
|
||||||
label = status_label(c)
|
label = status_label(c)
|
||||||
d.text((14, y), _fit(d, c.name, f_row, 170), font=f_row, fill=INK)
|
d.text((24, y), cyber.fit(d, c.name.upper(), cyber.font(15), 226), font=cyber.font(15), fill=TEXT)
|
||||||
if label in ATTENTION:
|
if label in ATTENTION:
|
||||||
width = d.textbbox((0, 0), label, font=f_tiny)[2] + 6
|
colour = MAGENTA if label == "RESTART" else RED
|
||||||
lcdkit.tag(d, (294 - width, y), label, f_tiny)
|
width = d.textlength(label, font=cyber.font(13))
|
||||||
|
cyber.chamfer(d, (int(314 - width - 14), y + 1, 314, y + 16), 4, fill=colour, cuts="tl br")
|
||||||
|
d.text((314 - width - 7, y - 1), label, font=cyber.font(13), fill=INK)
|
||||||
else:
|
else:
|
||||||
d.text((294 - d.textlength(label, font=f_tiny), y + 2), label, font=f_tiny, fill=INK)
|
d.text((312 - d.textlength(label, font=cyber.font(13)), y), label, font=cyber.font(13), fill=CYAN)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _processes(d, stats: Stats | None, f_tiny, f_row) -> None:
|
def _processes(d: ImageDraw.ImageDraw, stats: Stats | None) -> None:
|
||||||
d.text((318, 166), "PROCESY", font=f_tiny, fill=INK)
|
d.text((336, 180), "TOP PROCESSES", font=cyber.font(16), fill=YELLOW)
|
||||||
for i, proc in enumerate(stats.procs if stats else ()):
|
y = 204
|
||||||
y = ROWS_TOP + i * 22
|
for proc in stats.procs if stats else ():
|
||||||
|
d.text((336, y), cyber.fit(d, proc.name.upper(), cyber.font(15), 76), font=cyber.font(15), fill=CYAN)
|
||||||
pct = f"{proc.cpu_pct:.1f}%"
|
pct = f"{proc.cpu_pct:.1f}%"
|
||||||
d.text((W - 16 - d.textlength(pct, font=f_row), y), pct, font=f_row, fill=INK)
|
d.text((W - 24 - d.textlength(pct, font=cyber.font(15)), y), pct, font=cyber.font(15), fill=YELLOW)
|
||||||
d.text((318, y), _fit(d, proc.name, f_row, 80), font=f_row, fill=INK)
|
d.rectangle((336, y + 17, 336 + int(min(proc.cpu_pct, 10) * 11), y + 18), fill=MAGENTA)
|
||||||
|
y += 22
|
||||||
@@ -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")
|
||||||
@@ -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))
|
||||||
@@ -5,9 +5,11 @@ import logging
|
|||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import socket
|
import socket
|
||||||
|
import time
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -144,15 +146,25 @@ def list_containers(sock_path: str, timeout: float = 3.0) -> tuple[Container, ..
|
|||||||
# --- reader --------------------------------------------------------------------
|
# --- reader --------------------------------------------------------------------
|
||||||
|
|
||||||
class StatsReader:
|
class StatsReader:
|
||||||
|
"""Reads everything on each call, but asks Docker only every `docker_every` seconds and ranks processes
|
||||||
|
over windows of `proc_every` seconds (a 1 s window makes the ranking flicker)."""
|
||||||
|
|
||||||
def __init__(self, proc_root: str = "/host/proc", sys_root: str = "/host/sys", disk_path: str = "/host/root",
|
def __init__(self, proc_root: str = "/host/proc", sys_root: str = "/host/sys", disk_path: str = "/host/root",
|
||||||
docker_sock: str = "/var/run/docker.sock", docker_timeout: float = 3.0) -> None:
|
docker_sock: str = "/var/run/docker.sock", docker_timeout: float = 3.0,
|
||||||
|
docker_every: float = 5.0, proc_every: float = 3.0,
|
||||||
|
clock: Callable[[], float] = time.monotonic) -> None:
|
||||||
self._proc = Path(proc_root)
|
self._proc = Path(proc_root)
|
||||||
self._sys = Path(sys_root)
|
self._sys = Path(sys_root)
|
||||||
self._disk = disk_path
|
self._disk = disk_path
|
||||||
self._sock = docker_sock
|
self._sock = docker_sock
|
||||||
self._docker_timeout = docker_timeout
|
self._docker_timeout = docker_timeout
|
||||||
|
self._docker_every = docker_every
|
||||||
|
self._proc_every = proc_every
|
||||||
|
self._clock = clock
|
||||||
self._prev_cpu: tuple[int, int] | None = None
|
self._prev_cpu: tuple[int, int] | None = None
|
||||||
self._prev_ticks: dict[int, int] = {}
|
self._docker: tuple[float, tuple[Container, ...] | None] | None = None # (when asked, result)
|
||||||
|
self._snapshot: tuple[float, int, dict[int, int], dict[int, str]] | None = None # (when, jiffies, ticks, names)
|
||||||
|
self._procs: tuple[Proc, ...] = ()
|
||||||
self._failing: set[str] = set()
|
self._failing: set[str] = set()
|
||||||
|
|
||||||
def _try(self, section: str, fn, default=None):
|
def _try(self, section: str, fn, default=None):
|
||||||
@@ -170,12 +182,11 @@ class StatsReader:
|
|||||||
return value
|
return value
|
||||||
|
|
||||||
def read(self) -> Stats:
|
def read(self) -> Stats:
|
||||||
total_delta = None
|
total = None
|
||||||
cpu = None
|
cpu = None
|
||||||
try:
|
try:
|
||||||
cur = parse_cpu_times((self._proc / "stat").read_text())
|
cur = parse_cpu_times((self._proc / "stat").read_text())
|
||||||
if self._prev_cpu is not None:
|
total = cur[1]
|
||||||
total_delta = cur[1] - self._prev_cpu[1]
|
|
||||||
cpu = cpu_pct(self._prev_cpu, cur)
|
cpu = cpu_pct(self._prev_cpu, cur)
|
||||||
self._prev_cpu = cur
|
self._prev_cpu = cur
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
@@ -192,10 +203,17 @@ class StatsReader:
|
|||||||
load=self._try("load", self._load),
|
load=self._try("load", self._load),
|
||||||
temp_c=self._try("temperature", self._temperature),
|
temp_c=self._try("temperature", self._temperature),
|
||||||
uptime_s=self._try("uptime", lambda: float((self._proc / "uptime").read_text().split()[0])),
|
uptime_s=self._try("uptime", lambda: float((self._proc / "uptime").read_text().split()[0])),
|
||||||
containers=self._try("docker", lambda: list_containers(self._sock, self._docker_timeout)),
|
containers=self._containers(),
|
||||||
procs=self._try("processes", lambda: self._processes(total_delta), ()),
|
procs=self._try("processes", lambda: self._processes(total), self._procs),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _containers(self) -> tuple[Container, ...] | None:
|
||||||
|
now = self._clock()
|
||||||
|
if self._docker is None or now - self._docker[0] >= self._docker_every:
|
||||||
|
result = self._try("docker", lambda: list_containers(self._sock, self._docker_timeout))
|
||||||
|
self._docker = (now, result)
|
||||||
|
return self._docker[1]
|
||||||
|
|
||||||
def _disk_pct(self) -> float:
|
def _disk_pct(self) -> float:
|
||||||
st = os.statvfs(self._disk)
|
st = os.statvfs(self._disk)
|
||||||
used = st.f_blocks - st.f_bfree
|
used = st.f_blocks - st.f_bfree
|
||||||
@@ -218,7 +236,13 @@ class StatsReader:
|
|||||||
cpu_zones = [c for is_cpu, c in readings if is_cpu]
|
cpu_zones = [c for is_cpu, c in readings if is_cpu]
|
||||||
return max(cpu_zones or [c for _, c in readings])
|
return max(cpu_zones or [c for _, c in readings])
|
||||||
|
|
||||||
def _processes(self, total_delta: int | None) -> tuple[Proc, ...]:
|
def _processes(self, total: int | None) -> tuple[Proc, ...]:
|
||||||
|
"""Top processes by CPU over the last window; the previous ranking is kept between windows."""
|
||||||
|
now = self._clock()
|
||||||
|
if total is None:
|
||||||
|
return self._procs
|
||||||
|
if self._snapshot is not None and now - self._snapshot[0] < self._proc_every:
|
||||||
|
return self._procs
|
||||||
ticks: dict[int, int] = {}
|
ticks: dict[int, int] = {}
|
||||||
names: dict[int, str] = {}
|
names: dict[int, str] = {}
|
||||||
for entry in os.scandir(self._proc):
|
for entry in os.scandir(self._proc):
|
||||||
@@ -229,12 +253,13 @@ class StatsReader:
|
|||||||
except (OSError, ValueError, IndexError):
|
except (OSError, ValueError, IndexError):
|
||||||
continue # the process exited while we were reading
|
continue # the process exited while we were reading
|
||||||
ticks[int(entry.name)], names[int(entry.name)] = t, name
|
ticks[int(entry.name)], names[int(entry.name)] = t, name
|
||||||
previous, self._prev_ticks = self._prev_ticks, ticks
|
previous, self._snapshot = self._snapshot, (now, total, ticks, names)
|
||||||
if not total_delta or total_delta <= 0 or not previous:
|
if previous is None or total - previous[1] <= 0:
|
||||||
return ()
|
return self._procs
|
||||||
per_name: dict[str, float] = defaultdict(float)
|
per_name: dict[str, float] = defaultdict(float)
|
||||||
for pid, t in ticks.items():
|
for pid, t in ticks.items():
|
||||||
if pid in previous and t > previous[pid]:
|
if pid in previous[2] and t > previous[2][pid]:
|
||||||
per_name[names[pid]] += (t - previous[pid]) / total_delta * 100
|
per_name[names[pid]] += (t - previous[2][pid]) / (total - previous[1]) * 100
|
||||||
ranked = sorted(per_name.items(), key=lambda kv: kv[1], reverse=True)[:TOP_PROCESSES]
|
ranked = sorted(per_name.items(), key=lambda kv: kv[1], reverse=True)[:TOP_PROCESSES]
|
||||||
return tuple(Proc(name, pct) for name, pct in ranked)
|
self._procs = tuple(Proc(name, pct) for name, pct in ranked)
|
||||||
|
return self._procs
|
||||||
@@ -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
|
||||||
@@ -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]}}
|
||||||
@@ -1 +1 @@
|
|||||||
{"latitude":49.23005,"longitude":17.657297,"generationtime_ms":0.3495216369628906,"utc_offset_seconds":7200,"timezone":"Europe/Prague","timezone_abbreviation":"GMT+2","elevation":221.0,"current_units":{"time":"iso8601","interval":"seconds","temperature_2m":"°C","weather_code":"wmo code"},"current":{"time":"2026-10-22T12:45","interval":900,"temperature_2m":10.2,"weather_code":61},"hourly_units":{"time":"iso8601","precipitation_probability":"%","precipitation":"mm"},"hourly":{"time":["2026-10-22T00:00","2026-10-22T01:00","2026-10-22T02:00","2026-10-22T03:00","2026-10-22T04:00","2026-10-22T05:00","2026-10-22T06:00","2026-10-22T07:00","2026-10-22T08:00","2026-10-22T09:00","2026-10-22T10:00","2026-10-22T11:00","2026-10-22T12:00","2026-10-22T13:00","2026-10-22T14:00","2026-10-22T15:00","2026-10-22T16:00","2026-10-22T17:00","2026-10-22T18:00","2026-10-22T19:00","2026-10-22T20:00","2026-10-22T21:00","2026-10-22T22:00","2026-10-22T23:00","2026-10-23T00:00","2026-10-23T01:00","2026-10-23T02:00","2026-10-23T03:00","2026-10-23T04:00","2026-10-23T05:00","2026-10-23T06:00","2026-10-23T07:00","2026-10-23T08:00","2026-10-23T09:00","2026-10-23T10:00","2026-10-23T11:00","2026-10-23T12:00","2026-10-23T13:00","2026-10-23T14:00","2026-10-23T15:00","2026-10-23T16:00","2026-10-23T17:00","2026-10-23T18:00","2026-10-23T19:00","2026-10-23T20:00","2026-10-23T21:00","2026-10-23T22:00","2026-10-23T23:00"],"precipitation_probability":[93,98,100,100,100,100,100,100,100,100,100,98,93,98,63,18,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,5,3,0],"precipitation":[0.40,1.80,2.50,3.80,2.00,2.20,2.30,1.40,2.60,3.50,1.80,1.00,0.40,0.50,0.40,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00]},"daily_units":{"time":"iso8601","temperature_2m_max":"°C","temperature_2m_min":"°C"},"daily":{"time":["2026-10-22","2026-10-23"],"temperature_2m_max":[15.0,14.3],"temperature_2m_min":[6.0,2.2]}}
|
{"latitude":49.23005,"longitude":17.657297,"generationtime_ms":0.3495216369628906,"utc_offset_seconds":7200,"timezone":"Europe/Prague","timezone_abbreviation":"GMT+2","elevation":221.0,"current_units":{"time":"iso8601","interval":"seconds","temperature_2m":"°C","weather_code":"wmo code","apparent_temperature":"°C"},"current":{"time":"2026-10-22T12:45","interval":900,"temperature_2m":10.2,"weather_code":61,"apparent_temperature":8.1},"hourly_units":{"time":"iso8601","precipitation_probability":"%","precipitation":"mm"},"hourly":{"time":["2026-10-22T00:00","2026-10-22T01:00","2026-10-22T02:00","2026-10-22T03:00","2026-10-22T04:00","2026-10-22T05:00","2026-10-22T06:00","2026-10-22T07:00","2026-10-22T08:00","2026-10-22T09:00","2026-10-22T10:00","2026-10-22T11:00","2026-10-22T12:00","2026-10-22T13:00","2026-10-22T14:00","2026-10-22T15:00","2026-10-22T16:00","2026-10-22T17:00","2026-10-22T18:00","2026-10-22T19:00","2026-10-22T20:00","2026-10-22T21:00","2026-10-22T22:00","2026-10-22T23:00","2026-10-23T00:00","2026-10-23T01:00","2026-10-23T02:00","2026-10-23T03:00","2026-10-23T04:00","2026-10-23T05:00","2026-10-23T06:00","2026-10-23T07:00","2026-10-23T08:00","2026-10-23T09:00","2026-10-23T10:00","2026-10-23T11:00","2026-10-23T12:00","2026-10-23T13:00","2026-10-23T14:00","2026-10-23T15:00","2026-10-23T16:00","2026-10-23T17:00","2026-10-23T18:00","2026-10-23T19:00","2026-10-23T20:00","2026-10-23T21:00","2026-10-23T22:00","2026-10-23T23:00"],"precipitation_probability":[93,98,100,100,100,100,100,100,100,100,100,98,93,98,63,18,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,5,3,0],"precipitation":[0.4,1.8,2.5,3.8,2.0,2.2,2.3,1.4,2.6,3.5,1.8,1.0,0.4,0.5,0.4,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]},"daily_units":{"time":"iso8601","weather_code":"wmo code","temperature_2m_max":"°C","temperature_2m_min":"°C","sunrise":"iso8601","sunset":"iso8601"},"daily":{"time":["2026-10-22","2026-10-23","2026-10-24","2026-10-25","2026-10-26","2026-10-27","2026-10-28"],"weather_code":[63,45,61,63,80,45,45],"temperature_2m_max":[15.0,14.3,12.1,10.2,11.2,10.0,11.5],"temperature_2m_min":[6.0,2.2,4.3,0.8,1.9,-0.2,-0.5],"sunrise":["2026-10-22T07:20","2026-10-23T07:22","2026-10-24T07:24","2026-10-25T06:25","2026-10-26T06:27","2026-10-27T06:28","2026-10-28T06:30"],"sunset":["2026-10-22T17:45","2026-10-23T17:44","2026-10-24T17:42","2026-10-25T16:40","2026-10-26T16:38","2026-10-27T16:36","2026-10-28T16:35"]}}
|
||||||
@@ -7,3 +7,11 @@ def count_colour(img: Image.Image, colour, box=None) -> int:
|
|||||||
if box is not None:
|
if box is not None:
|
||||||
img = img.crop(box)
|
img = img.crop(box)
|
||||||
return int((np.asarray(img.convert("RGB")) == np.array(colour)).all(axis=2).sum())
|
return int((np.asarray(img.convert("RGB")) == np.array(colour)).all(axis=2).sum())
|
||||||
|
|
||||||
|
|
||||||
|
def count_near(img: Image.Image, colour, tolerance: int = 70, box=None) -> int:
|
||||||
|
"""Pixels within `tolerance` (per channel) of `colour`: for anti-aliased text, which is never exactly pure."""
|
||||||
|
if box is not None:
|
||||||
|
img = img.crop(box)
|
||||||
|
diff = np.abs(np.asarray(img.convert("RGB")).astype(int) - np.array(colour))
|
||||||
|
return int((diff.max(axis=2) <= tolerance).sum())
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import math
|
||||||
|
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, datetime(2026, 10, 29, 4, 30))
|
||||||
|
assert near(p.start, datetime(2026, 10, 29, 5, 41), 1) # when it climbs past 10°, not when it rises
|
||||||
|
assert 35 < p.max_alt < 45
|
||||||
|
assert (direction(p.az_from), direction(p.az_to)) == ("Z", "JV")
|
||||||
|
|
||||||
|
|
||||||
|
def test_pass_that_comes_out_of_the_earths_shadow_counts_from_there():
|
||||||
|
p = astro.next_visible_pass(TLE, EVENING) # in the shadow at its highest, so easy to miss
|
||||||
|
assert near(p.start, datetime(2026, 10, 29, 4, 8), 1)
|
||||||
|
assert 35 < p.max_alt < 45
|
||||||
|
assert (direction(p.az_from), direction(p.az_to)) == ("V", "V")
|
||||||
|
|
||||||
|
|
||||||
|
def test_pass_brightness_is_that_of_a_typical_iss_pass():
|
||||||
|
p = astro.next_visible_pass(TLE, datetime(2026, 10, 29, 4, 30))
|
||||||
|
assert -4.2 < p.mag < -2.5 # a 40° pass: brighter than any star, short of the best overhead passes
|
||||||
|
|
||||||
|
|
||||||
|
def test_magnitude_formula():
|
||||||
|
assert astro.magnitude(1000, math.pi / 2) == pytest.approx(astro.ISS_STD_MAG)
|
||||||
|
assert astro.magnitude(500, math.pi / 2) == pytest.approx(astro.ISS_STD_MAG - 5 * math.log10(2))
|
||||||
|
assert astro.magnitude(1000, 0) == pytest.approx(astro.ISS_STD_MAG - 2.5 * math.log10(math.pi)) # fully lit
|
||||||
|
assert astro.magnitude(1000, math.pi) > 10 # only the dark side faces us: invisible, not an error
|
||||||
|
|
||||||
|
|
||||||
|
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,78 @@
|
|||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
import cyber
|
||||||
|
from cyber import BG, CYAN, DIM, RED, SCAN, YELLOW
|
||||||
|
from tests.helpers import count_colour, count_near
|
||||||
|
|
||||||
|
|
||||||
|
def canvas(w=200, h=100):
|
||||||
|
img = Image.new("RGB", (w, h), BG)
|
||||||
|
return img, ImageDraw.Draw(img)
|
||||||
|
|
||||||
|
|
||||||
|
def test_background_has_scanlines_and_is_a_private_copy():
|
||||||
|
a = cyber.background()
|
||||||
|
assert a.size == (480, 320)
|
||||||
|
assert a.getpixel((5, 0)) == SCAN and a.getpixel((5, 1)) == BG
|
||||||
|
a.putpixel((5, 1), (1, 2, 3))
|
||||||
|
assert cyber.background().getpixel((5, 1)) == BG # the cached original is untouched
|
||||||
|
|
||||||
|
|
||||||
|
def test_chamfer_cuts_the_requested_corner_only():
|
||||||
|
img, d = canvas()
|
||||||
|
cyber.chamfer(d, (10, 10, 90, 50), 12, fill=YELLOW, cuts="tl")
|
||||||
|
assert img.getpixel((11, 11)) == BG # cut away
|
||||||
|
assert img.getpixel((88, 48)) == YELLOW # the bottom-right corner is square
|
||||||
|
assert img.getpixel((30, 30)) == YELLOW
|
||||||
|
|
||||||
|
|
||||||
|
def test_glitch_text_shows_all_three_colours():
|
||||||
|
img, d = canvas()
|
||||||
|
cyber.glitch_text(d, (20, 10), "88", cyber.font(48))
|
||||||
|
for colour in (YELLOW, CYAN, RED): # the fringes are anti-aliased, so compare with a tolerance
|
||||||
|
assert count_near(img, colour) > 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_slanted_bar_lights_proportionally():
|
||||||
|
img, d = canvas()
|
||||||
|
cyber.slanted_bar(d, 10, 10, 50, 10, 10, 8, 2)
|
||||||
|
assert count_colour(img, YELLOW) > 0 and count_colour(img, DIM) > 0
|
||||||
|
lit, unlit = count_colour(img, YELLOW), count_colour(img, DIM)
|
||||||
|
assert abs(lit - unlit) <= lit * 0.15 # 5 of 10 segments
|
||||||
|
|
||||||
|
|
||||||
|
def test_slanted_bar_turns_red_when_hot():
|
||||||
|
img, d = canvas()
|
||||||
|
cyber.slanted_bar(d, 10, 10, 90, 10, 10, 8, 2)
|
||||||
|
assert count_colour(img, RED) > 0 and count_colour(img, YELLOW) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_slanted_bar_none_is_all_dim():
|
||||||
|
img, d = canvas()
|
||||||
|
cyber.slanted_bar(d, 10, 10, None, 10, 10, 8, 2)
|
||||||
|
assert count_colour(img, DIM) > 0
|
||||||
|
assert count_colour(img, YELLOW) == 0 and count_colour(img, RED) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_tag_is_sized_from_its_text_and_returns_its_box():
|
||||||
|
img, d = canvas(300, 60)
|
||||||
|
f = cyber.font(22)
|
||||||
|
short = cyber.tag(d, (10, 10), "HI", f)
|
||||||
|
long_ = cyber.tag(d, (10, 10), "HOME // SERVER", f)
|
||||||
|
assert (long_[2] - long_[0]) > (short[2] - short[0])
|
||||||
|
assert (long_[2] - long_[0]) >= d.textlength("HOME // SERVER", font=f)
|
||||||
|
assert count_colour(img, YELLOW) > 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_tag_colour_can_be_changed():
|
||||||
|
img, d = canvas()
|
||||||
|
cyber.tag(d, (10, 10), "STARÉ", cyber.font(14), colour=RED)
|
||||||
|
assert count_colour(img, RED) > 0 and count_colour(img, YELLOW) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_fit_shortens_long_text_with_an_ellipsis():
|
||||||
|
img, d = canvas()
|
||||||
|
f = cyber.font(15)
|
||||||
|
text = cyber.fit(d, "A-VERY-LONG-CONTAINER-NAME-INDEED", f, 80)
|
||||||
|
assert text.endswith("…") and d.textlength(text, font=f) <= 80
|
||||||
|
assert cyber.fit(d, "SHORT", f, 80) == "SHORT"
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import json
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from PIL import ImageChops
|
||||||
|
|
||||||
|
import astro
|
||||||
|
from iss_view import LAT_BOTTOM, LAT_TOP, MAP_H, MAP_TOP, MARKER, PANEL_TOP, TEXT, IssView, is_day, map_xy, \
|
||||||
|
pass_cells
|
||||||
|
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(LAT_TOP, -180) == pytest.approx((0, MAP_TOP))
|
||||||
|
assert map_xy(LAT_BOTTOM, 180) == pytest.approx((480, MAP_TOP + MAP_H))
|
||||||
|
(x0, y0), (x1, y1) = map_xy(0, 0), map_xy(10, 10)
|
||||||
|
assert x1 - x0 == pytest.approx(y0 - y1) # degrees as wide as they are tall
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_whole_orbit_fits_on_the_map():
|
||||||
|
assert MAP_TOP < map_xy(51.7, 0)[1] and map_xy(-51.7, 0)[1] < MAP_TOP + MAP_H
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
def test_next_pass_grid_shows_height_direction_brightness_and_clouds():
|
||||||
|
p = astro.next_visible_pass(TLE, NOW)
|
||||||
|
cells = {label: value for label, value, _ in pass_cells(p, CLOUDS)}
|
||||||
|
assert cells["VÝŠKA"] == "40°"
|
||||||
|
assert cells["SMĚR"] == "V → V" # out of the earth's shadow high in the east, sinking there
|
||||||
|
assert cells["JASNOST"].startswith("−") and cells["JASNOST"].endswith(" mag") and "," in cells["JASNOST"]
|
||||||
|
assert cells["MRAKY"] == "100 %"
|
||||||
|
assert {label: value for label, value, _ in pass_cells(p, ())}["MRAKY"] == "--"
|
||||||
|
|
||||||
|
|
||||||
|
def test_time_of_the_next_pass_is_large():
|
||||||
|
img = view().render(NOW).crop((0, PANEL_TOP, 200, 320))
|
||||||
|
mask = img.point(lambda v: 255 if v > 200 else 0).convert("L").point(lambda v: 255 if v == 255 else 0)
|
||||||
|
top, bottom = mask.getbbox()[1], mask.getbbox()[3]
|
||||||
|
assert bottom - top >= 50 # 48 px time over the date: readable across the room
|
||||||
@@ -81,3 +81,22 @@ def test_tag_is_ink_box_and_returns_its_box():
|
|||||||
x0, y0, x1, y1 = box
|
x0, y0, x1, y1 = box
|
||||||
assert img.getpixel((x0 + 1, y0 + 1)) == INK
|
assert img.getpixel((x0 + 1, y0 + 1)) == INK
|
||||||
assert x1 > x0 and y1 > y0
|
assert x1 > x0 and y1 > y0
|
||||||
|
|
||||||
|
|
||||||
|
def test_night_turns_background_dark_and_ink_light():
|
||||||
|
img = Image.new("RGB", (3, 1), BG)
|
||||||
|
img.putpixel((1, 0), INK)
|
||||||
|
img.putpixel((2, 0), GHOST)
|
||||||
|
bg, ink, ghost = (sum(lcdkit.night(img).getpixel((x, 0))) for x in range(3))
|
||||||
|
assert bg < 100 and ink > 450
|
||||||
|
# unlit segments stay faint: a little lighter than the background, nowhere near the ink
|
||||||
|
assert bg < ghost < (bg + ink) / 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_night_keeps_antialiased_text_in_between():
|
||||||
|
mid = tuple((a + b) // 2 for a, b in zip(INK, BG))
|
||||||
|
img = Image.new("RGB", (3, 1), BG)
|
||||||
|
img.putpixel((1, 0), INK)
|
||||||
|
img.putpixel((2, 0), mid)
|
||||||
|
bg, ink, edge = (sum(lcdkit.night(img).getpixel((x, 0))) for x in range(3))
|
||||||
|
assert bg < edge < ink
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from lcdkit import BG
|
||||||
|
from regions import changed_regions
|
||||||
|
|
||||||
|
|
||||||
|
def blank(w=480, h=320):
|
||||||
|
return Image.new("RGB", (w, h), BG)
|
||||||
|
|
||||||
|
|
||||||
|
def with_pixels(points, colour=(0, 0, 0)):
|
||||||
|
img = blank()
|
||||||
|
for p in points:
|
||||||
|
img.putpixel(p, colour)
|
||||||
|
return img
|
||||||
|
|
||||||
|
|
||||||
|
def test_identical_images_have_no_changed_regions():
|
||||||
|
assert changed_regions(blank(), blank()) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_single_pixel_gives_a_tight_box():
|
||||||
|
assert changed_regions(blank(), with_pixels([(100, 50)])) == [(100, 50, 101, 51)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_far_apart_changes_are_separate_boxes():
|
||||||
|
boxes = changed_regions(blank(), with_pixels([(10, 10), (400, 250)]))
|
||||||
|
assert boxes == [(10, 10, 11, 11), (400, 250, 401, 251)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_neighbouring_tiles_in_a_row_merge_into_one_box():
|
||||||
|
# x=10 is in tile 0 and x=40 in tile 1 (32 px tiles): one run, tight bounding box
|
||||||
|
assert changed_regions(blank(), with_pixels([(10, 10), (40, 12)])) == [(10, 10, 41, 13)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_boxes_always_cover_every_changed_pixel():
|
||||||
|
rng = np.random.default_rng(7)
|
||||||
|
for _ in range(20):
|
||||||
|
points = [(int(rng.integers(0, 480)), int(rng.integers(0, 320))) for _ in range(int(rng.integers(1, 12)))]
|
||||||
|
new = with_pixels(points)
|
||||||
|
boxes = changed_regions(blank(), new)
|
||||||
|
for x, y in points:
|
||||||
|
assert any(x0 <= x < x1 and y0 <= y < y1 for x0, y0, x1, y1 in boxes), (x, y, boxes)
|
||||||
|
for x0, y0, x1, y1 in boxes: # and stay inside the image
|
||||||
|
assert 0 <= x0 < x1 <= 480 and 0 <= y0 < y1 <= 320
|
||||||
|
|
||||||
|
|
||||||
|
def test_size_mismatch_is_an_error():
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
changed_regions(blank(480, 320), blank(320, 480))
|
||||||
@@ -3,22 +3,35 @@ 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():
|
||||||
with pytest.raises(UnknownView):
|
with pytest.raises(UnknownView):
|
||||||
make_view("")
|
make_view("")
|
||||||
|
|
||||||
|
|
||||||
|
def test_server_view_polls_every_second_and_weather_every_quarter_hour():
|
||||||
|
import registry
|
||||||
|
assert registry.SERVER_REFRESH_S == 1
|
||||||
|
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
|
||||||
@@ -25,9 +25,10 @@ class FakeLcd:
|
|||||||
class StubView:
|
class StubView:
|
||||||
name = "stub"
|
name = "stub"
|
||||||
|
|
||||||
def __init__(self, keys, with_patch=True):
|
def __init__(self, keys, with_patch=True, render_fn=None):
|
||||||
self._keys = keys # callable(now) -> key
|
self._keys = keys # callable(now) -> key
|
||||||
self._with_patch = with_patch
|
self._with_patch = with_patch
|
||||||
|
self._render_fn = render_fn # callable(now) -> Image, default: a blank frame
|
||||||
self.renders = 0
|
self.renders = 0
|
||||||
|
|
||||||
def start(self): ...
|
def start(self): ...
|
||||||
@@ -38,12 +39,19 @@ class StubView:
|
|||||||
|
|
||||||
def render(self, now):
|
def render(self, now):
|
||||||
self.renders += 1
|
self.renders += 1
|
||||||
return Image.new("RGB", (480, 320), BG)
|
return self._render_fn(now) if self._render_fn else Image.new("RGB", (480, 320), BG)
|
||||||
|
|
||||||
def patch(self, now):
|
def patch(self, now):
|
||||||
return Patch(Image.new("RGB", (10, 5), BG), 100, 50) if self._with_patch else None
|
return Patch(Image.new("RGB", (10, 5), BG), 100, 50) if self._with_patch else None
|
||||||
|
|
||||||
|
|
||||||
|
def marker(x, y, size=10):
|
||||||
|
"""A blank frame with one dark box; moving it between frames is a small change."""
|
||||||
|
img = Image.new("RGB", (480, 320), BG)
|
||||||
|
img.paste((0, 0, 0), (x, y, x + size, y + size))
|
||||||
|
return img
|
||||||
|
|
||||||
|
|
||||||
def ticks(n):
|
def ticks(n):
|
||||||
"""running() that is true for the first n calls."""
|
"""running() that is true for the first n calls."""
|
||||||
state = {"left": n}
|
state = {"left": n}
|
||||||
@@ -83,10 +91,12 @@ def test_run_pushes_patch_each_new_second_only():
|
|||||||
assert lcd.calls == [((480, 320), 0, 0), ((10, 5), 100, 50), ((10, 5), 100, 50)]
|
assert lcd.calls == [((480, 320), 0, 0), ((10, 5), 100, 50), ((10, 5), 100, 50)]
|
||||||
|
|
||||||
|
|
||||||
def test_run_pushes_full_frame_when_key_changes():
|
def test_run_pushes_only_the_changed_region_when_the_key_changes():
|
||||||
lcd, view = FakeLcd(), StubView(lambda now: now.minute)
|
view = StubView(lambda now: now.minute, render_fn=lambda now: marker(now.minute * 10, 40))
|
||||||
|
lcd = FakeLcd()
|
||||||
runner.run(view, lcd, now_fn=clock(T0, 60), running=ticks(3), sleep=lambda s: None)
|
runner.run(view, lcd, now_fn=clock(T0, 60), running=ticks(3), sleep=lambda s: None)
|
||||||
assert [c[0] for c in lcd.calls] == [(480, 320)] * 3
|
assert lcd.calls[0] == ((480, 320), 0, 0) # first frame: everything
|
||||||
|
assert lcd.calls[1:] == [((20, 10), 320, 40), ((20, 10), 330, 40)] # then just the box that moved
|
||||||
|
|
||||||
|
|
||||||
def test_run_retries_failed_draw_and_continues():
|
def test_run_retries_failed_draw_and_continues():
|
||||||
@@ -163,3 +173,70 @@ def test_run_counts_library_sys_exit_as_a_failed_draw():
|
|||||||
with pytest.raises(SystemExit): # after max_failures; Docker then restarts and open_screen retries
|
with pytest.raises(SystemExit): # after max_failures; Docker then restarts and open_screen retries
|
||||||
runner.run(view, ExitingLcd(), now_fn=clock(T0, 0), running=ticks(50), sleep=lambda s: None, max_failures=3)
|
runner.run(view, ExitingLcd(), now_fn=clock(T0, 0), running=ticks(50), sleep=lambda s: None, max_failures=3)
|
||||||
assert view.renders == 3 # it tried three times first
|
assert view.renders == 3 # it tried three times first
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_sends_everything_when_most_of_the_screen_changed():
|
||||||
|
frames = iter([Image.new("RGB", (480, 320), BG), Image.new("RGB", (480, 320), (0, 0, 0))])
|
||||||
|
view = StubView(lambda now: now.minute, render_fn=lambda now: next(frames))
|
||||||
|
lcd = FakeLcd()
|
||||||
|
runner.run(view, lcd, now_fn=clock(T0, 60), running=ticks(2), sleep=lambda s: None)
|
||||||
|
assert lcd.calls == [((480, 320), 0, 0), ((480, 320), 0, 0)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_sends_a_full_frame_again_after_the_refresh_interval():
|
||||||
|
view = StubView(lambda now: now.minute, render_fn=lambda now: marker(now.minute * 10, 40))
|
||||||
|
lcd = FakeLcd()
|
||||||
|
elapsed = {32: 0.0, 33: 10.0, 34: 1000.0} # seconds since start, by the minute being shown
|
||||||
|
t = {"now": 0.0}
|
||||||
|
|
||||||
|
def now_fn():
|
||||||
|
now = T0 + timedelta(minutes=t["tick"])
|
||||||
|
t["tick"] += 1
|
||||||
|
t["now"] = elapsed[now.minute]
|
||||||
|
return now
|
||||||
|
|
||||||
|
t["tick"] = 0
|
||||||
|
runner.run(view, lcd, now_fn=now_fn, running=ticks(3), sleep=lambda s: None,
|
||||||
|
full_refresh_s=900.0, monotonic=lambda: t["now"])
|
||||||
|
sizes = [c[0] for c in lcd.calls]
|
||||||
|
assert sizes == [(480, 320), (20, 10), (480, 320)] # the third frame is 1000 s after the last full one
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_sends_a_full_frame_after_a_failed_push():
|
||||||
|
view = StubView(lambda now: now.minute, render_fn=lambda now: marker(now.minute * 10, 40))
|
||||||
|
|
||||||
|
class FailsOnSecondCall(FakeLcd):
|
||||||
|
def DisplayPILImage(self, image, x=0, y=0, image_width=None, image_height=None):
|
||||||
|
if len(self.calls) == 1 and not getattr(self, "failed", False):
|
||||||
|
self.failed = True
|
||||||
|
raise OSError("serial hiccup")
|
||||||
|
super().DisplayPILImage(image, x, y)
|
||||||
|
|
||||||
|
lcd = FailsOnSecondCall()
|
||||||
|
runner.run(view, lcd, now_fn=clock(T0, 60), running=ticks(3), sleep=lambda s: None)
|
||||||
|
assert [c[0] for c in lcd.calls] == [(480, 320), (480, 320)] # the screen state was unknown, so everything again
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_does_not_resend_what_a_patch_already_drew():
|
||||||
|
state = {"n": 0}
|
||||||
|
|
||||||
|
def render(now):
|
||||||
|
state["n"] += 1
|
||||||
|
img = marker(300, 200) # something that never changes
|
||||||
|
img.paste((50, 50, 50), (100, 50, 110, 55)) # where the view's patch draws its seconds
|
||||||
|
if state["n"] == 2:
|
||||||
|
img.paste((0, 0, 0), (10, 10, 20, 20)) # the one real change
|
||||||
|
return img
|
||||||
|
|
||||||
|
class PatchView(StubView):
|
||||||
|
def patch(self, now):
|
||||||
|
return Patch(Image.new("RGB", (10, 5), (50, 50, 50)), 100, 50)
|
||||||
|
|
||||||
|
view = PatchView(lambda now: now.minute, render_fn=render)
|
||||||
|
lcd = FakeLcd()
|
||||||
|
seconds = iter([0, 1, 0]) # tick1 full; tick2 same key new second -> patch; tick3 new key
|
||||||
|
minutes = iter([0, 0, 1])
|
||||||
|
now_fn = lambda: T0.replace(minute=next(minutes), second=next(seconds))
|
||||||
|
runner.run(view, lcd, now_fn=now_fn, running=ticks(3), sleep=lambda s: None)
|
||||||
|
# full frame, the patch, then only the changed box: the patch region was already up to date
|
||||||
|
assert lcd.calls == [((480, 320), 0, 0), ((10, 5), 100, 50), ((10, 10), 10, 10)]
|
||||||
@@ -2,10 +2,10 @@ from datetime import datetime
|
|||||||
|
|
||||||
from PIL import ImageChops
|
from PIL import ImageChops
|
||||||
|
|
||||||
from lcdkit import INK
|
from cyber import DIM, RED, TEXT
|
||||||
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 tests.helpers import count_colour
|
from tests.helpers import count_colour, count_near
|
||||||
|
|
||||||
NOW = datetime(2026, 10, 22, 14, 32, 8)
|
NOW = datetime(2026, 10, 22, 14, 32, 8)
|
||||||
|
|
||||||
@@ -49,10 +49,13 @@ def test_render_size_is_480x320():
|
|||||||
assert view(stats()).render(NOW).size == (480, 320)
|
assert view(stats()).render(NOW).size == (480, 320)
|
||||||
|
|
||||||
|
|
||||||
def test_frame_key_changes_every_five_seconds():
|
def test_frame_key_follows_the_data_not_the_clock():
|
||||||
v = view(stats())
|
p = StubPoller(stats(), version=1)
|
||||||
assert v.frame_key(datetime(2026, 10, 22, 14, 32, 5)) == v.frame_key(datetime(2026, 10, 22, 14, 32, 9))
|
v = ServerView(p)
|
||||||
assert v.frame_key(datetime(2026, 10, 22, 14, 32, 9)) != v.frame_key(datetime(2026, 10, 22, 14, 32, 10))
|
before = v.frame_key(datetime(2026, 10, 22, 14, 32, 5))
|
||||||
|
assert before == v.frame_key(datetime(2026, 10, 22, 14, 32, 40)) # the clock does not matter
|
||||||
|
p.version = 2
|
||||||
|
assert v.frame_key(datetime(2026, 10, 22, 14, 32, 5)) != before # new data does
|
||||||
|
|
||||||
|
|
||||||
def test_frame_key_changes_on_new_data_and_stale_flip():
|
def test_frame_key_changes_on_new_data_and_stale_flip():
|
||||||
@@ -89,14 +92,21 @@ def test_stale_tag_only_when_old():
|
|||||||
old = view(stats(), age=ServerView.STALE_AFTER + 5).render(NOW)
|
old = view(stats(), age=ServerView.STALE_AFTER + 5).render(NOW)
|
||||||
bbox = region_diff(fresh, old)
|
bbox = region_diff(fresh, old)
|
||||||
assert bbox is not None
|
assert bbox is not None
|
||||||
assert bbox[0] >= 360 and bbox[1] >= 12 and bbox[3] <= 40
|
assert bbox[0] >= 360 and bbox[1] >= 12 and bbox[3] <= 44 # only the top-right status corner changes
|
||||||
|
|
||||||
|
|
||||||
def test_bar_reflects_value():
|
def test_gauge_reflects_value():
|
||||||
idle = view(stats(cpu_pct=0.0)).render(NOW)
|
idle = view(stats(cpu_pct=0.0)).render(NOW)
|
||||||
busy = view(stats(cpu_pct=100.0)).render(NOW)
|
busy = view(stats(cpu_pct=60.0)).render(NOW)
|
||||||
box = (72, 54, 232, 78) # the CPU bar
|
box = (24, 76, 246, 86) # the CPU gauge
|
||||||
assert count_colour(busy, INK, box) > count_colour(idle, INK, box) + 500
|
assert count_colour(busy, DIM, box) < count_colour(idle, DIM, box) - 500
|
||||||
|
|
||||||
|
|
||||||
|
def test_hot_gauge_turns_red():
|
||||||
|
box = (24, 76, 246, 86)
|
||||||
|
calm = view(stats(cpu_pct=20.0)).render(NOW)
|
||||||
|
hot = view(stats(cpu_pct=95.0)).render(NOW)
|
||||||
|
assert count_colour(hot, RED, box) > count_colour(calm, RED, box) + 500
|
||||||
|
|
||||||
|
|
||||||
def test_no_docker_differs_from_container_list():
|
def test_no_docker_differs_from_container_list():
|
||||||
@@ -104,7 +114,7 @@ def test_no_docker_differs_from_container_list():
|
|||||||
missing = view(stats(containers=None)).render(NOW)
|
missing = view(stats(containers=None)).render(NOW)
|
||||||
bbox = region_diff(listed, missing)
|
bbox = region_diff(listed, missing)
|
||||||
assert bbox is not None
|
assert bbox is not None
|
||||||
assert bbox[1] >= 160 and bbox[2] <= 304 # only the docker panel changes
|
assert bbox[1] >= 176 and bbox[2] <= 322 # only the docker panel changes
|
||||||
|
|
||||||
|
|
||||||
def test_attention_containers_sort_first():
|
def test_attention_containers_sort_first():
|
||||||
@@ -113,3 +123,28 @@ def test_attention_containers_sort_first():
|
|||||||
first_rows = view(stats(containers=fine + (sick,))).render(NOW)
|
first_rows = view(stats(containers=fine + (sick,))).render(NOW)
|
||||||
sorted_ok = view(stats(containers=(sick,) + fine)).render(NOW)
|
sorted_ok = view(stats(containers=(sick,) + fine)).render(NOW)
|
||||||
assert region_diff(first_rows, sorted_ok) is None # input order does not matter
|
assert region_diff(first_rows, sorted_ok) is None # input order does not matter
|
||||||
|
|
||||||
|
|
||||||
|
def test_failed_container_gets_a_red_chip():
|
||||||
|
ok = view(stats(containers=containers(3))).render(NOW)
|
||||||
|
broken = view(stats(containers=containers(2) + (Container("zzz", "exited", None),))).render(NOW)
|
||||||
|
panel = (24, 196, 322, 300)
|
||||||
|
assert count_colour(broken, RED, panel) > count_colour(ok, RED, panel) + 100
|
||||||
|
|
||||||
|
|
||||||
|
def test_long_container_name_stays_in_its_column():
|
||||||
|
long_name = Container("an-extraordinarily-long-container-name-that-would-run-into-the-process-list", "running", "healthy")
|
||||||
|
img = view(stats(containers=(long_name,) + containers(2))).render(NOW)
|
||||||
|
process_column = (326, 196, 470, 300)
|
||||||
|
assert count_near(img, TEXT, 20, process_column) == 0 # container names are the only near-white text
|
||||||
|
|
||||||
|
|
||||||
|
def test_status_chip_is_wide_enough_for_its_label():
|
||||||
|
import numpy as np
|
||||||
|
from cyber import INK
|
||||||
|
img = view(stats(containers=(Container("web", "running", "unhealthy"),))).render(NOW)
|
||||||
|
panel = np.asarray(img.crop((24, 196, 322, 300)).convert("RGB"))
|
||||||
|
ys, xs = np.where((panel == np.array(RED)).all(axis=2))
|
||||||
|
ink_ys, ink_xs = np.where((panel == np.array(INK)).all(axis=2)) # the label is drawn in INK on the chip
|
||||||
|
assert len(xs) > 0 and len(ink_xs) > 0
|
||||||
|
assert ink_xs.min() > xs.min() and ink_xs.max() < xs.max() # the label sits inside the chip, not past its edges
|
||||||
@@ -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
|
||||||
@@ -80,12 +80,14 @@ class FakeDocker:
|
|||||||
|
|
||||||
def __init__(self, path: str, body: bytes = b"[]", hang: bool = False):
|
def __init__(self, path: str, body: bytes = b"[]", hang: bool = False):
|
||||||
self.release = threading.Event()
|
self.release = threading.Event()
|
||||||
|
self.requests = 0
|
||||||
outer = self
|
outer = self
|
||||||
|
|
||||||
class Handler(socketserver.StreamRequestHandler):
|
class Handler(socketserver.StreamRequestHandler):
|
||||||
def handle(self):
|
def handle(self):
|
||||||
while self.rfile.readline() not in (b"\r\n", b""):
|
while self.rfile.readline() not in (b"\r\n", b""):
|
||||||
pass
|
pass
|
||||||
|
outer.requests += 1
|
||||||
if hang:
|
if hang:
|
||||||
outer.release.wait(5)
|
outer.release.wait(5)
|
||||||
return
|
return
|
||||||
@@ -111,6 +113,7 @@ def docker_in(tmp_path, monkeypatch):
|
|||||||
def make(body=b"[]", hang=False):
|
def make(body=b"[]", hang=False):
|
||||||
s = FakeDocker("d.sock", body, hang)
|
s = FakeDocker("d.sock", body, hang)
|
||||||
servers.append(s)
|
servers.append(s)
|
||||||
|
make.server = s
|
||||||
return "d.sock"
|
return "d.sock"
|
||||||
|
|
||||||
yield make
|
yield make
|
||||||
@@ -159,6 +162,8 @@ def thermal(sys_root: Path, zones: dict[str, tuple[str, int]]):
|
|||||||
|
|
||||||
|
|
||||||
def make_reader(tmp_path, docker_sock="missing.sock", **kw):
|
def make_reader(tmp_path, docker_sock="missing.sock", **kw):
|
||||||
|
kw.setdefault("docker_every", 0.0)
|
||||||
|
kw.setdefault("proc_every", 0.0)
|
||||||
proc, sys_root = tmp_path / "proc", tmp_path / "sys"
|
proc, sys_root = tmp_path / "proc", tmp_path / "sys"
|
||||||
thermal(sys_root, {"thermal_zone0": ("acpitz", 30000), "thermal_zone1": ("x86_pkg_temp", 41000)})
|
thermal(sys_root, {"thermal_zone0": ("acpitz", 30000), "thermal_zone1": ("x86_pkg_temp", 41000)})
|
||||||
write_proc(proc, "cpu 100 0 50 800 50 0 0 0 0 0", {10: pid_line(10, "postgres", 0), 11: pid_line(11, "postgres", 0),
|
write_proc(proc, "cpu 100 0 50 800 50 0 0 0 0 0", {10: pid_line(10, "postgres", 0), 11: pid_line(11, "postgres", 0),
|
||||||
@@ -239,3 +244,49 @@ def test_reader_missing_proc_files_give_none_not_error(tmp_path):
|
|||||||
s = reader.read()
|
s = reader.read()
|
||||||
assert (s.cpu_pct, s.mem_pct, s.disk_pct, s.load, s.temp_c, s.uptime_s, s.containers) == (None,) * 7
|
assert (s.cpu_pct, s.mem_pct, s.disk_pct, s.load, s.temp_c, s.uptime_s, s.containers) == (None,) * 7
|
||||||
assert s.procs == ()
|
assert s.procs == ()
|
||||||
|
|
||||||
|
|
||||||
|
class FakeClock:
|
||||||
|
def __init__(self):
|
||||||
|
self.t = 0.0
|
||||||
|
|
||||||
|
def __call__(self):
|
||||||
|
return self.t
|
||||||
|
|
||||||
|
|
||||||
|
def test_reader_asks_docker_only_every_docker_every_seconds(tmp_path, docker_in):
|
||||||
|
sock = docker_in((FIXTURES / "docker_containers.json").read_bytes())
|
||||||
|
clock = FakeClock()
|
||||||
|
reader, _ = make_reader(tmp_path, docker_sock=sock, docker_every=5.0, clock=clock)
|
||||||
|
first = reader.read()
|
||||||
|
clock.t = 1.0
|
||||||
|
second = reader.read()
|
||||||
|
assert docker_in.server.requests == 1
|
||||||
|
assert second.containers == first.containers and second.containers is not None
|
||||||
|
clock.t = 5.5
|
||||||
|
reader.read()
|
||||||
|
assert docker_in.server.requests == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_reader_caches_a_docker_failure_for_the_interval_too(tmp_path):
|
||||||
|
clock = FakeClock()
|
||||||
|
reader, _ = make_reader(tmp_path, docker_sock=str(tmp_path / "nope.sock"), docker_every=5.0, clock=clock)
|
||||||
|
assert reader.read().containers is None
|
||||||
|
clock.t = 1.0
|
||||||
|
assert reader.read().containers is None # no new attempt, still reported as unavailable
|
||||||
|
|
||||||
|
|
||||||
|
def test_reader_ranks_processes_over_a_longer_window(tmp_path):
|
||||||
|
clock = FakeClock()
|
||||||
|
reader, proc = make_reader(tmp_path, proc_every=3.0, clock=clock)
|
||||||
|
assert reader.read().procs == () # first snapshot
|
||||||
|
clock.t = 1.0
|
||||||
|
write_proc(proc, "cpu 600 0 300 2400 100 0 0 0 0 0", {10: pid_line(10, "postgres", 10)})
|
||||||
|
assert reader.read().procs == () # window not over yet: nothing new to rank
|
||||||
|
clock.t = 3.5
|
||||||
|
write_proc(proc, "cpu 900 0 450 3600 150 0 0 0 0 0", {10: pid_line(10, "postgres", 60)})
|
||||||
|
s = reader.read()
|
||||||
|
# 60 ticks over a jiffy window of 5100 - 1000 = 4100 -> 1.46 %
|
||||||
|
assert [(p.name, round(p.cpu_pct, 2)) for p in s.procs] == [("postgres", 1.46)]
|
||||||
|
clock.t = 4.0
|
||||||
|
assert reader.read().procs == s.procs # between windows the last ranking stays on screen
|
||||||
@@ -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)
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import copy
|
import copy
|
||||||
import json
|
import json
|
||||||
from datetime import datetime
|
from datetime import date, datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import weather_data
|
import weather_data
|
||||||
from weather_data import Icon, icon_for, parse_weather
|
from weather_data import Day, Icon, icon_for, parse_weather
|
||||||
|
|
||||||
FIXTURE = json.loads((Path(__file__).parent / "fixtures" / "open-meteo-zlin.json").read_text())
|
FIXTURE = json.loads((Path(__file__).parent / "fixtures" / "open-meteo-zlin.json").read_text())
|
||||||
NOW = datetime(2026, 10, 22, 12, 45)
|
NOW = datetime(2026, 10, 22, 12, 45)
|
||||||
@@ -24,9 +24,34 @@ def test_parse_fixture_window():
|
|||||||
assert (w.temp, w.code) == (10.2, 61)
|
assert (w.temp, w.code) == (10.2, 61)
|
||||||
|
|
||||||
|
|
||||||
def test_parse_today_max_min():
|
def test_parse_week_with_sunrise_and_sunset():
|
||||||
w = parse_weather(payload(), NOW)
|
w = parse_weather(payload(), NOW)
|
||||||
assert (w.today_max, w.today_min) == (15.0, 6.0)
|
assert len(w.days) == 7
|
||||||
|
assert w.days[0] == Day(date(2026, 10, 22), 63, 15.0, 6.0,
|
||||||
|
datetime(2026, 10, 22, 7, 20), datetime(2026, 10, 22, 17, 45))
|
||||||
|
assert w.days[6] == Day(date(2026, 10, 28), 45, 11.5, -0.5,
|
||||||
|
datetime(2026, 10, 28, 6, 30), datetime(2026, 10, 28, 16, 35))
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_feels_like():
|
||||||
|
assert parse_weather(payload(), NOW).feels == 8.1
|
||||||
|
|
||||||
|
|
||||||
|
def test_null_day_entries_become_none():
|
||||||
|
p = payload()
|
||||||
|
p["daily"]["weather_code"][1] = None
|
||||||
|
p["daily"]["sunset"][1] = None
|
||||||
|
day = parse_weather(p, NOW).days[1]
|
||||||
|
assert (day.code, day.sunset) == (None, None)
|
||||||
|
assert day.sunrise == datetime(2026, 10, 23, 7, 22)
|
||||||
|
|
||||||
|
|
||||||
|
def test_short_daily_lists_give_none_not_errors():
|
||||||
|
p = payload()
|
||||||
|
p["daily"]["temperature_2m_min"] = p["daily"]["temperature_2m_min"][:3]
|
||||||
|
w = parse_weather(p, NOW)
|
||||||
|
assert len(w.days) == 7
|
||||||
|
assert (w.days[2].low, w.days[3].low) == (4.3, None)
|
||||||
|
|
||||||
|
|
||||||
def test_window_runs_into_tomorrow_late_in_the_day():
|
def test_window_runs_into_tomorrow_late_in_the_day():
|
||||||
@@ -74,7 +99,7 @@ def test_missing_current_gives_none_temp():
|
|||||||
|
|
||||||
def test_missing_sections_do_not_raise():
|
def test_missing_sections_do_not_raise():
|
||||||
w = parse_weather({}, NOW)
|
w = parse_weather({}, NOW)
|
||||||
assert (w.temp, w.today_max, w.hours) == (None, None, ())
|
assert (w.temp, w.feels, w.days, w.hours) == (None, None, (), ())
|
||||||
|
|
||||||
|
|
||||||
def test_fetch_passes_coordinates():
|
def test_fetch_passes_coordinates():
|
||||||
@@ -99,3 +124,25 @@ def test_fetch_passes_coordinates():
|
|||||||
assert params["timezone"] == "Europe/Prague"
|
assert params["timezone"] == "Europe/Prague"
|
||||||
assert timeout == 10
|
assert timeout == 10
|
||||||
assert len(w.hours) == 12
|
assert len(w.hours) == 12
|
||||||
|
assert len(w.days) == 7
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_asks_for_a_week_with_sun_times_and_feels_like():
|
||||||
|
seen = {}
|
||||||
|
|
||||||
|
class Response:
|
||||||
|
def raise_for_status(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return payload()
|
||||||
|
|
||||||
|
def fake_get(url, params=None, timeout=None):
|
||||||
|
seen.update(params)
|
||||||
|
return Response()
|
||||||
|
|
||||||
|
weather_data.fetch_weather(NOW, get=fake_get)
|
||||||
|
assert seen["forecast_days"] >= 7
|
||||||
|
assert set(seen["daily"].split(",")) >= {"weather_code", "temperature_2m_max", "temperature_2m_min",
|
||||||
|
"sunrise", "sunset"}
|
||||||
|
assert "apparent_temperature" in seen["current"].split(",")
|
||||||
@@ -1,15 +1,18 @@
|
|||||||
from datetime import datetime
|
from datetime import date, datetime, time, timedelta
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from PIL import ImageChops
|
from PIL import ImageChops
|
||||||
|
|
||||||
from lcdkit import INK
|
from lcdkit import BG, INK
|
||||||
from tests.helpers import count_colour
|
from tests.helpers import count_colour
|
||||||
from view import Patch
|
from view import Patch
|
||||||
from weather_data import Hour, Weather
|
from weather_data import Day, Hour, Weather
|
||||||
from weather_view import WeatherView
|
from weather_view import WeatherView, is_night
|
||||||
|
|
||||||
NOW = datetime(2026, 10, 22, 12, 45, 8) # a Thursday
|
NOW = datetime(2026, 10, 22, 12, 45, 8) # a Thursday
|
||||||
|
CODES = (63, 45, 61, 3, 80, 0, 71)
|
||||||
|
CELL = 65 # width of one day in the forecast strip
|
||||||
|
BAR_X, BAR_PITCH, BAR_W = 22, 37, 26
|
||||||
|
|
||||||
|
|
||||||
class StubPoller:
|
class StubPoller:
|
||||||
@@ -27,9 +30,19 @@ class StubPoller:
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
def weather(temp=14.2, rain=(0, 0, 10, 20, 40, 70, 60, 50, 30, 20, 10, 0), code=2):
|
def day(d: date, sunrise=time(7, 20), sunset=time(17, 45)) -> Day:
|
||||||
|
"""A forecast day whose values depend only on its date."""
|
||||||
|
return Day(d, CODES[d.toordinal() % 7], float(5 + d.day % 10), float(d.day % 5),
|
||||||
|
datetime.combine(d, sunrise), datetime.combine(d, sunset))
|
||||||
|
|
||||||
|
|
||||||
|
def week(start=date(2026, 10, 22), n=7):
|
||||||
|
return tuple(day(start + timedelta(days=i)) for i in range(n))
|
||||||
|
|
||||||
|
|
||||||
|
def weather(temp=14.2, rain=(0, 0, 10, 20, 40, 70, 60, 50, 30, 20, 10, 0), code=2, days=None):
|
||||||
hours = tuple(Hour(datetime(2026, 10, 22, 12 + i, 0), p, 0.2) for i, p in enumerate(rain))
|
hours = tuple(Hour(datetime(2026, 10, 22, 12 + i, 0), p, 0.2) for i, p in enumerate(rain))
|
||||||
return Weather(temp=temp, code=code, today_max=16.0, today_min=7.0, hours=hours)
|
return Weather(temp=temp, feels=12.1, code=code, days=week() if days is None else days, hours=hours)
|
||||||
|
|
||||||
|
|
||||||
def view(**kw):
|
def view(**kw):
|
||||||
@@ -45,6 +58,20 @@ def ink_bbox(img, box):
|
|||||||
return (box[0] + xs.min(), box[1] + ys.min(), box[0] + xs.max(), box[1] + ys.max())
|
return (box[0] + xs.min(), box[1] + ys.min(), box[0] + xs.max(), box[1] + ys.max())
|
||||||
|
|
||||||
|
|
||||||
|
def icon_box(i):
|
||||||
|
cx = 12 + i * CELL + CELL // 2
|
||||||
|
return (cx - 16, 34, cx + 16, 68)
|
||||||
|
|
||||||
|
|
||||||
|
def hour_label_box(i):
|
||||||
|
x = BAR_X + i * BAR_PITCH
|
||||||
|
return (x, 290, x + BAR_W, 304)
|
||||||
|
|
||||||
|
|
||||||
|
def same(a, b):
|
||||||
|
return ImageChops.difference(a.convert("RGB"), b.convert("RGB")).getbbox() is None
|
||||||
|
|
||||||
|
|
||||||
def test_render_size_is_480x320():
|
def test_render_size_is_480x320():
|
||||||
assert view(value=weather()).render(NOW).size == (480, 320)
|
assert view(value=weather()).render(NOW).size == (480, 320)
|
||||||
|
|
||||||
@@ -77,20 +104,20 @@ def test_patch_matches_full_render_region():
|
|||||||
assert isinstance(patch, Patch)
|
assert isinstance(patch, Patch)
|
||||||
full = v.render(NOW)
|
full = v.render(NOW)
|
||||||
region = full.crop((patch.x, patch.y, patch.x + patch.image.width, patch.y + patch.image.height))
|
region = full.crop((patch.x, patch.y, patch.x + patch.image.width, patch.y + patch.image.height))
|
||||||
assert ImageChops.difference(region.convert("RGB"), patch.image.convert("RGB")).getbbox() is None
|
assert same(region, patch.image)
|
||||||
|
|
||||||
|
|
||||||
def test_patch_changes_with_the_second():
|
def test_patch_changes_with_the_second():
|
||||||
v = view(value=weather())
|
v = view(value=weather())
|
||||||
a = v.patch(datetime(2026, 10, 22, 12, 45, 8)).image
|
a = v.patch(datetime(2026, 10, 22, 12, 45, 8)).image
|
||||||
b = v.patch(datetime(2026, 10, 22, 12, 45, 9)).image
|
b = v.patch(datetime(2026, 10, 22, 12, 45, 9)).image
|
||||||
assert ImageChops.difference(a, b).getbbox() is not None
|
assert not same(a, b)
|
||||||
|
|
||||||
|
|
||||||
def test_no_weather_renders_without_error():
|
def test_no_weather_renders_without_error():
|
||||||
img = view(value=None, version=0, age=None).render(NOW)
|
img = view(value=None, version=0, age=None).render(NOW)
|
||||||
assert img.size == (480, 320)
|
assert img.size == (480, 320)
|
||||||
# weekday strip, clock and dashes are still drawn
|
# day names, clock and dashes are still drawn
|
||||||
assert count_colour(img, INK) > 1000
|
assert count_colour(img, INK) > 1000
|
||||||
|
|
||||||
|
|
||||||
@@ -99,35 +126,54 @@ def test_stale_tag_only_when_old():
|
|||||||
old = view(value=weather(), age=7200.0).render(NOW)
|
old = view(value=weather(), age=7200.0).render(NOW)
|
||||||
bbox = ImageChops.difference(fresh.convert("RGB"), old.convert("RGB")).getbbox()
|
bbox = ImageChops.difference(fresh.convert("RGB"), old.convert("RGB")).getbbox()
|
||||||
assert bbox is not None
|
assert bbox is not None
|
||||||
assert bbox[0] >= 20 and bbox[1] >= 160 and bbox[2] <= 204 and bbox[3] <= 186
|
assert bbox[0] >= 20 and bbox[1] >= 200 and bbox[2] <= 300 and bbox[3] <= 226 # on the rain header line
|
||||||
|
|
||||||
|
|
||||||
def test_hundred_percent_fits():
|
def test_today_is_the_first_day_and_inverted():
|
||||||
rain = (100,) * 12
|
img = view(value=weather()).render(NOW)
|
||||||
img = view(value=weather(rain=rain)).render(NOW)
|
assert img.getpixel((12 + 5, 14)) == INK
|
||||||
box = ink_bbox(img, (14, 262, 204, 312))
|
assert img.getpixel((12 + CELL + 5, 14)) != INK
|
||||||
assert box is not None and box[2] < 200
|
|
||||||
|
|
||||||
|
|
||||||
def test_negative_temp_fits_and_draws_minus():
|
def test_days_before_today_are_skipped():
|
||||||
|
# just after midnight the last fetch still starts with yesterday
|
||||||
|
from_yesterday = view(value=weather(days=week(start=date(2026, 10, 21)))).render(NOW)
|
||||||
|
from_today = view(value=weather(days=week(start=date(2026, 10, 22), n=6))).render(NOW)
|
||||||
|
assert same(from_yesterday, from_today)
|
||||||
|
|
||||||
|
|
||||||
|
def test_only_days_with_a_forecast_get_an_icon():
|
||||||
|
img = view(value=weather(days=week(n=3))).render(NOW)
|
||||||
|
for i in range(3):
|
||||||
|
assert ink_bbox(img, icon_box(i)) is not None, i
|
||||||
|
for i in range(3, 7):
|
||||||
|
assert ink_bbox(img, icon_box(i)) is None, i
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_bar_has_its_hour_label():
|
||||||
|
img = view(value=weather()).render(NOW)
|
||||||
|
for i in range(12):
|
||||||
|
assert ink_bbox(img, hour_label_box(i)) is not None, i
|
||||||
|
|
||||||
|
|
||||||
|
def test_hour_labels_only_for_known_hours():
|
||||||
|
img = view(value=weather(rain=(10, 20))).render(NOW)
|
||||||
|
assert ink_bbox(img, hour_label_box(1)) is not None
|
||||||
|
for i in range(2, 12):
|
||||||
|
assert ink_bbox(img, hour_label_box(i)) is None, i
|
||||||
|
|
||||||
|
|
||||||
|
def test_negative_temps_stay_inside_the_frame():
|
||||||
|
for temp in (-3.4, -10.4, -19.6):
|
||||||
|
img = view(value=weather(temp=temp)).render(NOW)
|
||||||
|
box = ink_bbox(img, (380, 104, 471, 150))
|
||||||
|
assert box is not None and box[2] < 466, temp
|
||||||
|
|
||||||
|
|
||||||
|
def test_negative_temp_draws_a_minus():
|
||||||
cold = view(value=weather(temp=-3.4)).render(NOW)
|
cold = view(value=weather(temp=-3.4)).render(NOW)
|
||||||
warm = view(value=weather(temp=3.4)).render(NOW)
|
warm = view(value=weather(temp=3.4)).render(NOW)
|
||||||
cold_box = ink_bbox(cold, (84, 180, 204, 236))
|
assert not same(cold, warm)
|
||||||
assert cold_box is not None and cold_box[2] < 200
|
|
||||||
assert ImageChops.difference(cold.convert("RGB"), warm.convert("RGB")).getbbox() is not None
|
|
||||||
|
|
||||||
|
|
||||||
def test_sunday_inverts_last_weekday_cell():
|
|
||||||
sunday = datetime(2026, 10, 25, 9, 0, 0)
|
|
||||||
img = view(value=weather()).render(sunday)
|
|
||||||
assert img.getpixel((402 + 1, 15)) == INK # NE cell
|
|
||||||
assert img.getpixel((12 + 1, 15)) != INK # PO cell
|
|
||||||
|
|
||||||
|
|
||||||
def test_thursday_inverts_fourth_cell():
|
|
||||||
img = view(value=weather()).render(NOW)
|
|
||||||
assert img.getpixel((12 + 3 * 65 + 1, 15)) == INK # ČT
|
|
||||||
assert img.getpixel((12 + 1, 15)) != INK
|
|
||||||
|
|
||||||
|
|
||||||
def test_fewer_than_twelve_hours_still_renders():
|
def test_fewer_than_twelve_hours_still_renders():
|
||||||
@@ -139,8 +185,52 @@ def test_unknown_weather_code_renders():
|
|||||||
assert view(value=weather(code=999)).render(NOW).size == (480, 320)
|
assert view(value=weather(code=999)).render(NOW).size == (480, 320)
|
||||||
|
|
||||||
|
|
||||||
def test_two_digit_negative_temps_stay_clear_of_the_divider():
|
# night: from sunset to sunrise the frame is a reverse LCD
|
||||||
for temp in (-10.4, -19.6):
|
|
||||||
img = view(value=weather(temp=temp)).render(NOW)
|
def test_is_night_between_sunset_and_sunrise():
|
||||||
box = ink_bbox(img, (84, 180, 204, 236))
|
w = weather() # sunrise 7:20, sunset 17:45
|
||||||
assert box is not None and box[2] < 200, temp
|
assert is_night(datetime(2026, 10, 22, 21, 0), w)
|
||||||
|
assert is_night(datetime(2026, 10, 22, 5, 30), w)
|
||||||
|
assert not is_night(datetime(2026, 10, 22, 12, 45), w)
|
||||||
|
|
||||||
|
|
||||||
|
def test_is_night_flips_exactly_at_sunrise_and_sunset():
|
||||||
|
w = weather()
|
||||||
|
assert not is_night(datetime(2026, 10, 22, 7, 20), w)
|
||||||
|
assert is_night(datetime(2026, 10, 22, 7, 19), w)
|
||||||
|
assert not is_night(datetime(2026, 10, 22, 17, 44), w)
|
||||||
|
assert is_night(datetime(2026, 10, 22, 17, 45), w)
|
||||||
|
|
||||||
|
|
||||||
|
def test_is_night_uses_todays_sun_times():
|
||||||
|
days = (day(date(2026, 10, 21), sunset=time(16, 0)), day(date(2026, 10, 22), sunset=time(17, 45)))
|
||||||
|
assert not is_night(datetime(2026, 10, 22, 16, 30), weather(days=days))
|
||||||
|
|
||||||
|
|
||||||
|
def test_is_night_without_today_uses_the_closest_known_day():
|
||||||
|
# data a week old (fetches failing): sunrise moves only minutes a day, so old times are close enough
|
||||||
|
days = (day(date(2026, 10, 15), sunrise=time(7, 8), sunset=time(17, 58)),)
|
||||||
|
assert is_night(datetime(2026, 10, 22, 21, 0), weather(days=days))
|
||||||
|
assert not is_night(datetime(2026, 10, 22, 12, 0), weather(days=days))
|
||||||
|
|
||||||
|
|
||||||
|
def test_is_night_without_any_forecast_stays_day():
|
||||||
|
assert not is_night(datetime(2026, 10, 22, 23, 0), None)
|
||||||
|
assert not is_night(datetime(2026, 10, 22, 23, 0), weather(days=()))
|
||||||
|
|
||||||
|
|
||||||
|
def test_night_frame_is_dark():
|
||||||
|
night = view(value=weather()).render(datetime(2026, 10, 22, 21, 0, 0))
|
||||||
|
day_ = view(value=weather()).render(NOW)
|
||||||
|
assert sum(night.getpixel((2, 2))) < 100
|
||||||
|
assert day_.getpixel((2, 2)) == BG
|
||||||
|
|
||||||
|
|
||||||
|
def test_night_patch_matches_full_render_region():
|
||||||
|
v = view(value=weather())
|
||||||
|
at = datetime(2026, 10, 22, 21, 0, 8)
|
||||||
|
patch = v.patch(at)
|
||||||
|
full = v.render(at)
|
||||||
|
region = full.crop((patch.x, patch.y, patch.x + patch.image.width, patch.y + patch.image.height))
|
||||||
|
assert same(region, patch.image)
|
||||||
|
assert sum(patch.image.getpixel((0, 0))) < 100
|
||||||
@@ -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()
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"""Open-Meteo forecast for Zlín: fetching and parsing (no drawing)."""
|
"""Open-Meteo forecast for Zlín: fetching and parsing (no drawing)."""
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime
|
from datetime import date, datetime
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
@@ -19,12 +19,22 @@ class Hour:
|
|||||||
mm: float | None
|
mm: float | None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Day:
|
||||||
|
date: date
|
||||||
|
code: int | None
|
||||||
|
high: float | None
|
||||||
|
low: float | None
|
||||||
|
sunrise: datetime | None # naive local time
|
||||||
|
sunset: datetime | None
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class Weather:
|
class Weather:
|
||||||
temp: float | None
|
temp: float | None
|
||||||
|
feels: float | None
|
||||||
code: int | None
|
code: int | None
|
||||||
today_max: float | None
|
days: tuple[Day, ...] # as the forecast gives them, today first when fresh
|
||||||
today_min: float | None
|
|
||||||
hours: tuple[Hour, ...] # at most WINDOW_HOURS, starting with the hour containing "now"
|
hours: tuple[Hour, ...] # at most WINDOW_HOURS, starting with the hour containing "now"
|
||||||
|
|
||||||
|
|
||||||
@@ -61,16 +71,26 @@ def _at(values, i: int):
|
|||||||
return values[i]
|
return values[i]
|
||||||
|
|
||||||
|
|
||||||
|
def _time(value) -> datetime | None:
|
||||||
|
return datetime.fromisoformat(value) if value else None
|
||||||
|
|
||||||
|
|
||||||
def parse_weather(payload: dict, now: datetime) -> Weather:
|
def parse_weather(payload: dict, now: datetime) -> Weather:
|
||||||
current = payload.get("current") or {}
|
current = payload.get("current") or {}
|
||||||
daily = payload.get("daily") or {}
|
daily = payload.get("daily") or {}
|
||||||
hourly = payload.get("hourly") or {}
|
hourly = payload.get("hourly") or {}
|
||||||
|
|
||||||
day = now.strftime("%Y-%m-%d")
|
days = tuple(
|
||||||
days = daily.get("time") or []
|
Day(
|
||||||
d = days.index(day) if day in days else None
|
date=date.fromisoformat(day),
|
||||||
today_max = _at(daily.get("temperature_2m_max"), d) if d is not None else None
|
code=_at(daily.get("weather_code"), i),
|
||||||
today_min = _at(daily.get("temperature_2m_min"), d) if d is not None else None
|
high=_at(daily.get("temperature_2m_max"), i),
|
||||||
|
low=_at(daily.get("temperature_2m_min"), i),
|
||||||
|
sunrise=_time(_at(daily.get("sunrise"), i)),
|
||||||
|
sunset=_time(_at(daily.get("sunset"), i)),
|
||||||
|
)
|
||||||
|
for i, day in enumerate(daily.get("time") or [])
|
||||||
|
)
|
||||||
|
|
||||||
hours: list[Hour] = []
|
hours: list[Hour] = []
|
||||||
times = hourly.get("time") or []
|
times = hourly.get("time") or []
|
||||||
@@ -86,9 +106,9 @@ def parse_weather(payload: dict, now: datetime) -> Weather:
|
|||||||
|
|
||||||
return Weather(
|
return Weather(
|
||||||
temp=current.get("temperature_2m"),
|
temp=current.get("temperature_2m"),
|
||||||
|
feels=current.get("apparent_temperature"),
|
||||||
code=current.get("weather_code"),
|
code=current.get("weather_code"),
|
||||||
today_max=today_max,
|
days=days,
|
||||||
today_min=today_min,
|
|
||||||
hours=tuple(hours),
|
hours=tuple(hours),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -97,11 +117,11 @@ def fetch_weather(now: datetime, get=requests.get) -> Weather:
|
|||||||
params = {
|
params = {
|
||||||
"latitude": LAT,
|
"latitude": LAT,
|
||||||
"longitude": LON,
|
"longitude": LON,
|
||||||
"current": "temperature_2m,weather_code",
|
"current": "temperature_2m,weather_code,apparent_temperature",
|
||||||
"hourly": "precipitation_probability,precipitation",
|
"hourly": "precipitation_probability,precipitation",
|
||||||
"daily": "temperature_2m_max,temperature_2m_min",
|
"daily": "weather_code,temperature_2m_max,temperature_2m_min,sunrise,sunset",
|
||||||
"timezone": TIMEZONE,
|
"timezone": TIMEZONE,
|
||||||
"forecast_days": 2,
|
"forecast_days": 7,
|
||||||
}
|
}
|
||||||
response = get(URL, params=params, timeout=10)
|
response = get(URL, params=params, timeout=10)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
|
|||||||
@@ -1,18 +1,20 @@
|
|||||||
"""Casio-style weather clock: time, date, current weather and a 12 hour rain forecast."""
|
"""Casio-style weather clock: week ahead, time, date, current weather and a 12 hour rain forecast."""
|
||||||
from datetime import datetime
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
from PIL import Image, ImageDraw
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
import lcdkit
|
import lcdkit
|
||||||
from lcdkit import BG, H, INK, W
|
from lcdkit import BG, GHOST, H, INK, W
|
||||||
from poller import Poller
|
from poller import Poller
|
||||||
from view import Patch
|
from view import Patch
|
||||||
from weather_data import Icon, Weather, icon_for
|
from weather_data import Day, Icon, Weather, icon_for
|
||||||
|
|
||||||
WEEKDAYS = ["PO", "ÚT", "ST", "ČT", "PÁ", "SO", "NE"]
|
WEEKDAYS = ["PO", "ÚT", "ST", "ČT", "PÁ", "SO", "NE"]
|
||||||
SECONDS_BOX = (370, 52, 466, 104) # region redrawn once per second
|
CELL = (W - 24) // 7 # one day of the forecast strip
|
||||||
SECONDS_GEOMETRY = dict(x=378, y=58, w=24, h=42, t=6, gap=6)
|
SECONDS_BOX = (288, 104, 352, 148) # region redrawn once per second
|
||||||
GRAPH_X, GRAPH_PITCH, GRAPH_BOTTOM = 222, 21, 282
|
SECONDS_GEOMETRY = dict(x=292, y=108, w=20, h=36, t=5, gap=5)
|
||||||
|
GRAPH_X, GRAPH_PITCH, GRAPH_BOTTOM, BAR_W = 22, 37, 288, 26
|
||||||
|
RAIN_LABEL = "DÉŠŤ % / HOD"
|
||||||
|
|
||||||
|
|
||||||
def _cloud(d: ImageDraw.ImageDraw, x: float, base: float, s: float, outline: bool = False) -> None:
|
def _cloud(d: ImageDraw.ImageDraw, x: float, base: float, s: float, outline: bool = False) -> None:
|
||||||
@@ -31,6 +33,19 @@ def _sun(d: ImageDraw.ImageDraw, cx: float, cy: float, r: float, s: float) -> No
|
|||||||
fill=INK, width=max(2, int(s / 16)))
|
fill=INK, width=max(2, int(s / 16)))
|
||||||
|
|
||||||
|
|
||||||
|
def is_night(now: datetime, weather: Weather | None) -> bool:
|
||||||
|
"""True from sunset until sunrise; the frame is then drawn as a reverse LCD.
|
||||||
|
|
||||||
|
Uses today's sun times, or those of the closest day the forecast has (they move only minutes a day).
|
||||||
|
Without any forecast it stays day.
|
||||||
|
"""
|
||||||
|
days = [day for day in (weather.days if weather else ()) if day.sunrise and day.sunset]
|
||||||
|
if not days:
|
||||||
|
return False
|
||||||
|
day = min(days, key=lambda d: abs((d.date - now.date()).days))
|
||||||
|
return not day.sunrise.time() <= now.time() < day.sunset.time()
|
||||||
|
|
||||||
|
|
||||||
def draw_icon(d: ImageDraw.ImageDraw, icon: Icon | None, x: float, y: float, s: float) -> None:
|
def draw_icon(d: ImageDraw.ImageDraw, icon: Icon | None, x: float, y: float, s: float) -> None:
|
||||||
w = max(2, int(s / 16))
|
w = max(2, int(s / 16))
|
||||||
if icon is Icon.SUN:
|
if icon is Icon.SUN:
|
||||||
@@ -82,83 +97,88 @@ class WeatherView:
|
|||||||
def frame_key(self, now: datetime):
|
def frame_key(self, now: datetime):
|
||||||
return (now.strftime("%Y%m%d%H%M"), self._poller.version, self._is_stale())
|
return (now.strftime("%Y%m%d%H%M"), self._poller.version, self._is_stale())
|
||||||
|
|
||||||
def patch(self, now: datetime) -> Patch:
|
@staticmethod
|
||||||
|
def _seconds(now: datetime) -> Image.Image:
|
||||||
x0, y0, x1, y1 = SECONDS_BOX
|
x0, y0, x1, y1 = SECONDS_BOX
|
||||||
img = Image.new("RGB", (x1 - x0, y1 - y0), BG)
|
img = Image.new("RGB", (x1 - x0, y1 - y0), BG)
|
||||||
g = SECONDS_GEOMETRY
|
g = SECONDS_GEOMETRY
|
||||||
lcdkit.number(ImageDraw.Draw(img), f"{now.second:02d}", g["x"] - x0, g["y"] - y0, g["w"], g["h"],
|
lcdkit.number(ImageDraw.Draw(img), f"{now.second:02d}", g["x"] - x0, g["y"] - y0, g["w"], g["h"],
|
||||||
g["t"], g["gap"])
|
g["t"], g["gap"])
|
||||||
return Patch(img, x0, y0)
|
return img
|
||||||
|
|
||||||
|
def patch(self, now: datetime) -> Patch:
|
||||||
|
img = self._seconds(now)
|
||||||
|
if is_night(now, self._poller.value):
|
||||||
|
img = lcdkit.night(img)
|
||||||
|
return Patch(img, SECONDS_BOX[0], SECONDS_BOX[1])
|
||||||
|
|
||||||
def render(self, now: datetime) -> Image.Image:
|
def render(self, now: datetime) -> Image.Image:
|
||||||
weather: Weather | None = self._poller.value
|
weather: Weather | None = self._poller.value
|
||||||
img = Image.new("RGB", (W, H), BG)
|
img = Image.new("RGB", (W, H), BG)
|
||||||
d = ImageDraw.Draw(img)
|
d = ImageDraw.Draw(img)
|
||||||
f_small, f_tiny = lcdkit.load_font(15), lcdkit.load_font(12)
|
f_small, f_tiny, f_mini = lcdkit.load_font(15), lcdkit.load_font(12), lcdkit.load_font(11)
|
||||||
|
|
||||||
d.rectangle((6, 6, W - 7, H - 7), outline=INK, width=2)
|
d.rectangle((6, 6, W - 7, H - 7), outline=INK, width=2)
|
||||||
self._weekday_strip(d, now, f_small)
|
self._week_strip(d, now, weather, f_small, f_tiny)
|
||||||
d.line((12, 46, W - 13, 46), fill=INK, width=2)
|
d.line((12, 100, W - 13, 100), fill=INK, width=2)
|
||||||
|
|
||||||
# time row: HH:MM, seconds and date on the right
|
# time row: HH:MM, seconds and date, then the weather now
|
||||||
lcdkit.number(d, now.strftime("%H:%M"), 24, 54, 54, 96, 12, 9)
|
lcdkit.number(d, now.strftime("%H:%M"), 22, 108, 48, 82, 11, 8)
|
||||||
x0, y0, _, _ = SECONDS_BOX
|
img.paste(self._seconds(now), SECONDS_BOX[:2])
|
||||||
img.paste(self.patch(now).image, (x0, y0))
|
lcdkit.number(d, now.strftime("%-d.%-m."), 292, 156, 13, 30, 4, 3, ghost=False)
|
||||||
lcdkit.number(d, now.strftime("%-d.%-m."), 372, 112, 14, 34, 4, 4, ghost=False)
|
d.line((376, 108, 376, 192), fill=INK, width=2)
|
||||||
d.line((12, 160, W - 13, 160), fill=INK, width=2)
|
self._current_block(d, weather, f_small, f_mini)
|
||||||
|
d.line((12, 200, W - 13, 200), fill=INK, width=2)
|
||||||
|
|
||||||
self._current_block(d, weather, f_small, f_tiny)
|
|
||||||
d.line((206, 168, 206, H - 14), fill=INK, width=2)
|
|
||||||
self._rain_graph(d, weather, f_small, f_tiny)
|
self._rain_graph(d, weather, f_small, f_tiny)
|
||||||
if self._is_stale():
|
if self._is_stale():
|
||||||
label_w = d.textlength("ZLÍN NYNÍ", font=f_tiny)
|
lcdkit.tag(d, (int(20 + d.textlength(RAIN_LABEL, font=f_tiny) + 8), 203), "STARÉ", f_tiny)
|
||||||
lcdkit.tag(d, (int(22 + label_w + 8), 163), "STARÉ", f_tiny)
|
return lcdkit.night(img) if is_night(now, weather) else img
|
||||||
return img
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _weekday_strip(d: ImageDraw.ImageDraw, now: datetime, font) -> None:
|
def _week_strip(d: ImageDraw.ImageDraw, now: datetime, weather: Weather | None, f_small, f_tiny) -> None:
|
||||||
cell = (W - 24) // 7
|
"""Today and the next six days: name, icon, max and min. Today is inverted."""
|
||||||
for i, name in enumerate(WEEKDAYS):
|
by_date: dict = {day.date: day for day in (weather.days if weather else ())}
|
||||||
x0 = 12 + i * cell
|
for i in range(7):
|
||||||
colour = INK
|
x0 = 12 + i * CELL
|
||||||
if i == now.weekday():
|
cx = x0 + CELL / 2
|
||||||
d.rectangle((x0, 14, x0 + cell - 6, 38), fill=INK)
|
if i:
|
||||||
colour = BG
|
d.line((x0, 16, x0, 92), fill=GHOST, width=1)
|
||||||
text_w = d.textlength(name, font=font)
|
else:
|
||||||
d.text((x0 + (cell - 6 - text_w) / 2, 17), name, font=font, fill=colour)
|
d.rectangle((x0 + 4, 12, x0 + CELL - 4, 32), fill=INK)
|
||||||
|
d.text((cx, 22), WEEKDAYS[(now.weekday() + i) % 7], font=f_small, fill=BG if i == 0 else INK,
|
||||||
|
anchor="mm")
|
||||||
|
day: Day | None = by_date.get(now.date() + timedelta(days=i))
|
||||||
|
if day is not None:
|
||||||
|
draw_icon(d, icon_for(day.code), cx - 15, 36, 30)
|
||||||
|
high = f"{lcdkit.fmt_temp(day.high if day else None)}°"
|
||||||
|
low = f" {lcdkit.fmt_temp(day.low if day else None)}°"
|
||||||
|
x = cx - (d.textlength(high, font=f_small) + d.textlength(low, font=f_tiny)) / 2
|
||||||
|
d.text((x, 90), high, font=f_small, fill=INK, anchor="ls")
|
||||||
|
d.text((x + d.textlength(high, font=f_small), 90), low, font=f_tiny, fill=INK, anchor="ls")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _current_block(d: ImageDraw.ImageDraw, weather: Weather | None, f_small, f_tiny) -> None:
|
def _current_block(d: ImageDraw.ImageDraw, weather: Weather | None, f_small, f_mini) -> None:
|
||||||
d.text((22, 166), "ZLÍN NYNÍ", font=f_tiny, fill=INK)
|
|
||||||
temp = weather.temp if weather else None
|
temp = weather.temp if weather else None
|
||||||
if weather:
|
|
||||||
draw_icon(d, icon_for(weather.code), 20, 182, 56)
|
|
||||||
text = lcdkit.fmt_temp(temp)
|
text = lcdkit.fmt_temp(temp)
|
||||||
w, gap = (26, 7) if len(text) <= 2 else (22, 5) # a third glyph (-10) must stay clear of the divider
|
w, gap = (18, 5) if len(text) <= 2 else (14, 4) # a third glyph (-10) must stay inside the frame
|
||||||
end = lcdkit.number(d, text, 90, 184, w, 46, 6, gap, ghost=False)
|
end = lcdkit.number(d, text, 388, 108, w, 38, 5, gap, ghost=False)
|
||||||
if temp is not None:
|
if temp is not None:
|
||||||
d.ellipse((end + 4, 184, end + 14, 194), outline=INK, width=3)
|
d.ellipse((end, 108, end + 10, 118), outline=INK, width=3)
|
||||||
hi = lcdkit.fmt_temp(weather.today_max) if weather else "--"
|
if weather:
|
||||||
lo = lcdkit.fmt_temp(weather.today_min) if weather else "--"
|
draw_icon(d, icon_for(weather.code), 380, 152, 40)
|
||||||
d.text((22, 244), f"MAX {hi}° MIN {lo}°", font=f_small, fill=INK)
|
d.text((424, 164), "POCIT", font=f_mini, fill=INK)
|
||||||
|
d.text((424, 176), f"{lcdkit.fmt_temp(weather.feels if weather else None)}°", font=f_small, fill=INK)
|
||||||
d.text((22, 264), "DEŠŤ", font=f_tiny, fill=INK)
|
|
||||||
chances = [h.rain_pct for h in (weather.hours if weather else ()) if h.rain_pct is not None]
|
|
||||||
text = str(max(chances)) if chances else "--"
|
|
||||||
x = lcdkit.number(d, text, 22, 279, 18, 28, 4, 6, ghost=False)
|
|
||||||
if chances:
|
|
||||||
d.text((x + 4, 288), "%", font=f_small, fill=INK)
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _rain_graph(d: ImageDraw.ImageDraw, weather: Weather | None, f_small, f_tiny) -> None:
|
def _rain_graph(d: ImageDraw.ImageDraw, weather: Weather | None, f_small, f_tiny) -> None:
|
||||||
d.text((220, 166), "DEŠŤ % / HOD", font=f_tiny, fill=INK)
|
d.text((20, 206), RAIN_LABEL, font=f_tiny, fill=INK)
|
||||||
hours = weather.hours if weather else ()
|
hours = weather.hours if weather else ()
|
||||||
mm = f"{sum(h.mm or 0 for h in hours):.1f} mm" if hours else "-- mm"
|
mm = f"{sum(h.mm or 0 for h in hours):.1f} mm" if hours else "-- mm"
|
||||||
d.text((W - 18 - d.textlength(mm, font=f_small), 164), mm, font=f_small, fill=INK)
|
d.text((W - 18 - d.textlength(mm, font=f_small), 204), mm, font=f_small, fill=INK)
|
||||||
for i in range(12):
|
for i in range(12):
|
||||||
bx = GRAPH_X + i * GRAPH_PITCH
|
bx = GRAPH_X + i * GRAPH_PITCH
|
||||||
hour = hours[i] if i < len(hours) else None
|
hour = hours[i] if i < len(hours) else None
|
||||||
lcdkit.v_bar(d, bx, GRAPH_BOTTOM, hour.rain_pct if hour else None, 14, 16, 5, 1)
|
lcdkit.v_bar(d, bx, GRAPH_BOTTOM, hour.rain_pct if hour else None, BAR_W, 11, 4, 1)
|
||||||
if hour is not None and i % 3 == 0:
|
if hour is not None:
|
||||||
label = f"{hour.time.hour:02d}"
|
d.text((bx + BAR_W / 2, 301), f"{hour.time.hour:02d}", font=f_tiny, fill=INK, anchor="ms")
|
||||||
d.text((bx + 7 - d.textlength(label, font=f_tiny) / 2, 290), label, font=f_tiny, fill=INK)
|
|
||||||