Compare commits
25
Commits
afd649acc5
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
472fe84d1b | ||
|
|
581d12324d | ||
|
|
70b02f865d | ||
|
|
0289150361 | ||
|
|
d093a8747e | ||
|
|
72e8a69b02 | ||
|
|
d0adefe954 | ||
|
|
517f0868db | ||
|
|
0de68bfce0 | ||
|
|
2132262896 | ||
|
|
6c9a1420d2 | ||
|
|
45508b1b68 | ||
|
|
5e64bfb64e | ||
|
|
edba341f30 | ||
|
|
c3a42cf35b | ||
|
|
abe6e9236b | ||
|
|
09f78d1a63 | ||
|
|
ae8c17d8d5 | ||
|
|
0a395fa735 | ||
|
|
6713e09791 | ||
|
|
32f8c288be | ||
|
|
65843aa958 | ||
|
|
37065a5fba | ||
|
|
839c1824a9 | ||
|
|
36e01c4b1c |
No files matched your search
@@ -0,0 +1,7 @@
|
|||||||
|
.git
|
||||||
|
.venv
|
||||||
|
.superpowers
|
||||||
|
.pytest_cache
|
||||||
|
__pycache__
|
||||||
|
tests
|
||||||
|
docs
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
.venv/
|
||||||
|
__pycache__/
|
||||||
|
.superpowers/
|
||||||
|
.pytest_cache/
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
FROM python:3.12-slim
|
||||||
|
|
||||||
|
# Pinned commit of the Turing Smart Screen library (we only need library/).
|
||||||
|
ARG LCD_COMMIT=2b33ab4f00a096916dd6a1174441a53a7ec33b03
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
ADD https://github.com/mathoudebine/turing-smart-screen-python/archive/${LCD_COMMIT}.tar.gz /tmp/lcd.tar.gz
|
||||||
|
RUN mkdir -p /opt/lcd \
|
||||||
|
&& tar -xzf /tmp/lcd.tar.gz -C /opt/lcd --strip-components=1 --wildcards '*/library' \
|
||||||
|
&& rm /tmp/lcd.tar.gz
|
||||||
|
|
||||||
|
ENV LCD_LIB_PATH=/opt/lcd \
|
||||||
|
PYTHONUNBUFFERED=1 \
|
||||||
|
TZ=Europe/Prague
|
||||||
|
|
||||||
|
COPY assets ./assets
|
||||||
|
COPY *.py ./
|
||||||
|
|
||||||
|
CMD ["python", "main.py"]
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
# second-screen
|
||||||
|
|
||||||
|
A second 3.5" Turing Smart Screen (Rev A) on the Coolify home server, next to the bus board
|
||||||
|
(`bus-department-schedule`). One Docker container shows **one view at a time**: a Casio digital watch (slanted
|
||||||
|
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 |
|
||||||
|
|---|---|
|
||||||
|
| `weather` | The week ahead in the Czech weekday strip (today first and inverted: icon, max and min for each day), big `HH:MM` with seconds, date, current temperature and feels-like (`POCIT`) for Zlín, and a 12-hour rain probability bar graph with the hour under every bar and the total mm. From sunset to sunrise the whole screen turns into a reverse LCD (light segments on black) |
|
||||||
|
| `sky` | Star chart of the sky over Zlín right now, as seen lying on your back (north up, east left): bright stars, a few constellations, the planets, the Moon in its real phase, and the sun by day. Beside it: the clock, tonight's full darkness, what is up (height and direction) or rising soon, the next 12 hours of cloud with a one-line summary, and the next visible ISS pass. Redrawn every minute |
|
||||||
|
| `iss` | Dotted world map with day and night (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`.
|
||||||
|
Plan: `docs/superpowers/plans/2026-10-22-second-screen.md`. Previews: `docs/previews/`.
|
||||||
|
|
||||||
|
## Switching views
|
||||||
|
|
||||||
|
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).
|
||||||
|
|
||||||
|
## Add a view
|
||||||
|
|
||||||
|
1. Write a module (any `*.py` in the project root is copied into the image) with a class that follows the `View` protocol in `view.py` (`start`, `stop`, `frame_key`,
|
||||||
|
`render`, `patch`). Put anything slow (network, system reads) in a `Poller` so drawing never blocks.
|
||||||
|
2. Add one entry to `REGISTRY` in `registry.py`.
|
||||||
|
3. Add a line to the table above, a sample to `preview.py`, and tests.
|
||||||
|
|
||||||
|
## Develop (no screen needed)
|
||||||
|
|
||||||
|
python3 -m venv .venv && .venv/bin/pip install -r requirements-dev.txt
|
||||||
|
.venv/bin/pytest
|
||||||
|
.venv/bin/python preview.py # writes docs/previews/weather.png, server.png, sky.png and iss.png
|
||||||
|
|
||||||
|
## Deployment (Coolify)
|
||||||
|
|
||||||
|
- Source: **Public Repository** on Gitea, branch `main`. The repo must stay public: Gitea SSH is disabled,
|
||||||
|
so Coolify cannot use a deploy key.
|
||||||
|
- 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.
|
||||||
|
- **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>'`.
|
||||||
|
- Only one container can hold a screen's serial port. Stop manual copies before deploying.
|
||||||
|
|
||||||
|
### Security note
|
||||||
|
|
||||||
|
The container mounts the Docker socket. Even with `:ro` that gives it full control of Docker on the server
|
||||||
|
(including Coolify, the bus board and everything else), because the API is not read-only. It also mounts the
|
||||||
|
host's `/proc` and `/sys` read-only. This was accepted for this LAN-only home server (owner approved the
|
||||||
|
socket on 2026-10-22). Remove the socket mount and the container list disappears (`NO DOCKER`), everything
|
||||||
|
else keeps working.
|
||||||
|
|
||||||
|
### Running by hand on the server (debugging only)
|
||||||
|
|
||||||
|
ls -l /dev/serial/by-id/
|
||||||
|
docker compose up --build -d
|
||||||
|
docker compose logs -f second-screen
|
||||||
|
|
||||||
|
## If something is wrong
|
||||||
|
|
||||||
|
- **Upside-down:** this screen is mounted the opposite way to the bus board. Set `SCREEN_ORIENTATION` to
|
||||||
|
`REVERSE_LANDSCAPE`.
|
||||||
|
- **Blank screen:** `docker compose logs second-screen`. If the port cannot be opened the app retries every 30 s
|
||||||
|
(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
|
||||||
|
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 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.
|
||||||
|
|
||||||
|
## Config (env vars)
|
||||||
|
|
||||||
|
| Variable | Default | |
|
||||||
|
|---|---|---|
|
||||||
|
| `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_ORIENTATION` | `LANDSCAPE` | `REVERSE_LANDSCAPE` flips it |
|
||||||
|
| `SCREEN_BRIGHTNESS` | `50` | 0–100 |
|
||||||
|
| `BOARD_TZ` | `Europe/Prague` | time zone of the clock |
|
||||||
|
| `LCD_LIB_PATH` | `/opt/lcd` | where the pinned screen library lives in the image |
|
||||||
|
|
||||||
|
The screen library is pinned to one upstream commit in the `Dockerfile` (`LCD_COMMIT`), the same as the bus board.
|
||||||
|
|
||||||
|
## Known limitations
|
||||||
|
|
||||||
|
- 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.
|
||||||
|
- 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
|
||||||
|
package sensor if the host has one, else the hottest thermal zone.
|
||||||
|
- The screen's link moves about 150 KB/s (measured 2026-10-22: a full 480x320 frame takes 1.96 s, a 96x52 box 65 ms),
|
||||||
|
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.
|
||||||
Binary file not shown.
@@ -0,0 +1,202 @@
|
|||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
Binary file not shown.
@@ -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.
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
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)
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
services:
|
||||||
|
second-screen:
|
||||||
|
build: .
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
# Which view to show: weather | server | sky | iss. To switch: edit, commit, push (Coolify deploys on push).
|
||||||
|
VIEW: weather
|
||||||
|
# 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_ORIENTATION: LANDSCAPE
|
||||||
|
SCREEN_BRIGHTNESS: "50"
|
||||||
|
TZ: Europe/Prague
|
||||||
|
BOARD_TZ: Europe/Prague
|
||||||
|
devices:
|
||||||
|
- "${SCREEN_DEVICE:-/dev/serial/by-id/usb-Turing_UsbMonitor_USB35INCHIPSV2-if00}:${SCREEN_DEVICE:-/dev/serial/by-id/usb-Turing_UsbMonitor_USB35INCHIPSV2-if00}"
|
||||||
|
volumes:
|
||||||
|
# Read-only host views for the server stats view.
|
||||||
|
- /proc:/host/proc:ro
|
||||||
|
- /sys:/host/sys:ro
|
||||||
|
# Any file on the host's root filesystem: only used to measure disk usage (statvfs), contents never read.
|
||||||
|
- /etc/hostname:/host/root:ro
|
||||||
|
# Container list. Read-only does not limit the Docker API: this is full control of Docker (see README).
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 57 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 91 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 59 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 51 KiB |
@@ -57,7 +57,7 @@ The owner wants it to be something nice to glance at and something to play with:
|
|||||||
- Device: `/dev/serial/by-id/usb-Turing_UsbMonitor_USB35INCHIPSV2-if00` (currently
|
- Device: `/dev/serial/by-id/usb-Turing_UsbMonitor_USB35INCHIPSV2-if00` (currently
|
||||||
`ttyACM1`). The bus board uses `/dev/serial/by-id/usb-2017-2-25_UsbMonitor_USB35INCHIPSV2-if00`.
|
`ttyACM1`). The bus board uses `/dev/serial/by-id/usb-2017-2-25_UsbMonitor_USB35INCHIPSV2-if00`.
|
||||||
Always use by-id paths, never `ttyACM*`.
|
Always use by-id paths, never `ttyACM*`.
|
||||||
- Server: reach with `ssh coolify` (user `rickzkm`, in the `docker` group, no passwordless sudo).
|
- Server: reach with `ssh coolify` (the owner's SSH alias).
|
||||||
Deploy via Coolify: public Gitea repo (`https://gitea.madeinzlin.cz/rickzkm/<repo>.git`,
|
Deploy via Coolify: public Gitea repo (`https://gitea.madeinzlin.cz/rickzkm/<repo>.git`,
|
||||||
branch `main`; the repo must stay public because Gitea SSH is disabled), build pack
|
branch `main`; the repo must stay public because Gitea SSH is disabled), build pack
|
||||||
Docker Compose, compose location `/docker-compose.yml`, press Deploy after `git push`
|
Docker Compose, compose location `/docker-compose.yml`, press Deploy after `git push`
|
||||||
@@ -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.
|
||||||
+168
@@ -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")
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
"""Casio-LCD drawing kit: slanted 7-segment digits, segmented bars, fonts, small labels."""
|
||||||
|
from functools import lru_cache
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Sequence
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
|
|
||||||
|
W, H = 480, 320
|
||||||
|
BG = (170, 184, 154)
|
||||||
|
INK = (28, 36, 24)
|
||||||
|
GHOST = (158, 172, 143) # unlit segments, barely darker than the background
|
||||||
|
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"
|
||||||
|
SEGMENT_GAP = 1.5
|
||||||
|
|
||||||
|
DIGIT_SEGMENTS = {
|
||||||
|
"0": "abcdef", "1": "bc", "2": "abdeg", "3": "abcdg", "4": "bcfg",
|
||||||
|
"5": "acdfg", "6": "acdefg", "7": "abc", "8": "abcdefg", "9": "abcdfg",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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]]:
|
||||||
|
return [(x + SLANT * (base_y - y), y) for x, y in points]
|
||||||
|
|
||||||
|
|
||||||
|
def _hexseg(horizontal: bool, c0: float, c1: float, c: float, t: float) -> list[tuple[float, float]]:
|
||||||
|
"""Hexagonal segment along the centre line c, from c0 to c1, thickness t."""
|
||||||
|
if horizontal:
|
||||||
|
return [(c0, c), (c0 + t / 2, c - t / 2), (c1 - t / 2, c - t / 2),
|
||||||
|
(c1, c), (c1 - t / 2, c + t / 2), (c0 + t / 2, c + t / 2)]
|
||||||
|
return [(c, c0), (c + t / 2, c0 + t / 2), (c + t / 2, c1 - t / 2),
|
||||||
|
(c, c1), (c - t / 2, c1 - t / 2), (c - t / 2, c0 + t / 2)]
|
||||||
|
|
||||||
|
|
||||||
|
def _advance(ch: str, w: float, t: float, gap: float) -> float:
|
||||||
|
if ch == ":":
|
||||||
|
return t * 1.1 * 2 + gap
|
||||||
|
if ch == ".":
|
||||||
|
return t + gap
|
||||||
|
return w + gap
|
||||||
|
|
||||||
|
|
||||||
|
def _digit(d: ImageDraw.ImageDraw, ch: str, x: float, y: float, w: float, h: float, t: float, ghost: bool) -> None:
|
||||||
|
g = SEGMENT_GAP
|
||||||
|
top, mid, bot = y + t / 2, y + h / 2, y + h - t / 2
|
||||||
|
left, right = x + t / 2, x + w - t / 2
|
||||||
|
geometry = {
|
||||||
|
"a": _hexseg(True, left + g, right - g, top, t),
|
||||||
|
"g": _hexseg(True, left + g, right - g, mid, t),
|
||||||
|
"d": _hexseg(True, left + g, right - g, bot, t),
|
||||||
|
"f": _hexseg(False, top + g, mid - g, left, t),
|
||||||
|
"b": _hexseg(False, top + g, mid - g, right, t),
|
||||||
|
"e": _hexseg(False, mid + g, bot - g, left, t),
|
||||||
|
"c": _hexseg(False, mid + g, bot - g, right, t),
|
||||||
|
}
|
||||||
|
lit = DIGIT_SEGMENTS.get(ch, "")
|
||||||
|
for name, points in geometry.items():
|
||||||
|
if name in lit or ghost:
|
||||||
|
d.polygon(_slant(points, y + h), fill=INK if name in lit else GHOST)
|
||||||
|
|
||||||
|
|
||||||
|
def number(d: ImageDraw.ImageDraw, text: str, x: float, y: float, w: float, h: float, t: float,
|
||||||
|
gap: float, ghost: bool = True) -> float:
|
||||||
|
"""Draw `0-9 : . -` as slanted 7-segment glyphs (a space is an empty cell).
|
||||||
|
|
||||||
|
Returns x after the last glyph, including the trailing gap.
|
||||||
|
"""
|
||||||
|
for ch in text:
|
||||||
|
if ch == ":":
|
||||||
|
s = t * 1.1
|
||||||
|
for cy in (y + h * 0.32, y + h * 0.68):
|
||||||
|
square = [(x + s / 2, cy - s / 2), (x + s * 1.5, cy - s / 2),
|
||||||
|
(x + s * 1.5, cy + s / 2), (x + s / 2, cy + s / 2)]
|
||||||
|
d.polygon(_slant(square, y + h), fill=INK)
|
||||||
|
elif ch == ".":
|
||||||
|
dot = [(x, y + h - t), (x + t, y + h - t), (x + t, y + h), (x, y + h)]
|
||||||
|
d.polygon(_slant(dot, y + h), fill=INK)
|
||||||
|
elif ch == "-":
|
||||||
|
d.polygon(_slant(_hexseg(True, x + t, x + w - t, y + h / 2, t), y + h), fill=INK)
|
||||||
|
elif ch != " ":
|
||||||
|
_digit(d, ch, x, y, w, h, t, ghost)
|
||||||
|
x += _advance(ch, w, t, gap)
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
|
def number_width(text: str, w: float, t: float, gap: float) -> float:
|
||||||
|
"""Horizontal space `number` uses for `text`."""
|
||||||
|
return sum(_advance(ch, w, t, gap) for ch in text)
|
||||||
|
|
||||||
|
|
||||||
|
def _lit_segments(pct: float | None, n_seg: int) -> int:
|
||||||
|
if pct is None:
|
||||||
|
return 0
|
||||||
|
return max(0, min(n_seg, round(pct / 100 * n_seg)))
|
||||||
|
|
||||||
|
|
||||||
|
def v_bar(d: ImageDraw.ImageDraw, x: float, y_bottom: float, pct: float | None, w: float,
|
||||||
|
n_seg: int, seg_h: float, gap: float) -> None:
|
||||||
|
"""Vertical segmented bar growing upwards from y_bottom; pct None draws it all unlit."""
|
||||||
|
lit = _lit_segments(pct, n_seg)
|
||||||
|
for k in range(n_seg):
|
||||||
|
y1 = y_bottom - k * (seg_h + gap)
|
||||||
|
d.rectangle((x, y1 - seg_h, x + w - 1, y1 - 1), fill=INK if k < lit else GHOST)
|
||||||
|
|
||||||
|
|
||||||
|
def h_bar(d: ImageDraw.ImageDraw, x: float, y: float, pct: float | None, h: float,
|
||||||
|
n_seg: int, seg_w: float, gap: float) -> None:
|
||||||
|
"""Horizontal segmented bar growing to the right; pct None draws it all unlit."""
|
||||||
|
lit = _lit_segments(pct, n_seg)
|
||||||
|
for i in range(n_seg):
|
||||||
|
x0 = x + i * (seg_w + gap)
|
||||||
|
d.rectangle((x0, y, x0 + seg_w - 1, y + h - 1), fill=INK if i < lit else GHOST)
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=None)
|
||||||
|
def load_font(size: int) -> ImageFont.FreeTypeFont:
|
||||||
|
return ImageFont.truetype(str(FONT_PATH), size)
|
||||||
|
|
||||||
|
|
||||||
|
def tag(d: ImageDraw.ImageDraw, xy: tuple[int, int], text: str, font: ImageFont.FreeTypeFont) -> tuple[int, int, int, int]:
|
||||||
|
"""Inverted label (background-coloured text on an ink box); returns the box."""
|
||||||
|
pad = 3
|
||||||
|
left, top, right, bottom = d.textbbox((0, 0), text, font=font)
|
||||||
|
x, y = xy
|
||||||
|
box = (x, y, x + (right - left) + 2 * pad, y + (bottom - top) + 2 * pad)
|
||||||
|
d.rectangle(box, fill=INK)
|
||||||
|
d.text((x + pad - left, y + pad - top), text, font=font, fill=BG)
|
||||||
|
return box
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_temp(value: float | None) -> str:
|
||||||
|
"""Whole-degree text; `--` when unknown; never `-0`."""
|
||||||
|
if value is None:
|
||||||
|
return "--"
|
||||||
|
rounded = round(value)
|
||||||
|
return "0" if rounded == 0 else str(int(rounded))
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""Container entry point: show the view named by VIEW on the second Turing screen."""
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import signal
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
|
||||||
|
import registry
|
||||||
|
import runner
|
||||||
|
from timeutil import local_now
|
||||||
|
|
||||||
|
DEFAULT_DEVICE = "/dev/serial/by-id/usb-Turing_UsbMonitor_USB35INCHIPSV2-if00"
|
||||||
|
|
||||||
|
# force=True: the screen library configures logging at import, which would swallow ours.
|
||||||
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", force=True)
|
||||||
|
log = logging.getLogger("main")
|
||||||
|
|
||||||
|
|
||||||
|
def _open_lcd(device: str, orientation_name: str, brightness: int):
|
||||||
|
from library.lcd.lcd_comm import Orientation # the screen library lives outside the project
|
||||||
|
from library.lcd.lcd_comm_rev_a import LcdCommRevA
|
||||||
|
|
||||||
|
lcd = LcdCommRevA(com_port=device) if device != "AUTO" else LcdCommRevA()
|
||||||
|
lcd.InitializeComm()
|
||||||
|
lcd.SetOrientation(Orientation[orientation_name])
|
||||||
|
lcd.SetBrightness(brightness)
|
||||||
|
return lcd
|
||||||
|
|
||||||
|
|
||||||
|
def main(stop: threading.Event | None = None) -> None:
|
||||||
|
stop = stop or threading.Event()
|
||||||
|
view_name = os.environ.get("VIEW", "")
|
||||||
|
device = os.environ.get("SCREEN_DEVICE", DEFAULT_DEVICE)
|
||||||
|
orientation = os.environ.get("SCREEN_ORIENTATION", "LANDSCAPE")
|
||||||
|
brightness = int(os.environ.get("SCREEN_BRIGHTNESS", "50"))
|
||||||
|
sys.path.insert(0, os.environ.get("LCD_LIB_PATH", "/opt/lcd"))
|
||||||
|
|
||||||
|
def running() -> bool:
|
||||||
|
return not stop.is_set()
|
||||||
|
|
||||||
|
log.info("Opening display on %s (%s), view %r", device, orientation, view_name)
|
||||||
|
lcd = runner.open_screen(lambda: _open_lcd(device, orientation, brightness), running=running, sleep=stop.wait)
|
||||||
|
if lcd is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
view = registry.make_view(view_name)
|
||||||
|
except registry.UnknownView as exc:
|
||||||
|
log.error("%s", exc)
|
||||||
|
runner.idle_with_message(
|
||||||
|
lcd, [f"UNKNOWN VIEW: {view_name or '(VIEW not set)'}", "VALID: " + ", ".join(exc.valid)],
|
||||||
|
running=running, sleep=stop.wait)
|
||||||
|
return
|
||||||
|
view.start()
|
||||||
|
try:
|
||||||
|
runner.run(view, lcd, now_fn=local_now, running=running, sleep=stop.wait)
|
||||||
|
finally:
|
||||||
|
view.stop()
|
||||||
|
finally:
|
||||||
|
lcd.closeSerial()
|
||||||
|
log.info("Stopped")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
event = threading.Event()
|
||||||
|
signal.signal(signal.SIGTERM, lambda *_: event.set())
|
||||||
|
signal.signal(signal.SIGINT, lambda *_: event.set())
|
||||||
|
main(event)
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
"""Background fetcher: keeps the last good value so a slow or failing source never blocks drawing."""
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from typing import Callable, Generic, TypeVar
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
T = TypeVar("T")
|
||||||
|
MAX_RETRY_S = 60.0
|
||||||
|
|
||||||
|
|
||||||
|
class Poller(Generic[T]):
|
||||||
|
def __init__(self, fetch: Callable[[], T], interval: float,
|
||||||
|
clock: Callable[[], float] = time.monotonic, retry: float = MAX_RETRY_S) -> None:
|
||||||
|
self._fetch = fetch
|
||||||
|
self._interval = interval
|
||||||
|
self._retry = retry
|
||||||
|
self._clock = clock
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._value: T | None = None
|
||||||
|
self._version = 0
|
||||||
|
self._failures = 0
|
||||||
|
self._updated_at: float | None = None
|
||||||
|
self._stop = threading.Event()
|
||||||
|
self._thread: threading.Thread | None = None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def value(self) -> T | None:
|
||||||
|
with self._lock:
|
||||||
|
return self._value
|
||||||
|
|
||||||
|
@property
|
||||||
|
def version(self) -> int:
|
||||||
|
with self._lock:
|
||||||
|
return self._version
|
||||||
|
|
||||||
|
@property
|
||||||
|
def failures(self) -> int:
|
||||||
|
with self._lock:
|
||||||
|
return self._failures
|
||||||
|
|
||||||
|
def age(self) -> float | None:
|
||||||
|
"""Seconds since the last successful fetch, None if there has been none."""
|
||||||
|
with self._lock:
|
||||||
|
return None if self._updated_at is None else self._clock() - self._updated_at
|
||||||
|
|
||||||
|
def poll_once(self) -> bool:
|
||||||
|
"""Run the fetch now; never raises. Returns whether it succeeded."""
|
||||||
|
try:
|
||||||
|
value = self._fetch()
|
||||||
|
except Exception as exc:
|
||||||
|
with self._lock:
|
||||||
|
self._failures += 1
|
||||||
|
first_in_streak = self._failures == 1
|
||||||
|
if first_in_streak:
|
||||||
|
log.warning("fetch failed: %s", exc)
|
||||||
|
return False
|
||||||
|
with self._lock:
|
||||||
|
recovered = self._failures > 0
|
||||||
|
self._value = value
|
||||||
|
self._version += 1
|
||||||
|
self._failures = 0
|
||||||
|
self._updated_at = self._clock()
|
||||||
|
if recovered:
|
||||||
|
log.info("fetch recovered")
|
||||||
|
return True
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
if self._thread is not None:
|
||||||
|
return
|
||||||
|
self._thread = threading.Thread(target=self._loop, name="poller", daemon=True)
|
||||||
|
self._thread.start()
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
self._stop.set()
|
||||||
|
if self._thread is not None:
|
||||||
|
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:
|
||||||
|
while not self._stop.is_set():
|
||||||
|
self._stop.wait(self.wait_after(self.poll_once()))
|
||||||
+124
@@ -0,0 +1,124 @@
|
|||||||
|
"""Render every view with fake data to docs/previews/*.png (no screen, no network needed)."""
|
||||||
|
import json
|
||||||
|
from datetime import date, datetime, time, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from iss_view import IssView
|
||||||
|
from lcdkit import H, W
|
||||||
|
from sky_data import parse_clouds, parse_tle
|
||||||
|
from sky_view import SkyView
|
||||||
|
from weather_data import Day, Hour, Weather
|
||||||
|
from server_view import ServerView
|
||||||
|
from stats_data import Container, Proc, Stats
|
||||||
|
from weather_view import WeatherView
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
class FakePoller:
|
||||||
|
def __init__(self, value, age: float | None = 60.0):
|
||||||
|
self.value, self.version, self.failures, self._age = value, 1 if value is not None else 0, 0, age
|
||||||
|
|
||||||
|
def age(self):
|
||||||
|
return self._age
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
|
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:
|
||||||
|
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))
|
||||||
|
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:
|
||||||
|
rows = -(-len(images) // columns)
|
||||||
|
out = Image.new("RGB", (columns * W + (columns - 1) * 20, rows * H + (rows - 1) * 20), (40, 40, 40))
|
||||||
|
for i, img in enumerate(images):
|
||||||
|
out.paste(img, ((i % columns) * (W + 20), (i // columns) * (H + 20)))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def weather_previews() -> Image.Image:
|
||||||
|
cases = [
|
||||||
|
(FakePoller(fake_weather()), NOW),
|
||||||
|
(FakePoller(fake_weather(temp=-3.4, rain=(100,) * 12, code=71)), NOW),
|
||||||
|
(FakePoller(None, age=None), NOW),
|
||||||
|
(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, now in cases])
|
||||||
|
|
||||||
|
|
||||||
|
REAL_NAMES = ["coolify", "coolify-db", "coolify-redis", "coolify-sentinel", "gitea", "jn5mdu87", "task-runners",
|
||||||
|
"n8n", "plex", "ntfy", "coolify-proxy", "screen", "pump-monitor"]
|
||||||
|
|
||||||
|
|
||||||
|
def fake_stats(**kw) -> Stats:
|
||||||
|
base = dict(
|
||||||
|
cpu_pct=14.0, mem_pct=13.9, disk_pct=6.0, load=(0.6, 0.52, 0.44), temp_c=41.0, uptime_s=934423.0,
|
||||||
|
containers=tuple(Container(n, "running", None if n in ("screen", "jn5mdu87", "coolify-sentinel") else "healthy")
|
||||||
|
for n in REAL_NAMES) + (Container("apod-test", "exited", None),),
|
||||||
|
procs=(Proc("postgres", 4.5), Proc("n8n", 2.1), Proc("plex", 1.4), Proc("dockerd", 0.8), Proc("python", 0.3)),
|
||||||
|
)
|
||||||
|
base.update(kw)
|
||||||
|
return Stats(**base)
|
||||||
|
|
||||||
|
|
||||||
|
def server_previews() -> Image.Image:
|
||||||
|
many = tuple(Container(f"service-{i}", "running", "healthy") for i in range(20)) + (
|
||||||
|
Container("web", "running", "unhealthy"), Container("worker", "restarting", None))
|
||||||
|
cases = [
|
||||||
|
FakePoller(fake_stats(), age=2.0),
|
||||||
|
FakePoller(fake_stats(containers=None, temp_c=None, load=None), age=2.0),
|
||||||
|
FakePoller(fake_stats(containers=many, cpu_pct=100.0, mem_pct=87.0, disk_pct=93.0, temp_c=72.0), age=2.0),
|
||||||
|
FakePoller(fake_stats(), age=120.0),
|
||||||
|
]
|
||||||
|
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:
|
||||||
|
OUT.mkdir(parents=True, exist_ok=True)
|
||||||
|
for name, image in (("weather", weather_previews()), ("server", server_previews()), ("sky", sky_previews()),
|
||||||
|
("iss", iss_previews())):
|
||||||
|
image.save(OUT / f"{name}.png")
|
||||||
|
print(OUT / f"{name}.png")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
[pytest]
|
||||||
|
pythonpath = .
|
||||||
|
testpaths = tests
|
||||||
+35
@@ -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
|
||||||
+64
@@ -0,0 +1,64 @@
|
|||||||
|
"""The views the container can show, selected by the VIEW env var."""
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
from iss_view import IssView
|
||||||
|
from poller import Poller
|
||||||
|
from server_view import ServerView
|
||||||
|
from sky_data import fetch_clouds, fetch_tle
|
||||||
|
from sky_view import SkyView
|
||||||
|
from stats_data import StatsReader
|
||||||
|
from timeutil import local_now
|
||||||
|
from view import View
|
||||||
|
from weather_data import fetch_weather
|
||||||
|
from weather_view import WeatherView
|
||||||
|
|
||||||
|
WEATHER_REFRESH_S = 15 * 60
|
||||||
|
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):
|
||||||
|
def __init__(self, name: str, valid: list[str]) -> None:
|
||||||
|
super().__init__(f"unknown view {name!r}; valid views: {', '.join(valid)}")
|
||||||
|
self.name = name
|
||||||
|
self.valid = valid
|
||||||
|
|
||||||
|
|
||||||
|
def _weather() -> View:
|
||||||
|
return WeatherView(Poller(lambda: fetch_weather(local_now()), WEATHER_REFRESH_S))
|
||||||
|
|
||||||
|
|
||||||
|
def _server() -> View:
|
||||||
|
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.
|
||||||
|
REGISTRY: dict[str, Callable[[], View]] = {
|
||||||
|
"weather": _weather,
|
||||||
|
"server": _server,
|
||||||
|
"sky": _sky,
|
||||||
|
"iss": _iss,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def make_view(name: str) -> View:
|
||||||
|
try:
|
||||||
|
factory = REGISTRY[name]
|
||||||
|
except KeyError:
|
||||||
|
raise UnknownView(name, sorted(REGISTRY)) from None
|
||||||
|
return factory()
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-r requirements.txt
|
||||||
|
pytest>=8
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
Pillow>=11.0
|
||||||
|
numpy>=2.0
|
||||||
|
pyserial~=3.5
|
||||||
|
requests>=2.32
|
||||||
|
ephem~=4.2
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""Draw a view on the screen: full frames when it changes, partial patches in between."""
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any, Callable, Sequence
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
import lcdkit
|
||||||
|
from lcdkit import BG, H, INK, W
|
||||||
|
from regions import changed_regions
|
||||||
|
from view import View
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
TICK_S = 0.05
|
||||||
|
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:
|
||||||
|
img = Image.new("RGB", (W, H), BG)
|
||||||
|
d = ImageDraw.Draw(img)
|
||||||
|
d.rectangle((6, 6, W - 7, H - 7), outline=INK, width=2)
|
||||||
|
lcdkit.tag(d, (14, 14), "ERROR", lcdkit.load_font(18))
|
||||||
|
font = lcdkit.load_font(18)
|
||||||
|
for i, line in enumerate(lines):
|
||||||
|
while line and d.textlength(line, font=font) > W - 40:
|
||||||
|
line = line[:-1]
|
||||||
|
d.text((20, 60 + i * 30), line, font=font, fill=INK)
|
||||||
|
return img
|
||||||
|
|
||||||
|
|
||||||
|
def open_screen(factory: Callable[[], Any], *, running: Callable[[], bool],
|
||||||
|
sleep: Callable[[float], None] = time.sleep, retry_s: float = OPEN_RETRY_S) -> Any | None:
|
||||||
|
"""Call `factory` until it returns a screen; None if `running()` turns false first. Logs the first failure only."""
|
||||||
|
logged = False
|
||||||
|
while running():
|
||||||
|
try:
|
||||||
|
return factory()
|
||||||
|
except (Exception, SystemExit) as exc: # the screen library calls sys.exit(0) when the port is missing
|
||||||
|
if not logged:
|
||||||
|
log.warning("screen not available (%s); retrying every %.0f s", exc, retry_s)
|
||||||
|
logged = True
|
||||||
|
sleep(retry_s)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def idle_with_message(lcd, lines: Sequence[str], *, running: Callable[[], bool],
|
||||||
|
sleep: Callable[[float], None] = time.sleep) -> None:
|
||||||
|
"""Show an error message and stay alive (holding the port) until stopped."""
|
||||||
|
try:
|
||||||
|
lcd.DisplayPILImage(render_error(lines), 0, 0)
|
||||||
|
except Exception:
|
||||||
|
log.exception("could not draw the error message")
|
||||||
|
while running():
|
||||||
|
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],
|
||||||
|
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_second = None
|
||||||
|
shown: Image.Image | None = None # what the screen is believed to show; None when unknown
|
||||||
|
last_full = 0.0
|
||||||
|
failures = 0
|
||||||
|
while running():
|
||||||
|
now = now_fn()
|
||||||
|
try:
|
||||||
|
key = view.frame_key(now)
|
||||||
|
if key != last_key:
|
||||||
|
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
|
||||||
|
elif now.second != last_second:
|
||||||
|
patch = view.patch(now)
|
||||||
|
if patch is not None:
|
||||||
|
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
|
||||||
|
failures = 0
|
||||||
|
except (Exception, SystemExit): # SystemExit: the library exits when it cannot reopen the port
|
||||||
|
log.exception("draw failed")
|
||||||
|
failures += 1
|
||||||
|
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:
|
||||||
|
raise # let Docker restart the process and reopen the port
|
||||||
|
sleep(TICK_S)
|
||||||
+149
@@ -0,0 +1,149 @@
|
|||||||
|
"""Cyberpunk-style server stats: CPU/RAM/disk gauges, load, temperature, uptime, containers, busiest processes."""
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
import cyber
|
||||||
|
from cyber import CYAN, GREY, INK, MAGENTA, RED, TEXT, W, H, YELLOW
|
||||||
|
from poller import Poller
|
||||||
|
from stats_data import Container, Stats, status_label
|
||||||
|
from view import Patch
|
||||||
|
|
||||||
|
TITLE = "HOME // SERVER"
|
||||||
|
ATTENTION = ("UNHEALTHY", "RESTART", "EXITED")
|
||||||
|
CONTAINER_ROWS = 5
|
||||||
|
GAUGES = (("CPU", "cpu_pct", 54), ("RAM", "mem_pct", 94), ("DISK", "disk_pct", 134))
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_uptime(seconds: float | None) -> str:
|
||||||
|
if seconds is None:
|
||||||
|
return "--"
|
||||||
|
minutes = int(seconds // 60)
|
||||||
|
days, rest = divmod(minutes, 24 * 60)
|
||||||
|
hours, minutes = divmod(rest, 60)
|
||||||
|
if days:
|
||||||
|
return f"{days}D {hours}H"
|
||||||
|
return f"{hours}H {minutes}M" if hours else f"{minutes}M"
|
||||||
|
|
||||||
|
|
||||||
|
class ServerView:
|
||||||
|
name = "server"
|
||||||
|
STALE_AFTER = 10.0 # seconds without a successful read before the numbers are marked old
|
||||||
|
|
||||||
|
def __init__(self, poller: Poller[Stats]) -> None:
|
||||||
|
self._poller = poller
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
self._poller.start()
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
self._poller.stop()
|
||||||
|
|
||||||
|
def _is_stale(self) -> bool:
|
||||||
|
age = self._poller.age()
|
||||||
|
return age is not None and age > self.STALE_AFTER
|
||||||
|
|
||||||
|
def frame_key(self, now: datetime):
|
||||||
|
return (self._poller.version, self._is_stale())
|
||||||
|
|
||||||
|
def patch(self, now: datetime) -> Patch | None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def render(self, now: datetime) -> Image.Image:
|
||||||
|
stats: Stats | None = self._poller.value
|
||||||
|
img = cyber.background()
|
||||||
|
d = ImageDraw.Draw(img)
|
||||||
|
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)
|
||||||
|
|
||||||
|
self._header(d, stats)
|
||||||
|
self._gauges(d, stats)
|
||||||
|
self._load_and_temp(d, stats)
|
||||||
|
d.line((22, 176, 318, 176), fill=YELLOW, width=1)
|
||||||
|
self._docker(d, stats)
|
||||||
|
d.line((324, 190, 324, H - 22), fill=YELLOW, width=1)
|
||||||
|
self._processes(d, stats)
|
||||||
|
return img
|
||||||
|
|
||||||
|
def _header(self, d: ImageDraw.ImageDraw, stats: Stats | None) -> None:
|
||||||
|
box = cyber.tag(d, (22, 14), TITLE, cyber.font(22))
|
||||||
|
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():
|
||||||
|
cyber.tag(d, (W - 22 - 70, 14), "STARÉ", cyber.font(16), colour=RED)
|
||||||
|
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
|
||||||
|
def _gauges(d: ImageDraw.ImageDraw, stats: Stats | None) -> None:
|
||||||
|
big = cyber.font(36)
|
||||||
|
for label, field, y in GAUGES:
|
||||||
|
pct = getattr(stats, field) if stats else None
|
||||||
|
d.text((24, y), label, font=cyber.font(15), fill=CYAN)
|
||||||
|
cyber.slanted_bar(d, 24, y + 22, pct, 10, 21, 7, 3)
|
||||||
|
text = "--" if pct is None else str(round(pct))
|
||||||
|
cyber.glitch_text(d, (246, y - 4), text, big)
|
||||||
|
if pct is not None:
|
||||||
|
d.text((246 + d.textlength(text, font=big) + 4, y + 8), "%", font=cyber.font(16), fill=CYAN)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _load_and_temp(d: ImageDraw.ImageDraw, stats: Stats | None) -> None:
|
||||||
|
load = stats.load if stats else None
|
||||||
|
cyber.chamfer(d, (330, 56, W - 22, 108), 8, outline=CYAN, cuts="tr bl")
|
||||||
|
d.text((340, 58), "LOAD AVG", font=cyber.font(13, False), fill=GREY)
|
||||||
|
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
|
||||||
|
cyber.chamfer(d, (330, 114, W - 22, 166), 8, outline=CYAN, cuts="tr bl")
|
||||||
|
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
|
||||||
|
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
|
||||||
|
if containers is None:
|
||||||
|
d.text((24, 226), "NO DOCKER", font=cyber.font(26), fill=RED)
|
||||||
|
d.text((24, 256), "SOCKET UNAVAILABLE", font=cyber.font(13, False), fill=GREY)
|
||||||
|
return
|
||||||
|
running = sum(1 for c in containers if c.state == "running")
|
||||||
|
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))
|
||||||
|
y = 202
|
||||||
|
for c in ordered[:CONTAINER_ROWS]:
|
||||||
|
ServerView._container_row(d, c, y)
|
||||||
|
y += 17
|
||||||
|
if len(ordered) > CONTAINER_ROWS:
|
||||||
|
d.text((24, y + 1), f"+{len(ordered) - CONTAINER_ROWS} MORE", font=cyber.font(13, False), fill=GREY)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _container_row(d: ImageDraw.ImageDraw, c: Container, y: int) -> None:
|
||||||
|
label = status_label(c)
|
||||||
|
d.text((24, y), cyber.fit(d, c.name.upper(), cyber.font(15), 226), font=cyber.font(15), fill=TEXT)
|
||||||
|
if label in ATTENTION:
|
||||||
|
colour = MAGENTA if label == "RESTART" else RED
|
||||||
|
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:
|
||||||
|
d.text((312 - d.textlength(label, font=cyber.font(13)), y), label, font=cyber.font(13), fill=CYAN)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _processes(d: ImageDraw.ImageDraw, stats: Stats | None) -> None:
|
||||||
|
d.text((336, 180), "TOP PROCESSES", font=cyber.font(16), fill=YELLOW)
|
||||||
|
y = 204
|
||||||
|
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}%"
|
||||||
|
d.text((W - 24 - d.textlength(pct, font=cyber.font(15)), y), pct, font=cyber.font(15), fill=YELLOW)
|
||||||
|
d.rectangle((336, y + 17, 336 + int(min(proc.cpu_pct, 10) * 11), y + 18), fill=MAGENTA)
|
||||||
|
y += 22
|
||||||
+79
@@ -0,0 +1,79 @@
|
|||||||
|
"""ISS orbit from CelesTrak and cloud cover from Open-Meteo for Zlín: fetching and parsing (no drawing)."""
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
import ephem
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from weather_data import LAT, LON, TIMEZONE, URL as OPEN_METEO_URL
|
||||||
|
|
||||||
|
CELESTRAK_URL = "https://celestrak.org/NORAD/elements/gp.php"
|
||||||
|
ISS_CATALOG_NUMBER = 25544
|
||||||
|
STORY_HOURS = 12
|
||||||
|
SOME_CLOUD, OVERCAST = 25, 60 # percent
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Tle:
|
||||||
|
"""Two-line orbital elements: what ephem needs to place a satellite at any moment."""
|
||||||
|
name: str
|
||||||
|
line1: str
|
||||||
|
line2: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class CloudHour:
|
||||||
|
time: datetime # naive local time, on the hour
|
||||||
|
pct: int | None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_tle(text: str) -> Tle:
|
||||||
|
lines = [line.strip() for line in text.strip().splitlines()]
|
||||||
|
if len(lines) < 3 or not lines[1].startswith("1 ") or not lines[2].startswith("2 "):
|
||||||
|
raise ValueError(f"not a TLE: {text[:60]!r}")
|
||||||
|
try:
|
||||||
|
ephem.readtle(*lines[:3])
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValueError(f"unreadable TLE: {exc}") from None
|
||||||
|
return Tle(*lines[:3])
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_tle(get=requests.get) -> Tle:
|
||||||
|
response = get(CELESTRAK_URL, params={"CATNR": ISS_CATALOG_NUMBER, "FORMAT": "TLE"}, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
return parse_tle(response.text)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_clouds(payload: dict) -> tuple[CloudHour, ...]:
|
||||||
|
hourly = payload.get("hourly") or {}
|
||||||
|
pcts = hourly.get("cloud_cover") or []
|
||||||
|
return tuple(CloudHour(datetime.fromisoformat(t), pcts[i] if i < len(pcts) else None)
|
||||||
|
for i, t in enumerate(hourly.get("time") or []))
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_clouds(get=requests.get) -> tuple[CloudHour, ...]:
|
||||||
|
params = {"latitude": LAT, "longitude": LON, "hourly": "cloud_cover", "timezone": TIMEZONE, "forecast_days": 2}
|
||||||
|
response = get(OPEN_METEO_URL, params=params, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
return parse_clouds(response.json())
|
||||||
|
|
||||||
|
|
||||||
|
def cloud_at(clouds: tuple[CloudHour, ...], when: datetime) -> int | None:
|
||||||
|
"""Cloud cover for the hour containing `when`, None if the forecast does not reach it."""
|
||||||
|
hour = when.replace(minute=0, second=0, microsecond=0)
|
||||||
|
return next((c.pct for c in clouds if c.time == hour), None)
|
||||||
|
|
||||||
|
|
||||||
|
def cloud_story(clouds: tuple[CloudHour, ...], now: datetime) -> str | None:
|
||||||
|
"""The next 12 hours in a few words: `Jasno`, `Polojasno`, `Zataženo` or `Jasno do 20 h, od 22 h zataženo`."""
|
||||||
|
start = now.replace(minute=0, second=0, microsecond=0)
|
||||||
|
hours = [c for c in clouds if start <= c.time <= start + timedelta(hours=STORY_HOURS)]
|
||||||
|
if not hours:
|
||||||
|
return None
|
||||||
|
some = next((c for c in hours if (c.pct or 0) >= SOME_CLOUD), None)
|
||||||
|
full = next((c for c in hours if (c.pct or 0) >= OVERCAST), None)
|
||||||
|
if some is None:
|
||||||
|
return "Jasno"
|
||||||
|
if some is hours[0]:
|
||||||
|
return "Zataženo" if full is some else "Polojasno"
|
||||||
|
return f"Jasno do {some.time.hour} h" + (f", od {full.time.hour} h zataženo" if full else ", pak polojasno")
|
||||||
+171
@@ -0,0 +1,171 @@
|
|||||||
|
"""The sky over Zlín right now: a star chart as seen lying on your back, and what is up tonight."""
|
||||||
|
import math
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
import astro
|
||||||
|
import skykit
|
||||||
|
from astro import Body, direction
|
||||||
|
from poller import Poller
|
||||||
|
from sky_data import CloudHour, Tle, cloud_at, cloud_story
|
||||||
|
from skykit import H, W, hm, mix, tracked
|
||||||
|
from view import Patch
|
||||||
|
|
||||||
|
BG, RING, LINE, LABEL = (7, 10, 24), (30, 42, 72), (46, 62, 100), (120, 140, 182)
|
||||||
|
TEXT, SUB, STAR, ISS = (236, 238, 246), (150, 165, 200), (214, 222, 242), (130, 220, 230)
|
||||||
|
DOME_NIGHT, DOME_TWILIGHT, DOME_DAY = (12, 19, 42), (17, 28, 60), (26, 46, 90)
|
||||||
|
CLEAR, CLOUDY = (40, 120, 90), (120, 124, 140)
|
||||||
|
STALE_BG, STALE_INK = (240, 200, 90), BG
|
||||||
|
COLOURS = {"Měsíc": (235, 235, 220), "Merkur": (180, 170, 160), "Venuše": (255, 248, 220), "Mars": (255, 120, 80),
|
||||||
|
"Jupiter": (245, 222, 180), "Saturn": (240, 200, 110), "Slunce": (255, 214, 90)}
|
||||||
|
LINES = (("Vega", "Deneb"), ("Deneb", "Altair"), ("Altair", "Vega"),
|
||||||
|
("Dubhe", "Merak"), ("Merak", "Phecda"), ("Phecda", "Megrez"), ("Megrez", "Dubhe"),
|
||||||
|
("Megrez", "Alioth"), ("Alioth", "Mizar"), ("Mizar", "Alkaid"),
|
||||||
|
("Markab", "Scheat"), ("Scheat", "Alpheratz"), ("Alpheratz", "Algenib"), ("Algenib", "Markab"),
|
||||||
|
("Alpheratz", "Mirach"), ("Mirach", "Almach"), ("Deneb", "Sadr"), ("Sadr", "Albireo"), ("Mirfak", "Algol"),
|
||||||
|
("Betelgeuse", "Bellatrix"), ("Bellatrix", "Mintaka"), ("Mintaka", "Alnilam"), ("Alnilam", "Alnitak"),
|
||||||
|
("Alnitak", "Saiph"), ("Saiph", "Rigel"), ("Rigel", "Mintaka"), ("Alnitak", "Betelgeuse"))
|
||||||
|
CX, CY, R = 162, 162, 150 # the dome
|
||||||
|
PANEL_X = 326
|
||||||
|
RISING_WITHIN = timedelta(hours=10)
|
||||||
|
MAX_ROWS = 4
|
||||||
|
|
||||||
|
|
||||||
|
def dome_xy(alt: float, az: float) -> tuple[float, float]:
|
||||||
|
"""Zenith in the centre, horizon on the rim, north up and east on the left (a chart held overhead)."""
|
||||||
|
r = R * (90 - alt) / 90
|
||||||
|
return CX - r * math.sin(math.radians(az)), CY - r * math.cos(math.radians(az))
|
||||||
|
|
||||||
|
|
||||||
|
def panel_rows(bodies: tuple[Body, ...], moon_pct: float, now: datetime) -> list[tuple[str, str]]:
|
||||||
|
"""What is up (highest first), then what rises in the next hours (soonest first); at most MAX_ROWS."""
|
||||||
|
up = sorted((b for b in bodies if b.alt > 0), key=lambda b: -b.alt)
|
||||||
|
rising = sorted((b for b in bodies if b.alt <= 0 and b.rise is not None and b.rise - now <= RISING_WITHIN),
|
||||||
|
key=lambda b: b.rise)
|
||||||
|
rows = [(b.name, f"{moon_pct:.0f} % · {direction(b.az)}" if b.name == "Měsíc" else f"{b.alt:.0f}° {direction(b.az)}")
|
||||||
|
for b in up]
|
||||||
|
rows += [(b.name, f"↑ {hm(b.rise)}") for b in rising]
|
||||||
|
return rows[:MAX_ROWS]
|
||||||
|
|
||||||
|
|
||||||
|
class SkyView:
|
||||||
|
name = "sky"
|
||||||
|
TLE_STALE_AFTER = 3 * 86400.0 # ISS predictions drift once the orbit is days old
|
||||||
|
CLOUDS_STALE_AFTER = 3600.0
|
||||||
|
|
||||||
|
def __init__(self, tle: Poller[Tle], clouds: Poller[tuple[CloudHour, ...]]) -> None:
|
||||||
|
self._tle = tle
|
||||||
|
self._clouds = clouds
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
self._tle.start()
|
||||||
|
self._clouds.start()
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
self._tle.stop()
|
||||||
|
self._clouds.stop()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _old(poller: Poller, limit: float) -> bool:
|
||||||
|
age = poller.age()
|
||||||
|
return age is not None and age > limit
|
||||||
|
|
||||||
|
def frame_key(self, now: datetime):
|
||||||
|
return (now.strftime("%Y%m%d%H%M"), self._tle.version, self._clouds.version,
|
||||||
|
self._old(self._tle, self.TLE_STALE_AFTER), self._old(self._clouds, self.CLOUDS_STALE_AFTER))
|
||||||
|
|
||||||
|
def patch(self, now: datetime) -> Patch | None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def render(self, now: datetime) -> Image.Image:
|
||||||
|
img = Image.new("RGB", (W, H), BG)
|
||||||
|
d = ImageDraw.Draw(img)
|
||||||
|
bodies = astro.bodies(now)
|
||||||
|
moon_pct, waxing = astro.moon_phase(now)
|
||||||
|
self._dome(img, d, now, bodies, moon_pct, waxing)
|
||||||
|
self._panel(d, now, bodies, moon_pct)
|
||||||
|
return img
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _dome(img, d, now, bodies, moon_pct, waxing) -> None:
|
||||||
|
sun = astro.sun(now)
|
||||||
|
fill = DOME_DAY if sun.alt > 0 else DOME_TWILIGHT if sun.alt > -12 else DOME_NIGHT
|
||||||
|
d.ellipse((CX - R, CY - R, CX + R, CY + R), fill=fill, outline=RING, width=2)
|
||||||
|
for alt in (30, 60):
|
||||||
|
r = R * (90 - alt) / 90
|
||||||
|
for k in range(0, 360, 4):
|
||||||
|
d.point((CX + r * math.cos(math.radians(k)), CY + r * math.sin(math.radians(k))), fill=RING)
|
||||||
|
|
||||||
|
stars = {s.name: s for s in astro.stars(now)}
|
||||||
|
for a, b in LINES:
|
||||||
|
if a in stars and b in stars:
|
||||||
|
d.line((*dome_xy(stars[a].alt, stars[a].az), *dome_xy(stars[b].alt, stars[b].az)), fill=LINE)
|
||||||
|
for s in stars.values():
|
||||||
|
x, y = dome_xy(s.alt, s.az)
|
||||||
|
r = max(0.8, 2.8 - 0.8 * s.mag)
|
||||||
|
d.ellipse((x - r, y - r, x + r, y + r), fill=STAR)
|
||||||
|
|
||||||
|
visible = [b for b in (sun, *bodies) if b.alt > 0] # the sun and moon claim their label space first
|
||||||
|
for b in visible:
|
||||||
|
x, y = dome_xy(b.alt, b.az)
|
||||||
|
if b.name == "Měsíc":
|
||||||
|
skykit.moon_disc(img, x, y, 9, moon_pct, waxing, lit=COLOURS[b.name], dark=(40, 44, 60))
|
||||||
|
else:
|
||||||
|
r = 7 if b.name == "Slunce" else 4
|
||||||
|
d.ellipse((x - r, y - r, x + r, y + r), fill=COLOURS[b.name])
|
||||||
|
labels: list[tuple[float, float, float, float]] = []
|
||||||
|
for b in visible:
|
||||||
|
x, y = dome_xy(b.alt, b.az)
|
||||||
|
colour = COLOURS[b.name]
|
||||||
|
f = skykit.font(11, 600)
|
||||||
|
right = x + 12 + d.textlength(b.name, font=f) <= CX + R # else put the label on the left
|
||||||
|
at, anchor = ((x + 12, y + 4), "ls") if right else ((x - 12, y + 4), "rs")
|
||||||
|
box = d.textbbox(at, b.name, font=f, anchor=anchor)
|
||||||
|
if not any(box[0] < o[2] and o[0] < box[2] and box[1] < o[3] and o[1] < box[3] for o in labels):
|
||||||
|
d.text(at, b.name, font=f, fill=colour, anchor=anchor)
|
||||||
|
labels.append(box)
|
||||||
|
for text, (x, y) in (("S", (CX, 24)), ("J", (CX, 300)), ("V", (24, CY)), ("Z", (300, CY))):
|
||||||
|
d.text((x, y), text, font=skykit.font(12, 700), fill=LABEL, anchor="mm")
|
||||||
|
|
||||||
|
def _panel(self, d, now, bodies, moon_pct) -> None:
|
||||||
|
x0, x1 = PANEL_X, 468
|
||||||
|
tracked(d, (x0, 24), "OBLOHA · ZLÍN", skykit.font(10, 650), LABEL)
|
||||||
|
d.text((x0, 60), hm(now), font=skykit.font(30, 700), fill=TEXT, anchor="ls")
|
||||||
|
dark = astro.darkness(now)
|
||||||
|
d.text((x0, 78), f"tma {hm(dark[0])}–{hm(dark[1])}" if dark else "bez úplné tmy", font=skykit.font(12, 500),
|
||||||
|
fill=SUB, anchor="ls")
|
||||||
|
d.line((x0, 90, x1, 90), fill=RING)
|
||||||
|
|
||||||
|
rows = panel_rows(bodies, moon_pct, now)
|
||||||
|
for i, (name, info) in enumerate(rows):
|
||||||
|
y = 112 + i * 24
|
||||||
|
d.ellipse((x0, y - 8, x0 + 7, y - 1), fill=COLOURS[name])
|
||||||
|
d.text((x0 + 14, y), name, font=skykit.font(13, 600), fill=TEXT, anchor="ls")
|
||||||
|
d.text((x1, y), info, font=skykit.font(12, 500), fill=SUB, anchor="rs")
|
||||||
|
y = 112 + len(rows) * 24 - 8
|
||||||
|
d.line((x0, y, x1, y), fill=RING)
|
||||||
|
|
||||||
|
clouds: tuple[CloudHour, ...] = self._clouds.value or ()
|
||||||
|
end = tracked(d, (x0, y + 20), "MRAKY", skykit.font(10, 650), LABEL)
|
||||||
|
if self._old(self._clouds, self.CLOUDS_STALE_AFTER):
|
||||||
|
skykit.tag(d, (end + 8, y + 20), "STARÉ", skykit.font(10, 700), STALE_BG, STALE_INK)
|
||||||
|
for i in range(12):
|
||||||
|
pct = cloud_at(clouds, now + timedelta(hours=i))
|
||||||
|
colour = RING if pct is None else mix(CLEAR, CLOUDY, pct / 100)
|
||||||
|
d.rectangle((x0 + i * 12, y + 28, x0 + i * 12 + 9, y + 44), fill=colour)
|
||||||
|
story = cloud_story(clouds, now) or "--"
|
||||||
|
for k, line in enumerate(story.split(", ")):
|
||||||
|
d.text((x0, y + 60 + k * 15), line, font=skykit.font(11, 600), fill=TEXT, anchor="ls")
|
||||||
|
|
||||||
|
tle: Tle | None = self._tle.value
|
||||||
|
if tle is None:
|
||||||
|
text = "ISS --"
|
||||||
|
else:
|
||||||
|
p = astro.next_visible_pass(tle, now)
|
||||||
|
text = f"ISS {skykit.WEEKDAYS[p.start.weekday()]} {hm(p.start)} · {p.max_alt:.0f}°" if p else \
|
||||||
|
"ISS: nic do 3 dnů"
|
||||||
|
end = d.textlength(text, font=skykit.font(12, 600)) + x0
|
||||||
|
d.text((x0, 304), text, font=skykit.font(12, 600), fill=ISS, anchor="ls")
|
||||||
|
if self._old(self._tle, self.TLE_STALE_AFTER):
|
||||||
|
skykit.tag(d, (end + 8, 304), "STARÉ", skykit.font(10, 700), STALE_BG, STALE_INK)
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""Night-sky drawing kit for the sky and ISS views: Inter type, letter-spaced labels, colour mixing, moon phase."""
|
||||||
|
import math
|
||||||
|
from functools import lru_cache
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PIL import Image, ImageChops, ImageDraw, ImageFont
|
||||||
|
|
||||||
|
W, H = 480, 320
|
||||||
|
FONT_PATH = Path(__file__).parent / "assets" / "fonts" / "Inter.ttf"
|
||||||
|
WEEKDAYS = ["po", "út", "st", "čt", "pá", "so", "ne"]
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=None)
|
||||||
|
def font(size: int, weight: int = 500) -> ImageFont.FreeTypeFont:
|
||||||
|
f = ImageFont.truetype(str(FONT_PATH), size)
|
||||||
|
f.set_variation_by_axes([14 if size < 20 else 32, weight]) # optical size, weight
|
||||||
|
return f
|
||||||
|
|
||||||
|
|
||||||
|
def mix(a, b, t: float):
|
||||||
|
t = max(0.0, min(1.0, t))
|
||||||
|
return tuple(round(x + (y - x) * t) for x, y in zip(a, b))
|
||||||
|
|
||||||
|
|
||||||
|
def hm(t) -> str:
|
||||||
|
return "--:--" if t is None else f"{t.hour}:{t.minute:02d}"
|
||||||
|
|
||||||
|
|
||||||
|
def tracked(d: ImageDraw.ImageDraw, xy, text: str, f, fill, track: float = 1.2, right: bool = False) -> float:
|
||||||
|
"""Letter-spaced text on baseline xy[1]; returns the end x."""
|
||||||
|
width = sum(d.textlength(ch, font=f) for ch in text) + track * (len(text) - 1)
|
||||||
|
x = xy[0] - width if right else xy[0]
|
||||||
|
for ch in text:
|
||||||
|
d.text((x, xy[1]), ch, font=f, fill=fill, anchor="ls")
|
||||||
|
x += d.textlength(ch, font=f) + track
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
|
def tag(d: ImageDraw.ImageDraw, xy, text: str, f, fill, ink) -> None:
|
||||||
|
"""A pill-shaped label with its text baseline at xy[1]."""
|
||||||
|
x, y = xy
|
||||||
|
width = d.textlength(text, font=f)
|
||||||
|
d.rounded_rectangle((x, y - 13, x + width + 12, y + 4), 8, fill=fill)
|
||||||
|
d.text((x + 6, y), text, font=f, fill=ink, anchor="ls")
|
||||||
|
|
||||||
|
|
||||||
|
def moon_disc(img: Image.Image, cx: float, cy: float, r: int, pct: float, waxing: bool, lit, dark) -> None:
|
||||||
|
"""The moon as seen from the northern hemisphere: lit on the right while waxing, on the left while waning."""
|
||||||
|
p = math.acos(max(-1.0, min(1.0, 1 - 2 * pct / 100))) / (2 * math.pi) # 0 new .. 0.5 full
|
||||||
|
p = p if waxing else 1 - p
|
||||||
|
s = 2 * r * 4 # drawn 4x larger, then scaled down for smooth edges
|
||||||
|
disc = Image.new("L", (s, s), 0)
|
||||||
|
ImageDraw.Draw(disc).ellipse((0, 0, s - 1, s - 1), fill=255)
|
||||||
|
half = Image.new("L", (s, s), 0)
|
||||||
|
ImageDraw.Draw(half).rectangle((s // 2, 0, s, s) if p < 0.5 else (0, 0, s // 2, s), fill=255)
|
||||||
|
lit_mask = ImageChops.multiply(half, disc)
|
||||||
|
ew = s * abs(math.cos(2 * math.pi * p)) / 2 # half-width of the terminator ellipse
|
||||||
|
terminator = Image.new("L", (s, s), 0)
|
||||||
|
ImageDraw.Draw(terminator).ellipse((s / 2 - ew, 0, s / 2 + ew, s - 1), fill=255)
|
||||||
|
if pct < 50:
|
||||||
|
lit_mask = ImageChops.subtract(lit_mask, terminator)
|
||||||
|
else:
|
||||||
|
lit_mask = ImageChops.lighter(lit_mask, ImageChops.multiply(terminator, disc))
|
||||||
|
x0, y0 = round(cx - r), round(cy - r)
|
||||||
|
box = (x0, y0, x0 + 2 * r, y0 + 2 * r)
|
||||||
|
img.paste(dark, box, disc.resize((2 * r, 2 * r), Image.LANCZOS))
|
||||||
|
if pct > 0:
|
||||||
|
img.paste(lit, box, lit_mask.resize((2 * r, 2 * r), Image.LANCZOS).point(lambda v: 255 if v > 127 else 0))
|
||||||
+265
@@ -0,0 +1,265 @@
|
|||||||
|
"""Server stats from the host's /proc, /sys, root filesystem and the Docker socket (no drawing)."""
|
||||||
|
import http.client
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import socket
|
||||||
|
import time
|
||||||
|
from collections import defaultdict
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
TOP_PROCESSES = 5
|
||||||
|
CPU_SENSOR_TYPES = ("x86_pkg_temp", "coretemp", "cpu_thermal", "cpu-thermal")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Container:
|
||||||
|
name: str # short, readable
|
||||||
|
state: str # docker state: running, restarting, exited, ...
|
||||||
|
health: str | None # healthy, unhealthy, starting, or None without a healthcheck
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Proc:
|
||||||
|
name: str
|
||||||
|
cpu_pct: float # share of the whole machine's CPU capacity
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Stats:
|
||||||
|
cpu_pct: float | None
|
||||||
|
mem_pct: float | None
|
||||||
|
disk_pct: float | None
|
||||||
|
load: tuple[float, float, float] | None
|
||||||
|
temp_c: float | None
|
||||||
|
uptime_s: float | None
|
||||||
|
containers: tuple[Container, ...] | None # None: Docker unavailable
|
||||||
|
procs: tuple[Proc, ...]
|
||||||
|
|
||||||
|
|
||||||
|
# --- names and labels ---------------------------------------------------------
|
||||||
|
|
||||||
|
# Coolify appends a random 24 character id (and sometimes a deploy timestamp) to container names.
|
||||||
|
_SUFFIX = r"(?:-\d+(?:T\d+)?)?"
|
||||||
|
_HASHED = re.compile(rf"^(.+)-[a-z0-9]{{24}}{_SUFFIX}$")
|
||||||
|
_HASH_ONLY = re.compile(rf"^[a-z0-9]{{24}}{_SUFFIX}$")
|
||||||
|
|
||||||
|
|
||||||
|
def short_name(name: str, labels: dict[str, str], image: str) -> str:
|
||||||
|
"""A readable name: Coolify's random suffix stripped, else compose service label, else image, else hash start."""
|
||||||
|
match = _HASHED.match(name)
|
||||||
|
if match:
|
||||||
|
return match.group(1)
|
||||||
|
if not _HASH_ONLY.match(name):
|
||||||
|
return name
|
||||||
|
image_name = image.rsplit("/", 1)[-1].split(":")[0]
|
||||||
|
for candidate in (labels.get("com.docker.compose.service", ""), image_name):
|
||||||
|
if candidate and not _HASH_ONLY.match(candidate):
|
||||||
|
return candidate
|
||||||
|
return name[:8]
|
||||||
|
|
||||||
|
|
||||||
|
def status_label(c: Container) -> str:
|
||||||
|
if c.state == "running":
|
||||||
|
return {"healthy": "OK", "unhealthy": "UNHEALTHY"}.get(c.health, "UP")
|
||||||
|
return "RESTART" if c.state == "restarting" else "EXITED"
|
||||||
|
|
||||||
|
|
||||||
|
# --- parsers -------------------------------------------------------------------
|
||||||
|
|
||||||
|
def parse_cpu_times(proc_stat_text: str) -> tuple[int, int]:
|
||||||
|
"""(busy, total) jiffies from the aggregate `cpu ` line."""
|
||||||
|
for line in proc_stat_text.splitlines():
|
||||||
|
if line.startswith("cpu "):
|
||||||
|
fields = [int(x) for x in line.split()[1:]]
|
||||||
|
total = sum(fields[:8])
|
||||||
|
return total - fields[3] - fields[4], total
|
||||||
|
raise ValueError("no cpu line in /proc/stat")
|
||||||
|
|
||||||
|
|
||||||
|
def cpu_pct(prev: tuple[int, int] | None, cur: tuple[int, int]) -> float | None:
|
||||||
|
if prev is None or cur[1] - prev[1] <= 0:
|
||||||
|
return None
|
||||||
|
return (cur[0] - prev[0]) / (cur[1] - prev[1]) * 100
|
||||||
|
|
||||||
|
|
||||||
|
def parse_mem_pct(meminfo_text: str) -> float:
|
||||||
|
values = {}
|
||||||
|
for line in meminfo_text.splitlines():
|
||||||
|
key, _, rest = line.partition(":")
|
||||||
|
if key in ("MemTotal", "MemAvailable"):
|
||||||
|
values[key] = int(rest.split()[0])
|
||||||
|
return (1 - values["MemAvailable"] / values["MemTotal"]) * 100
|
||||||
|
|
||||||
|
|
||||||
|
def parse_pid_stat(text: str) -> tuple[str, int]:
|
||||||
|
"""(command name, utime + stime) from /proc/<pid>/stat; the name may contain spaces and parentheses."""
|
||||||
|
head, _, tail = text.rpartition(")")
|
||||||
|
name = head.partition("(")[2]
|
||||||
|
fields = tail.split()
|
||||||
|
return name, int(fields[11]) + int(fields[12])
|
||||||
|
|
||||||
|
|
||||||
|
# --- docker --------------------------------------------------------------------
|
||||||
|
|
||||||
|
class _UnixHTTPConnection(http.client.HTTPConnection):
|
||||||
|
def __init__(self, path: str, timeout: float) -> None:
|
||||||
|
super().__init__("localhost", timeout=timeout)
|
||||||
|
self._path = path
|
||||||
|
|
||||||
|
def connect(self) -> None:
|
||||||
|
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||||
|
self.sock.settimeout(self.timeout)
|
||||||
|
self.sock.connect(self._path)
|
||||||
|
|
||||||
|
|
||||||
|
_HEALTH = re.compile(r"\((healthy|unhealthy|health: starting)\)")
|
||||||
|
|
||||||
|
|
||||||
|
def list_containers(sock_path: str, timeout: float = 3.0) -> tuple[Container, ...]:
|
||||||
|
conn = _UnixHTTPConnection(sock_path, timeout)
|
||||||
|
try:
|
||||||
|
conn.request("GET", "/containers/json?all=1")
|
||||||
|
response = conn.getresponse()
|
||||||
|
if response.status != 200:
|
||||||
|
raise OSError(f"docker answered {response.status}")
|
||||||
|
payload = json.loads(response.read())
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
containers = []
|
||||||
|
for c in payload:
|
||||||
|
name = ((c.get("Names") or ["?"])[0]).lstrip("/")
|
||||||
|
health = _HEALTH.search(c.get("Status", ""))
|
||||||
|
containers.append(Container(
|
||||||
|
name=short_name(name, c.get("Labels") or {}, c.get("Image", "")),
|
||||||
|
state=c.get("State", "unknown"),
|
||||||
|
health={"health: starting": "starting"}.get(health.group(1), health.group(1)) if health else None,
|
||||||
|
))
|
||||||
|
return tuple(containers)
|
||||||
|
|
||||||
|
|
||||||
|
# --- reader --------------------------------------------------------------------
|
||||||
|
|
||||||
|
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",
|
||||||
|
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._sys = Path(sys_root)
|
||||||
|
self._disk = disk_path
|
||||||
|
self._sock = docker_sock
|
||||||
|
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._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()
|
||||||
|
|
||||||
|
def _try(self, section: str, fn, default=None):
|
||||||
|
"""Run one section; a failure yields `default` and is logged once per failure streak."""
|
||||||
|
try:
|
||||||
|
value = fn()
|
||||||
|
except Exception as exc:
|
||||||
|
if section not in self._failing:
|
||||||
|
self._failing.add(section)
|
||||||
|
log.warning("stats: %s unavailable: %s", section, exc)
|
||||||
|
return default
|
||||||
|
if section in self._failing:
|
||||||
|
self._failing.discard(section)
|
||||||
|
log.info("stats: %s recovered", section)
|
||||||
|
return value
|
||||||
|
|
||||||
|
def read(self) -> Stats:
|
||||||
|
total = None
|
||||||
|
cpu = None
|
||||||
|
try:
|
||||||
|
cur = parse_cpu_times((self._proc / "stat").read_text())
|
||||||
|
total = cur[1]
|
||||||
|
cpu = cpu_pct(self._prev_cpu, cur)
|
||||||
|
self._prev_cpu = cur
|
||||||
|
except Exception as exc:
|
||||||
|
if "cpu" not in self._failing:
|
||||||
|
self._failing.add("cpu")
|
||||||
|
log.warning("stats: cpu unavailable: %s", exc)
|
||||||
|
else:
|
||||||
|
self._failing.discard("cpu")
|
||||||
|
|
||||||
|
return Stats(
|
||||||
|
cpu_pct=cpu,
|
||||||
|
mem_pct=self._try("memory", lambda: parse_mem_pct((self._proc / "meminfo").read_text())),
|
||||||
|
disk_pct=self._try("disk", self._disk_pct),
|
||||||
|
load=self._try("load", self._load),
|
||||||
|
temp_c=self._try("temperature", self._temperature),
|
||||||
|
uptime_s=self._try("uptime", lambda: float((self._proc / "uptime").read_text().split()[0])),
|
||||||
|
containers=self._containers(),
|
||||||
|
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:
|
||||||
|
st = os.statvfs(self._disk)
|
||||||
|
used = st.f_blocks - st.f_bfree
|
||||||
|
return used / (used + st.f_bavail) * 100
|
||||||
|
|
||||||
|
def _load(self) -> tuple[float, float, float]:
|
||||||
|
a, b, c = (self._proc / "loadavg").read_text().split()[:3]
|
||||||
|
return float(a), float(b), float(c)
|
||||||
|
|
||||||
|
def _temperature(self) -> float | None:
|
||||||
|
readings = [] # (is_cpu_sensor, celsius)
|
||||||
|
for zone in sorted((self._sys / "class" / "thermal").glob("thermal_zone*")):
|
||||||
|
try:
|
||||||
|
kind = (zone / "type").read_text().strip()
|
||||||
|
readings.append((kind in CPU_SENSOR_TYPES, int((zone / "temp").read_text()) / 1000))
|
||||||
|
except (OSError, ValueError):
|
||||||
|
continue # some zones exist but have no reading
|
||||||
|
if not readings:
|
||||||
|
return None
|
||||||
|
cpu_zones = [c for is_cpu, c in readings if is_cpu]
|
||||||
|
return max(cpu_zones or [c for _, c in readings])
|
||||||
|
|
||||||
|
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] = {}
|
||||||
|
names: dict[int, str] = {}
|
||||||
|
for entry in os.scandir(self._proc):
|
||||||
|
if not entry.name.isdigit():
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
name, t = parse_pid_stat((Path(entry.path) / "stat").read_text())
|
||||||
|
except (OSError, ValueError, IndexError):
|
||||||
|
continue # the process exited while we were reading
|
||||||
|
ticks[int(entry.name)], names[int(entry.name)] = t, name
|
||||||
|
previous, self._snapshot = self._snapshot, (now, total, ticks, names)
|
||||||
|
if previous is None or total - previous[1] <= 0:
|
||||||
|
return self._procs
|
||||||
|
per_name: dict[str, float] = defaultdict(float)
|
||||||
|
for pid, t in ticks.items():
|
||||||
|
if pid in previous[2] and t > previous[2][pid]:
|
||||||
|
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]
|
||||||
|
self._procs = tuple(Proc(name, pct) for name, pct in ranked)
|
||||||
|
return self._procs
|
||||||
Whitespace-only changes.
@@ -0,0 +1,4 @@
|
|||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
Vendored
+3
@@ -0,0 +1,3 @@
|
|||||||
|
ISS (ZARYA)
|
||||||
|
1 25544U 98067A 26301.46699108 .00005372 00000+0 10526-3 0 9998
|
||||||
|
2 25544 51.6335 0.5562 0007038 319.9799 40.0670 15.49088092592412
|
||||||
+152
@@ -0,0 +1,152 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"Names": [
|
||||||
|
"/apod-test"
|
||||||
|
],
|
||||||
|
"Image": "apod-test",
|
||||||
|
"State": "exited",
|
||||||
|
"Status": "Exited (0) 36 minutes ago",
|
||||||
|
"Labels": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Names": [
|
||||||
|
"/coolify"
|
||||||
|
],
|
||||||
|
"Image": "docker.io/coollabsio/coolify:4.4.7",
|
||||||
|
"State": "running",
|
||||||
|
"Status": "Up 11 hours (healthy)",
|
||||||
|
"Labels": {
|
||||||
|
"com.docker.compose.service": "coolify"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Names": [
|
||||||
|
"/coolify-db"
|
||||||
|
],
|
||||||
|
"Image": "postgres:15-alpine",
|
||||||
|
"State": "running",
|
||||||
|
"Status": "Up 11 hours (healthy)",
|
||||||
|
"Labels": {
|
||||||
|
"com.docker.compose.service": "postgres"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Names": [
|
||||||
|
"/coolify-redis"
|
||||||
|
],
|
||||||
|
"Image": "redis:7-alpine",
|
||||||
|
"State": "running",
|
||||||
|
"Status": "Up 11 hours (healthy)",
|
||||||
|
"Labels": {
|
||||||
|
"com.docker.compose.service": "redis"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Names": [
|
||||||
|
"/coolify-sentinel"
|
||||||
|
],
|
||||||
|
"Image": "docker.io/coollabsio/sentinel:1.1.2",
|
||||||
|
"State": "running",
|
||||||
|
"Status": "Up 22 hours (healthy)",
|
||||||
|
"Labels": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Names": [
|
||||||
|
"/gitea-xj97t0yzdnfmqxlfkz9mekot"
|
||||||
|
],
|
||||||
|
"Image": "gitea/gitea:latest",
|
||||||
|
"State": "running",
|
||||||
|
"Status": "Up 12 hours (healthy)",
|
||||||
|
"Labels": {
|
||||||
|
"com.docker.compose.service": "gitea"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Names": [
|
||||||
|
"/jn5mdu87ituoxzyojk84ugdj-20261018T132559"
|
||||||
|
],
|
||||||
|
"Image": "jn5mdu87ituoxzyojk84ugdj:1833c2f1bf67cbe93e579ed6d9b569fe3cd3b668",
|
||||||
|
"State": "running",
|
||||||
|
"Status": "Up 3 days",
|
||||||
|
"Labels": {
|
||||||
|
"com.docker.compose.service": "jn5mdu87ituoxzyojk84ugdj-20261018T132559"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Names": [
|
||||||
|
"/task-runners-ebe62bdjbp9f755kwh59lv8d"
|
||||||
|
],
|
||||||
|
"Image": "n8nio/runners:2.22.3",
|
||||||
|
"State": "running",
|
||||||
|
"Status": "Up 3 days (healthy)",
|
||||||
|
"Labels": {
|
||||||
|
"com.docker.compose.service": "task-runners"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Names": [
|
||||||
|
"/n8n-ebe62bdjbp9f755kwh59lv8d"
|
||||||
|
],
|
||||||
|
"Image": "n8nio/n8n:next",
|
||||||
|
"State": "running",
|
||||||
|
"Status": "Up 3 days (healthy)",
|
||||||
|
"Labels": {
|
||||||
|
"com.docker.compose.service": "n8n"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Names": [
|
||||||
|
"/plex-z0qh1wrbuzxo0jsfiazc3evc"
|
||||||
|
],
|
||||||
|
"Image": "lscr.io/linuxserver/plex:latest",
|
||||||
|
"State": "running",
|
||||||
|
"Status": "Up 3 days (healthy)",
|
||||||
|
"Labels": {
|
||||||
|
"com.docker.compose.service": "plex"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Names": [
|
||||||
|
"/ntfy-x1aokzlzorj1eo05a0xbraln"
|
||||||
|
],
|
||||||
|
"Image": "binwiederhier/ntfy",
|
||||||
|
"State": "running",
|
||||||
|
"Status": "Up 3 days (healthy)",
|
||||||
|
"Labels": {
|
||||||
|
"com.docker.compose.service": "ntfy"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Names": [
|
||||||
|
"/coolify-proxy"
|
||||||
|
],
|
||||||
|
"Image": "traefik:v3.7",
|
||||||
|
"State": "running",
|
||||||
|
"Status": "Up 3 days (healthy)",
|
||||||
|
"Labels": {
|
||||||
|
"com.docker.compose.service": "traefik"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Names": [
|
||||||
|
"/screen-pe28mpghgqnxaz12vyfyijrg-151725872213"
|
||||||
|
],
|
||||||
|
"Image": "pe28mpghgqnxaz12vyfyijrg_screen:3ad6dc696346485bfc5d7fff001aded38b60579c",
|
||||||
|
"State": "running",
|
||||||
|
"Status": "Up 3 days",
|
||||||
|
"Labels": {
|
||||||
|
"com.docker.compose.service": "screen"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Names": [
|
||||||
|
"/pump-monitor-qhcmhuhweydfg4tzbci4xxzt-093246425801"
|
||||||
|
],
|
||||||
|
"Image": "qhcmhuhweydfg4tzbci4xxzt_pump-monitor:9d7179308fd58d8d6582ce00d716844c3786360b",
|
||||||
|
"State": "running",
|
||||||
|
"Status": "Up 3 days (healthy)",
|
||||||
|
"Labels": {
|
||||||
|
"com.docker.compose.service": "pump-monitor"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
Vendored
+55
@@ -0,0 +1,55 @@
|
|||||||
|
MemTotal: 16147480 kB
|
||||||
|
MemFree: 542768 kB
|
||||||
|
MemAvailable: 13909124 kB
|
||||||
|
Buffers: 1120732 kB
|
||||||
|
Cached: 11485884 kB
|
||||||
|
SwapCached: 44 kB
|
||||||
|
Active: 2844728 kB
|
||||||
|
Inactive: 10869760 kB
|
||||||
|
Active(anon): 1362912 kB
|
||||||
|
Inactive(anon): 2048 kB
|
||||||
|
Active(file): 1481816 kB
|
||||||
|
Inactive(file): 10867712 kB
|
||||||
|
Unevictable: 27284 kB
|
||||||
|
Mlocked: 27160 kB
|
||||||
|
SwapTotal: 4194300 kB
|
||||||
|
SwapFree: 4193532 kB
|
||||||
|
Zswap: 0 kB
|
||||||
|
Zswapped: 0 kB
|
||||||
|
Dirty: 936 kB
|
||||||
|
Writeback: 0 kB
|
||||||
|
AnonPages: 1135056 kB
|
||||||
|
Mapped: 1020564 kB
|
||||||
|
Shmem: 249388 kB
|
||||||
|
KReclaimable: 1353512 kB
|
||||||
|
Slab: 1597868 kB
|
||||||
|
SReclaimable: 1353512 kB
|
||||||
|
SUnreclaim: 244356 kB
|
||||||
|
KernelStack: 12088 kB
|
||||||
|
PageTables: 26740 kB
|
||||||
|
SecPageTables: 0 kB
|
||||||
|
NFS_Unstable: 0 kB
|
||||||
|
Bounce: 0 kB
|
||||||
|
WritebackTmp: 0 kB
|
||||||
|
CommitLimit: 12268040 kB
|
||||||
|
Committed_AS: 6849128 kB
|
||||||
|
VmallocTotal: 34359738367 kB
|
||||||
|
VmallocUsed: 51616 kB
|
||||||
|
VmallocChunk: 0 kB
|
||||||
|
Percpu: 29568 kB
|
||||||
|
HardwareCorrupted: 0 kB
|
||||||
|
AnonHugePages: 0 kB
|
||||||
|
ShmemHugePages: 0 kB
|
||||||
|
ShmemPmdMapped: 0 kB
|
||||||
|
FileHugePages: 0 kB
|
||||||
|
FilePmdMapped: 0 kB
|
||||||
|
Unaccepted: 0 kB
|
||||||
|
HugePages_Total: 0
|
||||||
|
HugePages_Free: 0
|
||||||
|
HugePages_Rsvd: 0
|
||||||
|
HugePages_Surp: 0
|
||||||
|
Hugepagesize: 2048 kB
|
||||||
|
Hugetlb: 0 kB
|
||||||
|
DirectMap4k: 223920 kB
|
||||||
|
DirectMap2M: 10031104 kB
|
||||||
|
DirectMap1G: 6291456 kB
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
{"latitude":49.23005,"longitude":17.657297,"generationtime_ms":0.030279159545898438,"utc_offset_seconds":3600,"timezone":"Europe/Prague","timezone_abbreviation":"GMT+1","elevation":221.0,"hourly_units":{"time":"iso8601","cloud_cover":"%"},"hourly":{"time":["2026-10-28T00:00","2026-10-28T01:00","2026-10-28T02:00","2026-10-28T03:00","2026-10-28T04:00","2026-10-28T05:00","2026-10-28T06:00","2026-10-28T07:00","2026-10-28T08:00","2026-10-28T09:00","2026-10-28T10:00","2026-10-28T11:00","2026-10-28T12:00","2026-10-28T13:00","2026-10-28T14:00","2026-10-28T15:00","2026-10-28T16:00","2026-10-28T17:00","2026-10-28T18:00","2026-10-28T19:00","2026-10-28T20:00","2026-10-28T21:00","2026-10-28T22:00","2026-10-28T23:00","2026-10-29T00:00","2026-10-29T01:00","2026-10-29T02:00","2026-10-29T03:00","2026-10-29T04:00","2026-10-29T05:00","2026-10-29T06:00","2026-10-29T07:00","2026-10-29T08:00","2026-10-29T09:00","2026-10-29T10:00","2026-10-29T11:00","2026-10-29T12:00","2026-10-29T13:00","2026-10-29T14:00","2026-10-29T15:00","2026-10-29T16:00","2026-10-29T17:00","2026-10-29T18:00","2026-10-29T19:00","2026-10-29T20:00","2026-10-29T21:00","2026-10-29T22:00","2026-10-29T23:00"],"cloud_cover":[0,0,0,4,0,0,44,100,18,0,0,0,0,0,0,0,0,0,0,0,31,36,82,100,99,98,99,100,100,100,99,95,94,69,74,83,79,84,91,86,91,93,76,68,82,96,96,99]}}
|
||||||
Vendored
+1
-1
@@ -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"]}}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import numpy as np
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
|
||||||
|
def count_colour(img: Image.Image, colour, box=None) -> int:
|
||||||
|
"""Number of pixels of `colour` in `img` (optionally only inside `box`)."""
|
||||||
|
if box is not None:
|
||||||
|
img = img.crop(box)
|
||||||
|
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
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
import lcdkit
|
||||||
|
from lcdkit import BG, GHOST, INK
|
||||||
|
from tests.helpers import count_colour as count
|
||||||
|
|
||||||
|
|
||||||
|
def canvas(w=200, h=120):
|
||||||
|
img = Image.new("RGB", (w, h), BG)
|
||||||
|
return img, ImageDraw.Draw(img)
|
||||||
|
|
||||||
|
|
||||||
|
def test_number_returns_start_plus_width():
|
||||||
|
_, d = canvas(480, 120)
|
||||||
|
end = lcdkit.number(d, "14:32", 10, 10, 54, 96, 12, 9)
|
||||||
|
assert end - 10 == lcdkit.number_width("14:32", 54, 12, 9)
|
||||||
|
|
||||||
|
|
||||||
|
def test_eight_lights_more_ink_than_one():
|
||||||
|
one, d1 = canvas()
|
||||||
|
eight, d8 = canvas()
|
||||||
|
lcdkit.number(d1, "1", 20, 10, 40, 80, 9, 6, ghost=False)
|
||||||
|
lcdkit.number(d8, "8", 20, 10, 40, 80, 9, 6, ghost=False)
|
||||||
|
assert count(eight, INK) > count(one, INK) > 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_ghost_segments_use_ghost_colour():
|
||||||
|
with_ghost, d1 = canvas()
|
||||||
|
without, d2 = canvas()
|
||||||
|
lcdkit.number(d1, "1", 20, 10, 40, 80, 9, 6, ghost=True)
|
||||||
|
lcdkit.number(d2, "1", 20, 10, 40, 80, 9, 6, ghost=False)
|
||||||
|
assert count(with_ghost, GHOST) > 0
|
||||||
|
assert count(without, GHOST) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_minus_draws_ink():
|
||||||
|
three, d3 = canvas()
|
||||||
|
minus3, dm = canvas()
|
||||||
|
lcdkit.number(d3, "3", 20, 10, 40, 80, 9, 6, ghost=False)
|
||||||
|
lcdkit.number(dm, "-3", 20, 10, 40, 80, 9, 6, ghost=False)
|
||||||
|
assert count(minus3, INK) > count(three, INK)
|
||||||
|
|
||||||
|
|
||||||
|
def segment_lit(img, x, y):
|
||||||
|
return img.getpixel((x, y)) == INK
|
||||||
|
|
||||||
|
|
||||||
|
def test_h_bar_lights_proportionally():
|
||||||
|
img, d = canvas()
|
||||||
|
# 10 segments, 8 px wide, 2 px gap -> segment i spans x = 10 + i*10 .. 17
|
||||||
|
lcdkit.h_bar(d, 10, 10, 50, 20, 10, 8, 2)
|
||||||
|
lit = [segment_lit(img, 10 + i * 10 + 4, 20) for i in range(10)]
|
||||||
|
assert lit == [True] * 5 + [False] * 5
|
||||||
|
|
||||||
|
|
||||||
|
def test_v_bar_lights_from_the_bottom():
|
||||||
|
img, d = canvas()
|
||||||
|
# 4 segments, 5 px tall, 1 px gap, bottom edge at y=100 -> segment k spans y = 100-k*6-5 .. 100-k*6
|
||||||
|
lcdkit.v_bar(d, 10, 100, 50, 14, 4, 5, 1)
|
||||||
|
lit = [segment_lit(img, 15, 100 - k * 6 - 3) for k in range(4)]
|
||||||
|
assert lit == [True, True, False, False]
|
||||||
|
|
||||||
|
|
||||||
|
def test_bar_none_is_all_ghost():
|
||||||
|
img, d = canvas()
|
||||||
|
lcdkit.h_bar(d, 10, 10, None, 20, 10, 8, 2)
|
||||||
|
assert count(img, INK) == 0
|
||||||
|
assert count(img, GHOST) > 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_fmt_temp_cases():
|
||||||
|
assert lcdkit.fmt_temp(10.2) == "10"
|
||||||
|
assert lcdkit.fmt_temp(-3.4) == "-3"
|
||||||
|
assert lcdkit.fmt_temp(-0.4) == "0"
|
||||||
|
assert lcdkit.fmt_temp(None) == "--"
|
||||||
|
|
||||||
|
|
||||||
|
def test_tag_is_ink_box_and_returns_its_box():
|
||||||
|
img, d = canvas()
|
||||||
|
box = lcdkit.tag(d, (10, 10), "STARÉ", lcdkit.load_font(12))
|
||||||
|
x0, y0, x1, y1 = box
|
||||||
|
assert img.getpixel((x0 + 1, y0 + 1)) == INK
|
||||||
|
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
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import types
|
||||||
|
from enum import Enum
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
import main
|
||||||
|
import registry
|
||||||
|
from lcdkit import BG
|
||||||
|
from view import Patch
|
||||||
|
|
||||||
|
|
||||||
|
class FakeLcd:
|
||||||
|
instances = []
|
||||||
|
|
||||||
|
def __init__(self, com_port="AUTO"):
|
||||||
|
self.com_port = com_port
|
||||||
|
self.calls, self.closed, self.orientation, self.brightness = [], False, None, None
|
||||||
|
FakeLcd.instances.append(self)
|
||||||
|
|
||||||
|
def InitializeComm(self): ...
|
||||||
|
|
||||||
|
def SetOrientation(self, o):
|
||||||
|
self.orientation = o
|
||||||
|
|
||||||
|
def SetBrightness(self, b):
|
||||||
|
self.brightness = b
|
||||||
|
|
||||||
|
def DisplayPILImage(self, image, x=0, y=0, image_width=None, image_height=None):
|
||||||
|
self.calls.append((image.size, x, y))
|
||||||
|
|
||||||
|
def closeSerial(self):
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
|
||||||
|
class FakeOrientation(Enum):
|
||||||
|
PORTRAIT = 0
|
||||||
|
REVERSE_PORTRAIT = 1
|
||||||
|
LANDSCAPE = 2
|
||||||
|
REVERSE_LANDSCAPE = 3
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def fake_library(monkeypatch):
|
||||||
|
FakeLcd.instances = []
|
||||||
|
lib = types.ModuleType("library")
|
||||||
|
lcd = types.ModuleType("library.lcd")
|
||||||
|
comm = types.ModuleType("library.lcd.lcd_comm")
|
||||||
|
comm.Orientation = FakeOrientation
|
||||||
|
rev_a = types.ModuleType("library.lcd.lcd_comm_rev_a")
|
||||||
|
rev_a.LcdCommRevA = FakeLcd
|
||||||
|
for name, mod in (("library", lib), ("library.lcd", lcd), ("library.lcd.lcd_comm", comm),
|
||||||
|
("library.lcd.lcd_comm_rev_a", rev_a)):
|
||||||
|
monkeypatch.setitem(sys.modules, name, mod)
|
||||||
|
monkeypatch.setenv("SCREEN_DEVICE", "/dev/fake")
|
||||||
|
|
||||||
|
|
||||||
|
class StubView:
|
||||||
|
name = "stub"
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.started = self.stopped = False
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
self.started = True
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
|
self.stopped = True
|
||||||
|
|
||||||
|
def frame_key(self, now):
|
||||||
|
return "k"
|
||||||
|
|
||||||
|
def render(self, now):
|
||||||
|
return Image.new("RGB", (480, 320), BG)
|
||||||
|
|
||||||
|
def patch(self, now):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def stop_soon(seconds=0.4):
|
||||||
|
stop = threading.Event()
|
||||||
|
threading.Timer(seconds, stop.set).start()
|
||||||
|
return stop
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_view_shows_error_and_stays_up_until_stopped(monkeypatch):
|
||||||
|
monkeypatch.setenv("VIEW", "bogus")
|
||||||
|
main.main(stop_soon())
|
||||||
|
lcd = FakeLcd.instances[0]
|
||||||
|
assert lcd.calls == [((480, 320), 0, 0)] # the error screen, drawn once
|
||||||
|
assert lcd.closed
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_view_variable_is_an_error_screen_too(monkeypatch):
|
||||||
|
monkeypatch.delenv("VIEW", raising=False)
|
||||||
|
main.main(stop_soon())
|
||||||
|
assert FakeLcd.instances[0].calls == [((480, 320), 0, 0)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_known_view_runs_and_is_stopped_cleanly(monkeypatch):
|
||||||
|
view = StubView()
|
||||||
|
monkeypatch.setitem(registry.REGISTRY, "stub", lambda: view)
|
||||||
|
monkeypatch.setenv("VIEW", "stub")
|
||||||
|
main.main(stop_soon())
|
||||||
|
lcd = FakeLcd.instances[0]
|
||||||
|
assert view.started and view.stopped and lcd.closed
|
||||||
|
assert lcd.calls[0] == ((480, 320), 0, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_settings_reach_the_screen(monkeypatch):
|
||||||
|
monkeypatch.setitem(registry.REGISTRY, "stub", StubView)
|
||||||
|
monkeypatch.setenv("VIEW", "stub")
|
||||||
|
monkeypatch.setenv("SCREEN_BRIGHTNESS", "70")
|
||||||
|
main.main(stop_soon(0.2))
|
||||||
|
lcd = FakeLcd.instances[0]
|
||||||
|
assert (lcd.com_port, lcd.orientation, lcd.brightness) == ("/dev/fake", FakeOrientation.LANDSCAPE, 70)
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import fnmatch
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
|
|
||||||
|
def copied_sources():
|
||||||
|
sources = []
|
||||||
|
for line in (ROOT / "Dockerfile").read_text().splitlines():
|
||||||
|
match = re.match(r"^COPY\s+(.+)\s+\S+$", line.strip())
|
||||||
|
if match:
|
||||||
|
sources += match.group(1).split()
|
||||||
|
return sources
|
||||||
|
|
||||||
|
|
||||||
|
def test_dockerfile_copies_every_top_level_module():
|
||||||
|
"""A new view module must reach the image without anyone editing the Dockerfile."""
|
||||||
|
sources = copied_sources()
|
||||||
|
missing = [p.name for p in ROOT.glob("*.py") if not any(fnmatch.fnmatch(p.name, s) for s in sources)]
|
||||||
|
assert missing == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_dockerignore_keeps_dev_files_out_of_the_image_but_not_assets():
|
||||||
|
ignored = (ROOT / ".dockerignore").read_text().split()
|
||||||
|
for name in (".venv", ".git", "tests", "docs", ".superpowers"):
|
||||||
|
assert name in ignored
|
||||||
|
assert "assets" not in ignored
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import threading
|
||||||
|
import time
|
||||||
|
|
||||||
|
from poller import Poller
|
||||||
|
|
||||||
|
|
||||||
|
class FakeClock:
|
||||||
|
def __init__(self):
|
||||||
|
self.now = 1000.0
|
||||||
|
|
||||||
|
def __call__(self):
|
||||||
|
return self.now
|
||||||
|
|
||||||
|
|
||||||
|
def flaky(results):
|
||||||
|
"""fetch() returning each item of `results` in turn; an Exception item is raised."""
|
||||||
|
items = iter(results)
|
||||||
|
|
||||||
|
def fetch():
|
||||||
|
item = next(items)
|
||||||
|
if isinstance(item, Exception):
|
||||||
|
raise item
|
||||||
|
return item
|
||||||
|
|
||||||
|
return fetch
|
||||||
|
|
||||||
|
|
||||||
|
def test_success_stores_value_and_bumps_version():
|
||||||
|
p = Poller(flaky(["a"]), interval=10)
|
||||||
|
assert p.poll_once() is True
|
||||||
|
assert (p.value, p.version, p.failures) == ("a", 1, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_failure_keeps_last_good_value_and_counts():
|
||||||
|
p = Poller(flaky(["a", RuntimeError("boom")]), interval=10)
|
||||||
|
p.poll_once()
|
||||||
|
assert p.poll_once() is False
|
||||||
|
assert (p.value, p.version, p.failures) == ("a", 1, 1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_success_resets_failures():
|
||||||
|
p = Poller(flaky([RuntimeError("x"), RuntimeError("y"), "b"]), interval=10)
|
||||||
|
p.poll_once()
|
||||||
|
p.poll_once()
|
||||||
|
assert p.failures == 2
|
||||||
|
p.poll_once()
|
||||||
|
assert (p.value, p.failures) == ("b", 0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_age_uses_injected_clock():
|
||||||
|
clock = FakeClock()
|
||||||
|
p = Poller(flaky(["a"]), interval=10, clock=clock)
|
||||||
|
p.poll_once()
|
||||||
|
clock.now += 90
|
||||||
|
assert p.age() == 90
|
||||||
|
|
||||||
|
|
||||||
|
def test_age_none_before_first_success():
|
||||||
|
p = Poller(flaky([RuntimeError("x")]), interval=10)
|
||||||
|
assert p.age() is None
|
||||||
|
p.poll_once()
|
||||||
|
assert p.age() is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_slow_fetch_does_not_block_reader():
|
||||||
|
release = threading.Event()
|
||||||
|
|
||||||
|
def slow():
|
||||||
|
release.wait(5)
|
||||||
|
return "late"
|
||||||
|
|
||||||
|
p = Poller(slow, interval=60)
|
||||||
|
p.start()
|
||||||
|
try:
|
||||||
|
assert p.value is None # returns immediately although fetch is blocked
|
||||||
|
release.set()
|
||||||
|
deadline = time.monotonic() + 5
|
||||||
|
while p.version == 0 and time.monotonic() < deadline:
|
||||||
|
time.sleep(0.01)
|
||||||
|
assert (p.value, p.version) == ("late", 1)
|
||||||
|
finally:
|
||||||
|
release.set()
|
||||||
|
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))
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
|
from registry import REGISTRY, UnknownView, make_view
|
||||||
|
|
||||||
|
|
||||||
|
def test_registry_has_all_views():
|
||||||
|
assert sorted(REGISTRY) == ["iss", "server", "sky", "weather"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_make_view_builds_named_views():
|
||||||
|
for name in ("weather", "server", "sky", "iss"):
|
||||||
|
assert make_view(name).name == name
|
||||||
|
|
||||||
|
|
||||||
|
def test_make_view_unknown_lists_valid_names():
|
||||||
|
with pytest.raises(UnknownView) as err:
|
||||||
|
make_view("bogus")
|
||||||
|
assert err.value.name == "bogus"
|
||||||
|
assert err.value.valid == ["iss", "server", "sky", "weather"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_make_view_empty_name_is_unknown():
|
||||||
|
with pytest.raises(UnknownView):
|
||||||
|
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
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
import logging
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
import runner
|
||||||
|
from lcdkit import BG, INK
|
||||||
|
from tests.helpers import count_colour
|
||||||
|
from view import Patch
|
||||||
|
|
||||||
|
|
||||||
|
class FakeLcd:
|
||||||
|
def __init__(self, fail_first=0, always_fail=False):
|
||||||
|
self.calls = [] # (size, x, y)
|
||||||
|
self._fail_first, self._always_fail = fail_first, always_fail
|
||||||
|
|
||||||
|
def DisplayPILImage(self, image, x=0, y=0, image_width=None, image_height=None):
|
||||||
|
if self._always_fail or self._fail_first > 0:
|
||||||
|
self._fail_first -= 1
|
||||||
|
raise OSError("serial hiccup")
|
||||||
|
self.calls.append((image.size, x, y))
|
||||||
|
|
||||||
|
|
||||||
|
class StubView:
|
||||||
|
name = "stub"
|
||||||
|
|
||||||
|
def __init__(self, keys, with_patch=True, render_fn=None):
|
||||||
|
self._keys = keys # callable(now) -> key
|
||||||
|
self._with_patch = with_patch
|
||||||
|
self._render_fn = render_fn # callable(now) -> Image, default: a blank frame
|
||||||
|
self.renders = 0
|
||||||
|
|
||||||
|
def start(self): ...
|
||||||
|
def stop(self): ...
|
||||||
|
|
||||||
|
def frame_key(self, now):
|
||||||
|
return self._keys(now)
|
||||||
|
|
||||||
|
def render(self, now):
|
||||||
|
self.renders += 1
|
||||||
|
return self._render_fn(now) if self._render_fn else Image.new("RGB", (480, 320), BG)
|
||||||
|
|
||||||
|
def patch(self, now):
|
||||||
|
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):
|
||||||
|
"""running() that is true for the first n calls."""
|
||||||
|
state = {"left": n}
|
||||||
|
|
||||||
|
def running():
|
||||||
|
state["left"] -= 1
|
||||||
|
return state["left"] >= 0
|
||||||
|
|
||||||
|
return running
|
||||||
|
|
||||||
|
|
||||||
|
def clock(start, step_s):
|
||||||
|
state = {"now": start - timedelta(seconds=step_s)}
|
||||||
|
|
||||||
|
def now_fn():
|
||||||
|
state["now"] += timedelta(seconds=step_s)
|
||||||
|
return state["now"]
|
||||||
|
|
||||||
|
return now_fn
|
||||||
|
|
||||||
|
|
||||||
|
T0 = datetime(2026, 10, 22, 14, 32, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_pushes_full_frame_once_per_key():
|
||||||
|
lcd, view = FakeLcd(), StubView(lambda now: "same", with_patch=False)
|
||||||
|
runner.run(view, lcd, now_fn=clock(T0, 0), running=ticks(3), sleep=lambda s: None)
|
||||||
|
assert lcd.calls == [((480, 320), 0, 0)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_pushes_patch_each_new_second_only():
|
||||||
|
lcd, view = FakeLcd(), StubView(lambda now: "same")
|
||||||
|
# ticks at seconds 0, 0, 1, 1, 2 -> full frame, then one patch per *new* second
|
||||||
|
seconds = iter([0, 0, 1, 1, 2])
|
||||||
|
now_fn = lambda: T0.replace(second=next(seconds))
|
||||||
|
runner.run(view, lcd, now_fn=now_fn, running=ticks(5), sleep=lambda s: None)
|
||||||
|
assert lcd.calls == [((480, 320), 0, 0), ((10, 5), 100, 50), ((10, 5), 100, 50)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_pushes_only_the_changed_region_when_the_key_changes():
|
||||||
|
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)
|
||||||
|
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():
|
||||||
|
lcd, view = FakeLcd(fail_first=1), StubView(lambda now: "same", with_patch=False)
|
||||||
|
runner.run(view, lcd, now_fn=clock(T0, 0), running=ticks(3), sleep=lambda s: None)
|
||||||
|
assert lcd.calls == [((480, 320), 0, 0)] # failed once, redrawn on the next tick, then stable
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_raises_after_max_failures():
|
||||||
|
lcd, view = FakeLcd(always_fail=True), StubView(lambda now: "same")
|
||||||
|
with pytest.raises(OSError):
|
||||||
|
runner.run(view, lcd, now_fn=clock(T0, 0), running=ticks(50), sleep=lambda s: None, max_failures=3)
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_screen_retries_until_available(caplog):
|
||||||
|
attempts, sleeps = [], []
|
||||||
|
|
||||||
|
def factory():
|
||||||
|
attempts.append(1)
|
||||||
|
if len(attempts) < 3:
|
||||||
|
raise OSError("no such device")
|
||||||
|
return "lcd"
|
||||||
|
|
||||||
|
with caplog.at_level(logging.WARNING):
|
||||||
|
result = runner.open_screen(factory, running=lambda: True, sleep=sleeps.append)
|
||||||
|
assert result == "lcd"
|
||||||
|
assert sleeps == [30.0, 30.0]
|
||||||
|
assert len([r for r in caplog.records if r.levelno == logging.WARNING]) == 1 # logged once
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_screen_returns_none_when_stopped():
|
||||||
|
def factory():
|
||||||
|
raise OSError("no such device")
|
||||||
|
|
||||||
|
assert runner.open_screen(factory, running=ticks(1), sleep=lambda s: None) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_idle_with_message_draws_once_and_returns_on_stop():
|
||||||
|
lcd = FakeLcd()
|
||||||
|
runner.idle_with_message(lcd, ["UNKNOWN VIEW: bogus"], running=ticks(4), sleep=lambda s: None)
|
||||||
|
assert lcd.calls == [((480, 320), 0, 0)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_error_size_and_has_ink():
|
||||||
|
img = runner.render_error(["UNKNOWN VIEW: bogus", "VALID: server, weather"])
|
||||||
|
assert img.size == (480, 320)
|
||||||
|
assert count_colour(img, INK) > 500
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_error_long_line_does_not_raise():
|
||||||
|
assert runner.render_error(["X" * 500]).size == (480, 320)
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_screen_retries_when_the_library_calls_sys_exit():
|
||||||
|
"""The pinned screen library calls sys.exit(0) when the port is missing; that must not end the process."""
|
||||||
|
attempts, sleeps = [], []
|
||||||
|
|
||||||
|
def factory():
|
||||||
|
attempts.append(1)
|
||||||
|
if len(attempts) < 3:
|
||||||
|
raise SystemExit(0)
|
||||||
|
return "lcd"
|
||||||
|
|
||||||
|
assert runner.open_screen(factory, running=lambda: True, sleep=sleeps.append) == "lcd"
|
||||||
|
assert sleeps == [30.0, 30.0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_counts_library_sys_exit_as_a_failed_draw():
|
||||||
|
class ExitingLcd:
|
||||||
|
def DisplayPILImage(self, *a, **k):
|
||||||
|
raise SystemExit(0)
|
||||||
|
|
||||||
|
view = StubView(lambda now: "same")
|
||||||
|
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)
|
||||||
|
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)]
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from PIL import ImageChops
|
||||||
|
|
||||||
|
from cyber import DIM, RED, TEXT
|
||||||
|
from server_view import ServerView
|
||||||
|
from stats_data import Container, Proc, Stats
|
||||||
|
from tests.helpers import count_colour, count_near
|
||||||
|
|
||||||
|
NOW = datetime(2026, 10, 22, 14, 32, 8)
|
||||||
|
|
||||||
|
|
||||||
|
class StubPoller:
|
||||||
|
def __init__(self, value=None, version=1, age=2.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 containers(n, state="running", health="healthy"):
|
||||||
|
return tuple(Container(f"service-{i}", state, health) for i in range(n))
|
||||||
|
|
||||||
|
|
||||||
|
def stats(**kw):
|
||||||
|
base = dict(cpu_pct=14.0, mem_pct=62.0, disk_pct=6.0, load=(0.6, 0.52, 0.44), temp_c=41.0,
|
||||||
|
uptime_s=934423.0, containers=containers(5),
|
||||||
|
procs=(Proc("postgres", 4.5), Proc("node", 2.0)))
|
||||||
|
base.update(kw)
|
||||||
|
return Stats(**base)
|
||||||
|
|
||||||
|
|
||||||
|
def view(value, **kw):
|
||||||
|
return ServerView(StubPoller(value, **kw))
|
||||||
|
|
||||||
|
|
||||||
|
def region_diff(a, b):
|
||||||
|
return ImageChops.difference(a.convert("RGB"), b.convert("RGB")).getbbox()
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_size_is_480x320():
|
||||||
|
assert view(stats()).render(NOW).size == (480, 320)
|
||||||
|
|
||||||
|
|
||||||
|
def test_frame_key_follows_the_data_not_the_clock():
|
||||||
|
p = StubPoller(stats(), version=1)
|
||||||
|
v = ServerView(p)
|
||||||
|
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():
|
||||||
|
p = StubPoller(stats(), version=1, age=2.0)
|
||||||
|
v = ServerView(p)
|
||||||
|
key = v.frame_key(NOW)
|
||||||
|
p.version = 2
|
||||||
|
assert v.frame_key(NOW) != key
|
||||||
|
key = v.frame_key(NOW)
|
||||||
|
p._age = ServerView.STALE_AFTER + 1
|
||||||
|
assert v.frame_key(NOW) != key
|
||||||
|
|
||||||
|
|
||||||
|
def test_patch_is_none():
|
||||||
|
assert view(stats()).patch(NOW) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_none_stats_render_without_error():
|
||||||
|
empty = Stats(None, None, None, None, None, None, None, ())
|
||||||
|
img = view(empty).render(NOW)
|
||||||
|
assert img.size == (480, 320)
|
||||||
|
assert view(None, version=0, age=None).render(NOW).size == (480, 320)
|
||||||
|
|
||||||
|
|
||||||
|
def test_many_containers_are_truncated_with_remainder():
|
||||||
|
few = view(stats(containers=containers(5))).render(NOW)
|
||||||
|
many = view(stats(containers=containers(30))).render(NOW)
|
||||||
|
assert many.size == (480, 320)
|
||||||
|
assert region_diff(few, many) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_stale_tag_only_when_old():
|
||||||
|
fresh = view(stats(), age=2.0).render(NOW)
|
||||||
|
old = view(stats(), age=ServerView.STALE_AFTER + 5).render(NOW)
|
||||||
|
bbox = region_diff(fresh, old)
|
||||||
|
assert bbox is not None
|
||||||
|
assert bbox[0] >= 360 and bbox[1] >= 12 and bbox[3] <= 44 # only the top-right status corner changes
|
||||||
|
|
||||||
|
|
||||||
|
def test_gauge_reflects_value():
|
||||||
|
idle = view(stats(cpu_pct=0.0)).render(NOW)
|
||||||
|
busy = view(stats(cpu_pct=60.0)).render(NOW)
|
||||||
|
box = (24, 76, 246, 86) # the CPU gauge
|
||||||
|
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():
|
||||||
|
listed = view(stats()).render(NOW)
|
||||||
|
missing = view(stats(containers=None)).render(NOW)
|
||||||
|
bbox = region_diff(listed, missing)
|
||||||
|
assert bbox is not None
|
||||||
|
assert bbox[1] >= 176 and bbox[2] <= 322 # only the docker panel changes
|
||||||
|
|
||||||
|
|
||||||
|
def test_attention_containers_sort_first():
|
||||||
|
sick = Container("zzz-broken", "running", "unhealthy")
|
||||||
|
fine = containers(7)
|
||||||
|
first_rows = view(stats(containers=fine + (sick,))).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
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
@@ -0,0 +1,292 @@
|
|||||||
|
import json
|
||||||
|
import socketserver
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import stats_data
|
||||||
|
from stats_data import (Container, StatsReader, cpu_pct, list_containers, parse_cpu_times,
|
||||||
|
parse_mem_pct, parse_pid_stat, short_name, status_label)
|
||||||
|
|
||||||
|
FIXTURES = Path(__file__).parent / "fixtures"
|
||||||
|
|
||||||
|
|
||||||
|
# --- pure parsers -----------------------------------------------------------
|
||||||
|
|
||||||
|
def test_parse_cpu_times_and_pct():
|
||||||
|
first = parse_cpu_times("cpu 100 0 50 800 50 0 0 0 0 0\ncpu0 1 2 3 4 5 6 7 8 9 10\n")
|
||||||
|
second = parse_cpu_times("cpu 200 0 100 1600 100 0 0 0 0 0\n")
|
||||||
|
assert first == (150, 1000) # busy = total - idle - iowait
|
||||||
|
assert second == (300, 2000)
|
||||||
|
assert cpu_pct(first, second) == pytest.approx(15.0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_cpu_pct_none_without_previous():
|
||||||
|
assert cpu_pct(None, (300, 2000)) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_cpu_pct_none_on_zero_delta():
|
||||||
|
assert cpu_pct((300, 2000), (300, 2000)) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_mem_pct_real_fixture():
|
||||||
|
# fixture: MemTotal 16147480 kB, MemAvailable 13909124 kB (home server)
|
||||||
|
assert parse_mem_pct((FIXTURES / "meminfo").read_text()) == pytest.approx(13.86, abs=0.01)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_pid_stat_with_parens_and_spaces():
|
||||||
|
text = "4242 (my (odd) proc) S 1 4242 4242 0 -1 4194304 100 0 0 0 70 30 0 0 20 0 1 0 12345 1 2"
|
||||||
|
assert parse_pid_stat(text) == ("my (odd) proc", 100)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("name, expected", [
|
||||||
|
("n8n-ebe62bdjbp9f755kwh59lv8d", "n8n"),
|
||||||
|
("screen-pe28mpghgqnxaz12vyfyijrg-151725872213", "screen"),
|
||||||
|
("task-runners-ebe62bdjbp9f755kwh59lv8d", "task-runners"),
|
||||||
|
("plex-z0qh1wrbuzxo0jsfiazc3evc", "plex"),
|
||||||
|
("coolify-db", "coolify-db"),
|
||||||
|
])
|
||||||
|
def test_short_name_strips_coolify_suffix(name, expected):
|
||||||
|
assert short_name(name, {}, "x/y:1") == expected
|
||||||
|
|
||||||
|
|
||||||
|
def test_short_name_hash_only_uses_label_then_image_then_hash():
|
||||||
|
hashed = "jn5mdu87ituoxzyojk84ugdj-20261018T132559"
|
||||||
|
assert short_name(hashed, {"com.docker.compose.service": "web"}, "a/b:1") == "web"
|
||||||
|
assert short_name(hashed, {}, "ghcr.io/acme/tool:1.2") == "tool"
|
||||||
|
# the real container on the server: hash in name, label and image
|
||||||
|
assert short_name(hashed, {"com.docker.compose.service": hashed},
|
||||||
|
"jn5mdu87ituoxzyojk84ugdj:1833c2f1bf67cbe93e579ed6d9b569fe3cd3b668") == "jn5mdu87"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("state, health, expected", [
|
||||||
|
("running", "healthy", "OK"),
|
||||||
|
("running", None, "UP"),
|
||||||
|
("running", "starting", "UP"),
|
||||||
|
("running", "unhealthy", "UNHEALTHY"),
|
||||||
|
("restarting", None, "RESTART"),
|
||||||
|
("exited", None, "EXITED"),
|
||||||
|
])
|
||||||
|
def test_status_label_cases(state, health, expected):
|
||||||
|
assert status_label(Container("x", state, health)) == expected
|
||||||
|
|
||||||
|
|
||||||
|
# --- docker over a unix socket ---------------------------------------------
|
||||||
|
|
||||||
|
class FakeDocker:
|
||||||
|
"""Tiny HTTP server on a unix socket (relative path: macOS limits socket paths to ~100 chars)."""
|
||||||
|
|
||||||
|
def __init__(self, path: str, body: bytes = b"[]", hang: bool = False):
|
||||||
|
self.release = threading.Event()
|
||||||
|
self.requests = 0
|
||||||
|
outer = self
|
||||||
|
|
||||||
|
class Handler(socketserver.StreamRequestHandler):
|
||||||
|
def handle(self):
|
||||||
|
while self.rfile.readline() not in (b"\r\n", b""):
|
||||||
|
pass
|
||||||
|
outer.requests += 1
|
||||||
|
if hang:
|
||||||
|
outer.release.wait(5)
|
||||||
|
return
|
||||||
|
self.wfile.write(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
|
||||||
|
+ f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n".encode() + body)
|
||||||
|
|
||||||
|
self.server = socketserver.ThreadingUnixStreamServer(path, Handler)
|
||||||
|
self.server.daemon_threads = True
|
||||||
|
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
||||||
|
self.thread.start()
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.release.set()
|
||||||
|
self.server.shutdown()
|
||||||
|
self.server.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def docker_in(tmp_path, monkeypatch):
|
||||||
|
monkeypatch.chdir(tmp_path)
|
||||||
|
servers = []
|
||||||
|
|
||||||
|
def make(body=b"[]", hang=False):
|
||||||
|
s = FakeDocker("d.sock", body, hang)
|
||||||
|
servers.append(s)
|
||||||
|
make.server = s
|
||||||
|
return "d.sock"
|
||||||
|
|
||||||
|
yield make
|
||||||
|
for s in servers:
|
||||||
|
s.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_containers_parses_fixture(docker_in):
|
||||||
|
sock = docker_in((FIXTURES / "docker_containers.json").read_bytes())
|
||||||
|
containers = {c.name: c for c in list_containers(sock)}
|
||||||
|
assert containers["coolify"] == Container("coolify", "running", "healthy")
|
||||||
|
assert containers["n8n"].health == "healthy"
|
||||||
|
assert containers["screen"] == Container("screen", "running", None)
|
||||||
|
assert containers["apod-test"].state == "exited"
|
||||||
|
assert "jn5mdu87" in containers
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_containers_missing_socket_raises(tmp_path):
|
||||||
|
with pytest.raises(OSError):
|
||||||
|
list_containers(str(tmp_path / "nope.sock"))
|
||||||
|
|
||||||
|
|
||||||
|
# --- reader on a fake /proc tree ---------------------------------------------
|
||||||
|
|
||||||
|
def write_proc(root: Path, cpu: str, procs: dict[int, str]):
|
||||||
|
root.mkdir(parents=True, exist_ok=True)
|
||||||
|
(root / "stat").write_text(cpu + "\n")
|
||||||
|
(root / "meminfo").write_text((FIXTURES / "meminfo").read_text())
|
||||||
|
(root / "loadavg").write_text("0.60 0.52 0.44 3/777 3724104\n")
|
||||||
|
(root / "uptime").write_text("934423.99 5265468.77\n")
|
||||||
|
for pid, stat in procs.items():
|
||||||
|
(root / str(pid)).mkdir(exist_ok=True)
|
||||||
|
(root / str(pid) / "stat").write_text(stat)
|
||||||
|
|
||||||
|
|
||||||
|
def pid_line(pid, name, ticks):
|
||||||
|
return f"{pid} ({name}) S 1 {pid} {pid} 0 -1 4194304 0 0 0 0 {ticks} 0 0 0 20 0 1 0 1 1 1\n"
|
||||||
|
|
||||||
|
|
||||||
|
def thermal(sys_root: Path, zones: dict[str, tuple[str, int]]):
|
||||||
|
for zone, (kind, milli) in zones.items():
|
||||||
|
z = sys_root / "class" / "thermal" / zone
|
||||||
|
z.mkdir(parents=True)
|
||||||
|
(z / "type").write_text(kind + "\n")
|
||||||
|
(z / "temp").write_text(f"{milli}\n")
|
||||||
|
|
||||||
|
|
||||||
|
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"
|
||||||
|
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),
|
||||||
|
12: pid_line(12, "node", 0)})
|
||||||
|
return StatsReader(proc_root=str(proc), sys_root=str(sys_root), disk_path=str(tmp_path),
|
||||||
|
docker_sock=docker_sock, **kw), proc
|
||||||
|
|
||||||
|
|
||||||
|
def test_reader_first_read_has_no_cpu_pct(tmp_path):
|
||||||
|
reader, _ = make_reader(tmp_path)
|
||||||
|
s = reader.read()
|
||||||
|
assert s.cpu_pct is None and s.procs == ()
|
||||||
|
assert s.mem_pct == pytest.approx(13.86, abs=0.01)
|
||||||
|
assert s.load == (0.60, 0.52, 0.44)
|
||||||
|
assert s.uptime_s == pytest.approx(934423.99)
|
||||||
|
assert 0 <= s.disk_pct <= 100
|
||||||
|
|
||||||
|
|
||||||
|
def test_reader_second_read_has_cpu_and_grouped_processes(tmp_path):
|
||||||
|
reader, proc = make_reader(tmp_path)
|
||||||
|
reader.read()
|
||||||
|
write_proc(proc, "cpu 200 0 100 1600 100 0 0 0 0 0",
|
||||||
|
{10: pid_line(10, "postgres", 60), 11: pid_line(11, "postgres", 40), 12: pid_line(12, "node", 20)})
|
||||||
|
s = reader.read()
|
||||||
|
assert s.cpu_pct == pytest.approx(15.0)
|
||||||
|
names = [(p.name, round(p.cpu_pct, 1)) for p in s.procs]
|
||||||
|
assert names == [("postgres", 10.0), ("node", 2.0)] # share of total jiffies delta (1000), grouped by name
|
||||||
|
|
||||||
|
|
||||||
|
def test_reader_prefers_cpu_package_temperature(tmp_path):
|
||||||
|
reader, _ = make_reader(tmp_path)
|
||||||
|
assert reader.read().temp_c == 41.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_reader_temperature_falls_back_to_hottest_zone(tmp_path):
|
||||||
|
reader, _ = make_reader(tmp_path)
|
||||||
|
for z in (tmp_path / "sys" / "class" / "thermal").glob("thermal_zone1"):
|
||||||
|
(z / "type").write_text("other\n")
|
||||||
|
assert reader.read().temp_c == 41.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_reader_survives_vanished_process(tmp_path):
|
||||||
|
reader, proc = make_reader(tmp_path)
|
||||||
|
reader.read()
|
||||||
|
(proc / "12" / "stat").unlink() # directory still listed, file gone: the process exited mid-read
|
||||||
|
write_proc(proc, "cpu 200 0 100 1600 100 0 0 0 0 0", {10: pid_line(10, "postgres", 10)})
|
||||||
|
s = reader.read()
|
||||||
|
assert s.cpu_pct == pytest.approx(15.0)
|
||||||
|
assert [p.name for p in s.procs] == ["postgres"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_reader_docker_down_still_returns_other_stats(tmp_path):
|
||||||
|
reader, _ = make_reader(tmp_path, docker_sock=str(tmp_path / "nope.sock"))
|
||||||
|
s = reader.read()
|
||||||
|
assert s.containers is None
|
||||||
|
assert s.mem_pct is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_reader_reads_containers(tmp_path, docker_in):
|
||||||
|
sock = docker_in((FIXTURES / "docker_containers.json").read_bytes())
|
||||||
|
reader, _ = make_reader(tmp_path, docker_sock=sock)
|
||||||
|
s = reader.read()
|
||||||
|
assert s.containers is not None and any(c.name == "n8n" for c in s.containers)
|
||||||
|
|
||||||
|
|
||||||
|
def test_reader_docker_hang_times_out(tmp_path, docker_in):
|
||||||
|
sock = docker_in(hang=True)
|
||||||
|
reader, _ = make_reader(tmp_path, docker_sock=sock, docker_timeout=0.3)
|
||||||
|
start = time.monotonic()
|
||||||
|
s = reader.read()
|
||||||
|
assert time.monotonic() - start < 2.0
|
||||||
|
assert s.containers is None and s.mem_pct is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_reader_missing_proc_files_give_none_not_error(tmp_path):
|
||||||
|
reader = StatsReader(proc_root=str(tmp_path / "nothing"), sys_root=str(tmp_path / "nothing"),
|
||||||
|
disk_path=str(tmp_path / "nothing"), docker_sock="missing.sock")
|
||||||
|
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.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)
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
import copy
|
||||||
|
import json
|
||||||
|
from datetime import date, datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import weather_data
|
||||||
|
from weather_data import Day, Icon, icon_for, parse_weather
|
||||||
|
|
||||||
|
FIXTURE = json.loads((Path(__file__).parent / "fixtures" / "open-meteo-zlin.json").read_text())
|
||||||
|
NOW = datetime(2026, 10, 22, 12, 45)
|
||||||
|
|
||||||
|
|
||||||
|
def payload():
|
||||||
|
return copy.deepcopy(FIXTURE)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_fixture_window():
|
||||||
|
w = parse_weather(payload(), NOW)
|
||||||
|
assert len(w.hours) == 12
|
||||||
|
assert w.hours[0].time == datetime(2026, 10, 22, 12, 0)
|
||||||
|
assert w.hours[-1].time == datetime(2026, 10, 22, 23, 0)
|
||||||
|
assert w.hours[0].rain_pct == FIXTURE["hourly"]["precipitation_probability"][12]
|
||||||
|
assert w.hours[0].mm == FIXTURE["hourly"]["precipitation"][12]
|
||||||
|
assert (w.temp, w.code) == (10.2, 61)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_week_with_sunrise_and_sunset():
|
||||||
|
w = parse_weather(payload(), NOW)
|
||||||
|
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():
|
||||||
|
w = parse_weather(payload(), datetime(2026, 10, 22, 20, 10))
|
||||||
|
assert w.hours[0].time == datetime(2026, 10, 22, 20, 0)
|
||||||
|
assert w.hours[-1].time == datetime(2026, 10, 23, 7, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_icon_mapping():
|
||||||
|
assert icon_for(0) is Icon.SUN
|
||||||
|
assert icon_for(2) is Icon.PARTLY
|
||||||
|
assert icon_for(3) is Icon.CLOUDY
|
||||||
|
assert icon_for(45) is Icon.FOG
|
||||||
|
assert icon_for(61) is Icon.RAIN
|
||||||
|
assert icon_for(81) is Icon.RAIN
|
||||||
|
assert icon_for(73) is Icon.SNOW
|
||||||
|
assert icon_for(95) is Icon.STORM
|
||||||
|
assert icon_for(999) is None
|
||||||
|
assert icon_for(None) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_null_entries_become_none():
|
||||||
|
p = payload()
|
||||||
|
p["hourly"]["precipitation_probability"][13] = None
|
||||||
|
p["hourly"]["precipitation"][13] = None
|
||||||
|
w = parse_weather(p, NOW)
|
||||||
|
assert (w.hours[1].rain_pct, w.hours[1].mm) == (None, None)
|
||||||
|
assert w.hours[0].rain_pct is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_short_hourly_gives_fewer_hours():
|
||||||
|
p = payload()
|
||||||
|
for key in ("time", "precipitation_probability", "precipitation"):
|
||||||
|
p["hourly"][key] = p["hourly"][key][:14]
|
||||||
|
assert len(parse_weather(p, NOW).hours) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_current_gives_none_temp():
|
||||||
|
p = payload()
|
||||||
|
del p["current"]
|
||||||
|
w = parse_weather(p, NOW)
|
||||||
|
assert (w.temp, w.code) == (None, None)
|
||||||
|
assert len(w.hours) == 12
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_sections_do_not_raise():
|
||||||
|
w = parse_weather({}, NOW)
|
||||||
|
assert (w.temp, w.feels, w.days, w.hours) == (None, None, (), ())
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_passes_coordinates():
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
class Response:
|
||||||
|
def raise_for_status(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return payload()
|
||||||
|
|
||||||
|
def fake_get(url, params=None, timeout=None):
|
||||||
|
calls.append((url, params, timeout))
|
||||||
|
return Response()
|
||||||
|
|
||||||
|
w = weather_data.fetch_weather(NOW, get=fake_get)
|
||||||
|
url, params, timeout = calls[0]
|
||||||
|
assert url.startswith("https://api.open-meteo.com/")
|
||||||
|
assert params["latitude"] == weather_data.LAT == 49.2265
|
||||||
|
assert params["longitude"] == weather_data.LON == 17.6627
|
||||||
|
assert params["timezone"] == "Europe/Prague"
|
||||||
|
assert timeout == 10
|
||||||
|
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(",")
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
from datetime import date, datetime, time, timedelta
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from PIL import ImageChops
|
||||||
|
|
||||||
|
from lcdkit import BG, INK
|
||||||
|
from tests.helpers import count_colour
|
||||||
|
from view import Patch
|
||||||
|
from weather_data import Day, Hour, Weather
|
||||||
|
from weather_view import WeatherView, is_night
|
||||||
|
|
||||||
|
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:
|
||||||
|
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 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))
|
||||||
|
return Weather(temp=temp, feels=12.1, code=code, days=week() if days is None else days, hours=hours)
|
||||||
|
|
||||||
|
|
||||||
|
def view(**kw):
|
||||||
|
return WeatherView(StubPoller(**kw))
|
||||||
|
|
||||||
|
|
||||||
|
def ink_bbox(img, box):
|
||||||
|
"""Bounding box of INK pixels inside `box`, in image coordinates, or None."""
|
||||||
|
region = np.asarray(img.crop(box).convert("RGB"))
|
||||||
|
ys, xs = np.where((region == np.array(INK)).all(axis=2))
|
||||||
|
if len(xs) == 0:
|
||||||
|
return None
|
||||||
|
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():
|
||||||
|
assert view(value=weather()).render(NOW).size == (480, 320)
|
||||||
|
|
||||||
|
|
||||||
|
def test_frame_key_changes_each_minute_not_each_second():
|
||||||
|
v = view(value=weather())
|
||||||
|
assert v.frame_key(datetime(2026, 10, 22, 12, 45, 0)) == v.frame_key(datetime(2026, 10, 22, 12, 45, 59))
|
||||||
|
assert v.frame_key(datetime(2026, 10, 22, 12, 45, 59)) != v.frame_key(datetime(2026, 10, 22, 12, 46, 0))
|
||||||
|
|
||||||
|
|
||||||
|
def test_frame_key_changes_when_weather_updates():
|
||||||
|
p = StubPoller(value=weather(), version=1)
|
||||||
|
v = WeatherView(p)
|
||||||
|
before = v.frame_key(NOW)
|
||||||
|
p.version = 2
|
||||||
|
assert v.frame_key(NOW) != before
|
||||||
|
|
||||||
|
|
||||||
|
def test_frame_key_changes_when_stale_flips():
|
||||||
|
p = StubPoller(value=weather(), age=60.0)
|
||||||
|
v = WeatherView(p)
|
||||||
|
before = v.frame_key(NOW)
|
||||||
|
p._age = WeatherView.STALE_AFTER + 1
|
||||||
|
assert v.frame_key(NOW) != before
|
||||||
|
|
||||||
|
|
||||||
|
def test_patch_matches_full_render_region():
|
||||||
|
v = view(value=weather())
|
||||||
|
patch = v.patch(NOW)
|
||||||
|
assert isinstance(patch, Patch)
|
||||||
|
full = v.render(NOW)
|
||||||
|
region = full.crop((patch.x, patch.y, patch.x + patch.image.width, patch.y + patch.image.height))
|
||||||
|
assert same(region, patch.image)
|
||||||
|
|
||||||
|
|
||||||
|
def test_patch_changes_with_the_second():
|
||||||
|
v = view(value=weather())
|
||||||
|
a = v.patch(datetime(2026, 10, 22, 12, 45, 8)).image
|
||||||
|
b = v.patch(datetime(2026, 10, 22, 12, 45, 9)).image
|
||||||
|
assert not same(a, b)
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_weather_renders_without_error():
|
||||||
|
img = view(value=None, version=0, age=None).render(NOW)
|
||||||
|
assert img.size == (480, 320)
|
||||||
|
# day names, clock and dashes are still drawn
|
||||||
|
assert count_colour(img, INK) > 1000
|
||||||
|
|
||||||
|
|
||||||
|
def test_stale_tag_only_when_old():
|
||||||
|
fresh = view(value=weather(), age=60.0).render(NOW)
|
||||||
|
old = view(value=weather(), age=7200.0).render(NOW)
|
||||||
|
bbox = ImageChops.difference(fresh.convert("RGB"), old.convert("RGB")).getbbox()
|
||||||
|
assert bbox is not None
|
||||||
|
assert bbox[0] >= 20 and bbox[1] >= 200 and bbox[2] <= 300 and bbox[3] <= 226 # on the rain header line
|
||||||
|
|
||||||
|
|
||||||
|
def test_today_is_the_first_day_and_inverted():
|
||||||
|
img = view(value=weather()).render(NOW)
|
||||||
|
assert img.getpixel((12 + 5, 14)) == INK
|
||||||
|
assert img.getpixel((12 + CELL + 5, 14)) != INK
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
warm = view(value=weather(temp=3.4)).render(NOW)
|
||||||
|
assert not same(cold, warm)
|
||||||
|
|
||||||
|
|
||||||
|
def test_fewer_than_twelve_hours_still_renders():
|
||||||
|
img = view(value=weather(rain=(10, 20))).render(NOW)
|
||||||
|
assert img.size == (480, 320)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_weather_code_renders():
|
||||||
|
assert view(value=weather(code=999)).render(NOW).size == (480, 320)
|
||||||
|
|
||||||
|
|
||||||
|
# night: from sunset to sunrise the frame is a reverse LCD
|
||||||
|
|
||||||
|
def test_is_night_between_sunset_and_sunrise():
|
||||||
|
w = weather() # sunrise 7:20, sunset 17:45
|
||||||
|
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
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
"""Wall-clock time independent of the container's own TZ."""
|
||||||
|
import os
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
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:
|
||||||
|
"""Naive wall-clock time in `tz_name` (default: env BOARD_TZ, else Europe/Prague)."""
|
||||||
|
return datetime.now(_zone(tz_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()
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""What a screen view looks like to the runner."""
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Hashable, Protocol
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Patch:
|
||||||
|
"""A partial update: draw `image` with its top-left corner at (x, y)."""
|
||||||
|
image: Image.Image
|
||||||
|
x: int
|
||||||
|
y: int
|
||||||
|
|
||||||
|
|
||||||
|
class View(Protocol):
|
||||||
|
name: str
|
||||||
|
|
||||||
|
def start(self) -> None: ...
|
||||||
|
|
||||||
|
def stop(self) -> None: ...
|
||||||
|
|
||||||
|
def frame_key(self, now: datetime) -> Hashable:
|
||||||
|
"""Changes whenever a full redraw is needed."""
|
||||||
|
|
||||||
|
def render(self, now: datetime) -> Image.Image:
|
||||||
|
"""The full 480x320 frame."""
|
||||||
|
|
||||||
|
def patch(self, now: datetime) -> Patch | None:
|
||||||
|
"""Cheap partial update valid while frame_key is unchanged (e.g. the seconds)."""
|
||||||
+128
@@ -0,0 +1,128 @@
|
|||||||
|
"""Open-Meteo forecast for Zlín: fetching and parsing (no drawing)."""
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import date, datetime
|
||||||
|
from enum import Enum
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
LAT = 49.2265
|
||||||
|
LON = 17.6627
|
||||||
|
URL = "https://api.open-meteo.com/v1/forecast"
|
||||||
|
TIMEZONE = "Europe/Prague"
|
||||||
|
WINDOW_HOURS = 12
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Hour:
|
||||||
|
time: datetime # naive local time
|
||||||
|
rain_pct: int | 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)
|
||||||
|
class Weather:
|
||||||
|
temp: float | None
|
||||||
|
feels: float | None
|
||||||
|
code: int | None
|
||||||
|
days: tuple[Day, ...] # as the forecast gives them, today first when fresh
|
||||||
|
hours: tuple[Hour, ...] # at most WINDOW_HOURS, starting with the hour containing "now"
|
||||||
|
|
||||||
|
|
||||||
|
class Icon(Enum):
|
||||||
|
SUN = "sun"
|
||||||
|
PARTLY = "partly"
|
||||||
|
CLOUDY = "cloudy"
|
||||||
|
RAIN = "rain"
|
||||||
|
SNOW = "snow"
|
||||||
|
STORM = "storm"
|
||||||
|
FOG = "fog"
|
||||||
|
|
||||||
|
|
||||||
|
_WMO_ICONS = {
|
||||||
|
Icon.SUN: (0,),
|
||||||
|
Icon.PARTLY: (1, 2),
|
||||||
|
Icon.CLOUDY: (3,),
|
||||||
|
Icon.FOG: (45, 48),
|
||||||
|
Icon.RAIN: (*range(51, 58), *range(61, 68), 80, 81, 82),
|
||||||
|
Icon.SNOW: (*range(71, 78), 85, 86),
|
||||||
|
Icon.STORM: (95, 96, 99),
|
||||||
|
}
|
||||||
|
_ICON_BY_CODE = {code: icon for icon, codes in _WMO_ICONS.items() for code in codes}
|
||||||
|
|
||||||
|
|
||||||
|
def icon_for(code: int | None) -> Icon | None:
|
||||||
|
return _ICON_BY_CODE.get(code)
|
||||||
|
|
||||||
|
|
||||||
|
def _at(values, i: int):
|
||||||
|
"""values[i] or None when the list is missing, short, or holds a null."""
|
||||||
|
if not isinstance(values, list) or i >= len(values):
|
||||||
|
return None
|
||||||
|
return values[i]
|
||||||
|
|
||||||
|
|
||||||
|
def _time(value) -> datetime | None:
|
||||||
|
return datetime.fromisoformat(value) if value else None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_weather(payload: dict, now: datetime) -> Weather:
|
||||||
|
current = payload.get("current") or {}
|
||||||
|
daily = payload.get("daily") or {}
|
||||||
|
hourly = payload.get("hourly") or {}
|
||||||
|
|
||||||
|
days = tuple(
|
||||||
|
Day(
|
||||||
|
date=date.fromisoformat(day),
|
||||||
|
code=_at(daily.get("weather_code"), i),
|
||||||
|
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] = []
|
||||||
|
times = hourly.get("time") or []
|
||||||
|
start = now.strftime("%Y-%m-%dT%H:00")
|
||||||
|
if start in times:
|
||||||
|
first = times.index(start)
|
||||||
|
for i in range(first, min(first + WINDOW_HOURS, len(times))):
|
||||||
|
hours.append(Hour(
|
||||||
|
time=datetime.fromisoformat(times[i]),
|
||||||
|
rain_pct=_at(hourly.get("precipitation_probability"), i),
|
||||||
|
mm=_at(hourly.get("precipitation"), i),
|
||||||
|
))
|
||||||
|
|
||||||
|
return Weather(
|
||||||
|
temp=current.get("temperature_2m"),
|
||||||
|
feels=current.get("apparent_temperature"),
|
||||||
|
code=current.get("weather_code"),
|
||||||
|
days=days,
|
||||||
|
hours=tuple(hours),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_weather(now: datetime, get=requests.get) -> Weather:
|
||||||
|
params = {
|
||||||
|
"latitude": LAT,
|
||||||
|
"longitude": LON,
|
||||||
|
"current": "temperature_2m,weather_code,apparent_temperature",
|
||||||
|
"hourly": "precipitation_probability,precipitation",
|
||||||
|
"daily": "weather_code,temperature_2m_max,temperature_2m_min,sunrise,sunset",
|
||||||
|
"timezone": TIMEZONE,
|
||||||
|
"forecast_days": 7,
|
||||||
|
}
|
||||||
|
response = get(URL, params=params, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
return parse_weather(response.json(), now)
|
||||||
+184
@@ -0,0 +1,184 @@
|
|||||||
|
"""Casio-style weather clock: week ahead, time, date, current weather and a 12 hour rain forecast."""
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
import lcdkit
|
||||||
|
from lcdkit import BG, GHOST, H, INK, W
|
||||||
|
from poller import Poller
|
||||||
|
from view import Patch
|
||||||
|
from weather_data import Day, Icon, Weather, icon_for
|
||||||
|
|
||||||
|
WEEKDAYS = ["PO", "ÚT", "ST", "ČT", "PÁ", "SO", "NE"]
|
||||||
|
CELL = (W - 24) // 7 # one day of the forecast strip
|
||||||
|
SECONDS_BOX = (288, 104, 352, 148) # region redrawn once per second
|
||||||
|
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:
|
||||||
|
"""A cloud of width ~0.8*s sitting on the line y=base; `outline` first paints a background halo."""
|
||||||
|
for pad, colour in ((3, BG), (0, INK)) if outline else ((0, INK),):
|
||||||
|
d.ellipse((x + s * 0.30 - pad, base - s * 0.34 - pad, x + s * 0.68 + pad, base + pad), fill=colour)
|
||||||
|
d.ellipse((x + s * 0.52 - pad, base - s * 0.26 - pad, x + s * 0.95 + pad, base + pad), fill=colour)
|
||||||
|
d.rounded_rectangle((x + s * 0.18 - pad, base - s * 0.20 - pad, x + s * 0.95 + pad, base + pad),
|
||||||
|
radius=int(s * 0.1), fill=colour)
|
||||||
|
|
||||||
|
|
||||||
|
def _sun(d: ImageDraw.ImageDraw, cx: float, cy: float, r: float, s: float) -> None:
|
||||||
|
d.ellipse((cx - r, cy - r, cx + r, cy + r), fill=INK)
|
||||||
|
for dx, dy in ((0, -1), (0, 1), (-1, 0), (1, 0), (-.7, -.7), (.7, -.7), (-.7, .7), (.7, .7)):
|
||||||
|
d.line((cx + dx * r * 1.35, cy + dy * r * 1.35, cx + dx * r * 1.8, cy + dy * r * 1.8),
|
||||||
|
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:
|
||||||
|
w = max(2, int(s / 16))
|
||||||
|
if icon is Icon.SUN:
|
||||||
|
_sun(d, x + s / 2, y + s / 2, s * 0.22, s)
|
||||||
|
elif icon is Icon.PARTLY:
|
||||||
|
_sun(d, x + s * 0.36, y + s * 0.36, s * 0.2, s)
|
||||||
|
_cloud(d, x, y + s * 0.82, s, outline=True)
|
||||||
|
elif icon is Icon.CLOUDY:
|
||||||
|
_cloud(d, x, y + s * 0.75, s)
|
||||||
|
elif icon is Icon.RAIN:
|
||||||
|
_cloud(d, x, y + s * 0.6, s)
|
||||||
|
for i in range(3):
|
||||||
|
dx = x + s * (0.3 + 0.2 * i)
|
||||||
|
d.line((dx + 4, y + s * 0.68, dx - 2, y + s * 0.92), fill=INK, width=w)
|
||||||
|
elif icon is Icon.SNOW:
|
||||||
|
_cloud(d, x, y + s * 0.6, s)
|
||||||
|
for i in range(3):
|
||||||
|
dx, dy = x + s * (0.3 + 0.2 * i), y + s * (0.8 if i % 2 == 0 else 0.9)
|
||||||
|
d.rectangle((dx - 2, dy - 2, dx + 2, dy + 2), fill=INK)
|
||||||
|
elif icon is Icon.STORM:
|
||||||
|
_cloud(d, x, y + s * 0.6, s)
|
||||||
|
bolt = [(x + s * 0.52, y + s * 0.62), (x + s * 0.40, y + s * 0.80), (x + s * 0.50, y + s * 0.80),
|
||||||
|
(x + s * 0.44, y + s * 0.98), (x + s * 0.62, y + s * 0.74), (x + s * 0.52, y + s * 0.74)]
|
||||||
|
d.polygon(bolt, fill=INK)
|
||||||
|
elif icon is Icon.FOG:
|
||||||
|
for i in range(4):
|
||||||
|
off = s * 0.08 if i % 2 else 0
|
||||||
|
yy = y + s * (0.25 + 0.17 * i)
|
||||||
|
d.line((x + s * 0.12 + off, yy, x + s * 0.88 + off, yy), fill=INK, width=w + 1)
|
||||||
|
|
||||||
|
|
||||||
|
class WeatherView:
|
||||||
|
name = "weather"
|
||||||
|
STALE_AFTER = 3600.0 # seconds without a successful fetch before the data is marked old
|
||||||
|
|
||||||
|
def __init__(self, poller: Poller[Weather]) -> None:
|
||||||
|
self._poller = poller
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
self._poller.start()
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
self._poller.stop()
|
||||||
|
|
||||||
|
def _is_stale(self) -> bool:
|
||||||
|
age = self._poller.age()
|
||||||
|
return age is not None and age > self.STALE_AFTER
|
||||||
|
|
||||||
|
def frame_key(self, now: datetime):
|
||||||
|
return (now.strftime("%Y%m%d%H%M"), self._poller.version, self._is_stale())
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _seconds(now: datetime) -> Image.Image:
|
||||||
|
x0, y0, x1, y1 = SECONDS_BOX
|
||||||
|
img = Image.new("RGB", (x1 - x0, y1 - y0), BG)
|
||||||
|
g = SECONDS_GEOMETRY
|
||||||
|
lcdkit.number(ImageDraw.Draw(img), f"{now.second:02d}", g["x"] - x0, g["y"] - y0, g["w"], g["h"],
|
||||||
|
g["t"], g["gap"])
|
||||||
|
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:
|
||||||
|
weather: Weather | None = self._poller.value
|
||||||
|
img = Image.new("RGB", (W, H), BG)
|
||||||
|
d = ImageDraw.Draw(img)
|
||||||
|
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)
|
||||||
|
self._week_strip(d, now, weather, f_small, f_tiny)
|
||||||
|
d.line((12, 100, W - 13, 100), fill=INK, width=2)
|
||||||
|
|
||||||
|
# time row: HH:MM, seconds and date, then the weather now
|
||||||
|
lcdkit.number(d, now.strftime("%H:%M"), 22, 108, 48, 82, 11, 8)
|
||||||
|
img.paste(self._seconds(now), SECONDS_BOX[:2])
|
||||||
|
lcdkit.number(d, now.strftime("%-d.%-m."), 292, 156, 13, 30, 4, 3, ghost=False)
|
||||||
|
d.line((376, 108, 376, 192), 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._rain_graph(d, weather, f_small, f_tiny)
|
||||||
|
if self._is_stale():
|
||||||
|
lcdkit.tag(d, (int(20 + d.textlength(RAIN_LABEL, font=f_tiny) + 8), 203), "STARÉ", f_tiny)
|
||||||
|
return lcdkit.night(img) if is_night(now, weather) else img
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _week_strip(d: ImageDraw.ImageDraw, now: datetime, weather: Weather | None, f_small, f_tiny) -> None:
|
||||||
|
"""Today and the next six days: name, icon, max and min. Today is inverted."""
|
||||||
|
by_date: dict = {day.date: day for day in (weather.days if weather else ())}
|
||||||
|
for i in range(7):
|
||||||
|
x0 = 12 + i * CELL
|
||||||
|
cx = x0 + CELL / 2
|
||||||
|
if i:
|
||||||
|
d.line((x0, 16, x0, 92), fill=GHOST, width=1)
|
||||||
|
else:
|
||||||
|
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
|
||||||
|
def _current_block(d: ImageDraw.ImageDraw, weather: Weather | None, f_small, f_mini) -> None:
|
||||||
|
temp = weather.temp if weather else None
|
||||||
|
text = lcdkit.fmt_temp(temp)
|
||||||
|
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, 388, 108, w, 38, 5, gap, ghost=False)
|
||||||
|
if temp is not None:
|
||||||
|
d.ellipse((end, 108, end + 10, 118), outline=INK, width=3)
|
||||||
|
if weather:
|
||||||
|
draw_icon(d, icon_for(weather.code), 380, 152, 40)
|
||||||
|
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)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _rain_graph(d: ImageDraw.ImageDraw, weather: Weather | None, f_small, f_tiny) -> None:
|
||||||
|
d.text((20, 206), RAIN_LABEL, font=f_tiny, fill=INK)
|
||||||
|
hours = weather.hours if weather else ()
|
||||||
|
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), 204), mm, font=f_small, fill=INK)
|
||||||
|
for i in range(12):
|
||||||
|
bx = GRAPH_X + i * GRAPH_PITCH
|
||||||
|
hour = hours[i] if i < len(hours) else None
|
||||||
|
lcdkit.v_bar(d, bx, GRAPH_BOTTOM, hour.rain_pct if hour else None, BAR_W, 11, 4, 1)
|
||||||
|
if hour is not None:
|
||||||
|
d.text((bx + BAR_W / 2, 301), f"{hour.time.hour:02d}", font=f_tiny, fill=INK, anchor="ms")
|
||||||
Reference in new issue
Block a user