Compare commits
10
Commits
afd649acc5
...
abe6e9236b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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,87 @@
|
|||||||
|
# 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**, drawn in the style of a
|
||||||
|
Casio digital watch (slanted 7-segment digits, pale LCD green):
|
||||||
|
|
||||||
|
| `VIEW` | Shows |
|
||||||
|
|---|---|
|
||||||
|
| `weather` | Czech weekday strip, big `HH:MM` with seconds, date, current weather for Zlín, today's max/min, highest rain chance and a 12-hour rain probability bar graph with the total mm |
|
||||||
|
| `server` | CPU / RAM / disk bars, load, CPU temperature, uptime, Docker containers (readable names and status) and the busiest processes |
|
||||||
|
|
||||||
|
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, `git push`, press **Deploy** in Coolify. 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 and server.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, `git push`, press **Deploy** (no webhook).
|
||||||
|
- **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 older than 1 h, server stats older than 30 s). 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` or `server` |
|
||||||
|
| `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.
|
||||||
|
- The weather graph is the next 12 hours from now, so late in the day it runs into tomorrow.
|
||||||
|
- 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.
|
||||||
|
- Seconds are redrawn once per second with a small partial update.
|
||||||
@@ -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,23 @@
|
|||||||
|
services:
|
||||||
|
second-screen:
|
||||||
|
build: .
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
# Which view to show: weather | server. To switch: edit, commit, push, press Deploy in Coolify.
|
||||||
|
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: 64 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 31 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`
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
"""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
|
||||||
|
|
||||||
|
from PIL import 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
|
||||||
|
|
||||||
|
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 _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,82 @@
|
|||||||
|
"""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) -> None:
|
||||||
|
self._fetch = fetch
|
||||||
|
self._interval = interval
|
||||||
|
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 _loop(self) -> None:
|
||||||
|
while not self._stop.is_set():
|
||||||
|
ok = self.poll_once()
|
||||||
|
self._stop.wait(self._interval if ok else min(self._interval, MAX_RETRY_S))
|
||||||
+90
@@ -0,0 +1,90 @@
|
|||||||
|
"""Render every view with fake data to docs/previews/*.png (no screen, no network needed)."""
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from lcdkit import H, W
|
||||||
|
from weather_data import 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"
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
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))
|
||||||
|
return Weather(temp=temp, code=code, today_max=16.0, today_min=7.0, 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()),
|
||||||
|
FakePoller(fake_weather(temp=-3.4, rain=(100,) * 12, code=71)),
|
||||||
|
FakePoller(None, age=None),
|
||||||
|
FakePoller(fake_weather(code=95), age=7200.0),
|
||||||
|
]
|
||||||
|
return sheet([WeatherView(p).render(NOW) for p 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 main() -> None:
|
||||||
|
OUT.mkdir(parents=True, exist_ok=True)
|
||||||
|
for name, image in (("weather", weather_previews()), ("server", server_previews())):
|
||||||
|
image.save(OUT / f"{name}.png")
|
||||||
|
print(OUT / f"{name}.png")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
[pytest]
|
||||||
|
pythonpath = .
|
||||||
|
testpaths = tests
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
"""The views the container can show, selected by the VIEW env var."""
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
from poller import Poller
|
||||||
|
from server_view import ServerView
|
||||||
|
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 = 5
|
||||||
|
|
||||||
|
|
||||||
|
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))
|
||||||
|
|
||||||
|
|
||||||
|
# To add a view: write the module, add one entry here, add a README line.
|
||||||
|
REGISTRY: dict[str, Callable[[], View]] = {
|
||||||
|
"weather": _weather,
|
||||||
|
"server": _server,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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,4 @@
|
|||||||
|
Pillow>=11.0
|
||||||
|
numpy>=2.0
|
||||||
|
pyserial~=3.5
|
||||||
|
requests>=2.32
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
"""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 view import View
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
TICK_S = 0.05
|
||||||
|
OPEN_RETRY_S = 30.0
|
||||||
|
|
||||||
|
|
||||||
|
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 run(view: View, lcd, *, now_fn: Callable[[], datetime], running: Callable[[], bool],
|
||||||
|
sleep: Callable[[float], None] = time.sleep, max_failures: int = 10) -> None:
|
||||||
|
last_key = None
|
||||||
|
last_second = None
|
||||||
|
failures = 0
|
||||||
|
while running():
|
||||||
|
now = now_fn()
|
||||||
|
try:
|
||||||
|
key = view.frame_key(now)
|
||||||
|
if key != last_key:
|
||||||
|
lcd.DisplayPILImage(view.render(now), 0, 0)
|
||||||
|
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)
|
||||||
|
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 everything on the next tick
|
||||||
|
if failures >= max_failures:
|
||||||
|
raise # let Docker restart the process and reopen the port
|
||||||
|
sleep(TICK_S)
|
||||||
+139
@@ -0,0 +1,139 @@
|
|||||||
|
"""Casio-style server stats: CPU/RAM/disk bars, load, temperature, uptime, containers, busiest processes."""
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
import lcdkit
|
||||||
|
from lcdkit import BG, H, INK, W
|
||||||
|
from poller import Poller
|
||||||
|
from stats_data import Container, Stats, status_label
|
||||||
|
from view import Patch
|
||||||
|
|
||||||
|
ATTENTION = ("UNHEALTHY", "RESTART", "EXITED")
|
||||||
|
CONTAINER_ROWS = 7
|
||||||
|
ROW_STEP, ROWS_TOP = 17, 184
|
||||||
|
DIGITS = dict(w=16, h=26, t=3, gap=5) # small segment digits used for all numbers
|
||||||
|
BAR_ROWS = (("CPU", "cpu_pct", 54), ("RAM", "mem_pct", 88), ("DISK", "disk_pct", 122))
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_uptime(seconds: float | None) -> str:
|
||||||
|
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"
|
||||||
|
|
||||||
|
|
||||||
|
def _fit(d: ImageDraw.ImageDraw, text: str, font, max_w: float) -> str:
|
||||||
|
if d.textlength(text, font=font) <= max_w:
|
||||||
|
return text
|
||||||
|
while text and d.textlength(text + "…", font=font) > max_w:
|
||||||
|
text = text[:-1]
|
||||||
|
return text + "…"
|
||||||
|
|
||||||
|
|
||||||
|
class ServerView:
|
||||||
|
name = "server"
|
||||||
|
STALE_AFTER = 30.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 (now.second // 5, 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 = Image.new("RGB", (W, H), BG)
|
||||||
|
d = ImageDraw.Draw(img)
|
||||||
|
f_small, f_tiny, f_row = lcdkit.load_font(15), lcdkit.load_font(12), lcdkit.load_font(14)
|
||||||
|
|
||||||
|
d.rectangle((6, 6, W - 7, H - 7), outline=INK, width=2)
|
||||||
|
self._header(d, stats, f_small, f_tiny)
|
||||||
|
d.line((12, 46, W - 13, 46), fill=INK, width=2)
|
||||||
|
self._bars(d, stats, f_small)
|
||||||
|
self._load_and_temp(d, stats, f_small, f_tiny)
|
||||||
|
d.line((12, 160, W - 13, 160), fill=INK, width=2)
|
||||||
|
self._docker(d, stats, f_tiny, f_row)
|
||||||
|
d.line((306, 168, 306, H - 14), fill=INK, width=2)
|
||||||
|
self._processes(d, stats, f_tiny, f_row)
|
||||||
|
return img
|
||||||
|
|
||||||
|
def _header(self, d, stats: Stats | None, f_small, f_tiny) -> None:
|
||||||
|
lcdkit.tag(d, (14, 14), "SERVER", f_small)
|
||||||
|
d.text((100, 16), f"UP {fmt_uptime(stats.uptime_s if stats else None)}", font=f_small, fill=INK)
|
||||||
|
if self._is_stale():
|
||||||
|
width = d.textbbox((0, 0), "STARÉ", font=f_tiny)[2] + 6
|
||||||
|
lcdkit.tag(d, (W - 14 - width, 17), "STARÉ", f_tiny)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _bars(d, stats: Stats | None, f_small) -> None:
|
||||||
|
for label, field, y in BAR_ROWS:
|
||||||
|
pct = getattr(stats, field) if stats else None
|
||||||
|
d.text((18, y + 3), label, font=f_small, fill=INK)
|
||||||
|
lcdkit.h_bar(d, 72, y, pct, 24, 16, 8, 2)
|
||||||
|
text = "--" if pct is None else str(round(pct))
|
||||||
|
x = lcdkit.number(d, text, 244, y - 1, **DIGITS, ghost=False)
|
||||||
|
if pct is not None:
|
||||||
|
d.text((x + 2, y + 6), "%", font=f_small, fill=INK)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _load_and_temp(d, stats: Stats | None, f_small, f_tiny) -> None:
|
||||||
|
load = stats.load if stats else None
|
||||||
|
d.text((336, 50), "LOAD", font=f_tiny, fill=INK)
|
||||||
|
lcdkit.number(d, f"{load[0]:.2f}" if load else "--", 336, 64, **DIGITS, ghost=False)
|
||||||
|
d.text((336, 96), f"{load[1]:.2f} {load[2]:.2f}" if load else "-- --", font=f_tiny, fill=INK)
|
||||||
|
temp = stats.temp_c if stats else None
|
||||||
|
x = lcdkit.number(d, lcdkit.fmt_temp(temp), 336, 116, **DIGITS, ghost=False)
|
||||||
|
d.text((x + 2, 126), "°C" if temp is not None else "", font=f_small, fill=INK)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _docker(d, stats: Stats | None, f_tiny, f_row) -> None:
|
||||||
|
containers = stats.containers if stats else None
|
||||||
|
if containers is None:
|
||||||
|
d.text((14, 166), "DOCKER", font=f_tiny, fill=INK)
|
||||||
|
d.text((22, 230), "NO DOCKER", font=lcdkit.load_font(18), fill=INK)
|
||||||
|
return
|
||||||
|
running = sum(1 for c in containers if c.state == "running")
|
||||||
|
d.text((14, 166), f"DOCKER {running}/{len(containers)}", font=f_tiny, fill=INK)
|
||||||
|
ordered = sorted(containers, key=lambda c: (status_label(c) not in ATTENTION, c.name))
|
||||||
|
shown = ordered if len(ordered) <= CONTAINER_ROWS else ordered[:CONTAINER_ROWS - 1]
|
||||||
|
for i, c in enumerate(shown):
|
||||||
|
ServerView._container_row(d, c, ROWS_TOP + i * ROW_STEP, f_tiny, f_row)
|
||||||
|
if len(shown) < len(ordered):
|
||||||
|
d.text((14, ROWS_TOP + len(shown) * ROW_STEP), f"+{len(ordered) - len(shown)}", font=f_row, fill=INK)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _container_row(d, c: Container, y: int, f_tiny, f_row) -> None:
|
||||||
|
label = status_label(c)
|
||||||
|
d.text((14, y), _fit(d, c.name, f_row, 170), font=f_row, fill=INK)
|
||||||
|
if label in ATTENTION:
|
||||||
|
width = d.textbbox((0, 0), label, font=f_tiny)[2] + 6
|
||||||
|
lcdkit.tag(d, (294 - width, y), label, f_tiny)
|
||||||
|
else:
|
||||||
|
d.text((294 - d.textlength(label, font=f_tiny), y + 2), label, font=f_tiny, fill=INK)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _processes(d, stats: Stats | None, f_tiny, f_row) -> None:
|
||||||
|
d.text((318, 166), "PROCESY", font=f_tiny, fill=INK)
|
||||||
|
for i, proc in enumerate(stats.procs if stats else ()):
|
||||||
|
y = ROWS_TOP + i * 22
|
||||||
|
pct = f"{proc.cpu_pct:.1f}%"
|
||||||
|
d.text((W - 16 - d.textlength(pct, font=f_row), y), pct, font=f_row, fill=INK)
|
||||||
|
d.text((318, y), _fit(d, proc.name, f_row, 80), font=f_row, fill=INK)
|
||||||
+240
@@ -0,0 +1,240 @@
|
|||||||
|
"""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
|
||||||
|
from collections import defaultdict
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
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:
|
||||||
|
def __init__(self, proc_root: str = "/host/proc", sys_root: str = "/host/sys", disk_path: str = "/host/root",
|
||||||
|
docker_sock: str = "/var/run/docker.sock", docker_timeout: float = 3.0) -> None:
|
||||||
|
self._proc = Path(proc_root)
|
||||||
|
self._sys = Path(sys_root)
|
||||||
|
self._disk = disk_path
|
||||||
|
self._sock = docker_sock
|
||||||
|
self._docker_timeout = docker_timeout
|
||||||
|
self._prev_cpu: tuple[int, int] | None = None
|
||||||
|
self._prev_ticks: dict[int, int] = {}
|
||||||
|
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_delta = None
|
||||||
|
cpu = None
|
||||||
|
try:
|
||||||
|
cur = parse_cpu_times((self._proc / "stat").read_text())
|
||||||
|
if self._prev_cpu is not None:
|
||||||
|
total_delta = cur[1] - self._prev_cpu[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._try("docker", lambda: list_containers(self._sock, self._docker_timeout)),
|
||||||
|
procs=self._try("processes", lambda: self._processes(total_delta), ()),
|
||||||
|
)
|
||||||
|
|
||||||
|
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_delta: int | None) -> tuple[Proc, ...]:
|
||||||
|
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._prev_ticks = self._prev_ticks, ticks
|
||||||
|
if not total_delta or total_delta <= 0 or not previous:
|
||||||
|
return ()
|
||||||
|
per_name: dict[str, float] = defaultdict(float)
|
||||||
|
for pid, t in ticks.items():
|
||||||
|
if pid in previous and t > previous[pid]:
|
||||||
|
per_name[names[pid]] += (t - previous[pid]) / total_delta * 100
|
||||||
|
ranked = sorted(per_name.items(), key=lambda kv: kv[1], reverse=True)[:TOP_PROCESSES]
|
||||||
|
return tuple(Proc(name, pct) for name, pct in ranked)
|
||||||
Whitespace-only changes.
@@ -0,0 +1,4 @@
|
|||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
+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
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
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())
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
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
|
||||||
@@ -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,83 @@
|
|||||||
|
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()
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
|
from registry import REGISTRY, UnknownView, make_view
|
||||||
|
|
||||||
|
|
||||||
|
def test_registry_has_both_views():
|
||||||
|
assert sorted(REGISTRY) == ["server", "weather"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_make_view_builds_named_views():
|
||||||
|
assert make_view("weather").name == "weather"
|
||||||
|
assert make_view("server").name == "server"
|
||||||
|
|
||||||
|
|
||||||
|
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 == ["server", "weather"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_make_view_empty_name_is_unknown():
|
||||||
|
with pytest.raises(UnknownView):
|
||||||
|
make_view("")
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
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):
|
||||||
|
self._keys = keys # callable(now) -> key
|
||||||
|
self._with_patch = with_patch
|
||||||
|
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 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 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_full_frame_when_key_changes():
|
||||||
|
lcd, view = FakeLcd(), StubView(lambda now: now.minute)
|
||||||
|
runner.run(view, lcd, now_fn=clock(T0, 60), running=ticks(3), sleep=lambda s: None)
|
||||||
|
assert [c[0] for c in lcd.calls] == [(480, 320)] * 3
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from PIL import ImageChops
|
||||||
|
|
||||||
|
from lcdkit import INK
|
||||||
|
from server_view import ServerView
|
||||||
|
from stats_data import Container, Proc, Stats
|
||||||
|
from tests.helpers import count_colour
|
||||||
|
|
||||||
|
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_changes_every_five_seconds():
|
||||||
|
v = view(stats())
|
||||||
|
assert v.frame_key(datetime(2026, 10, 22, 14, 32, 5)) == v.frame_key(datetime(2026, 10, 22, 14, 32, 9))
|
||||||
|
assert v.frame_key(datetime(2026, 10, 22, 14, 32, 9)) != v.frame_key(datetime(2026, 10, 22, 14, 32, 10))
|
||||||
|
|
||||||
|
|
||||||
|
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] <= 40
|
||||||
|
|
||||||
|
|
||||||
|
def test_bar_reflects_value():
|
||||||
|
idle = view(stats(cpu_pct=0.0)).render(NOW)
|
||||||
|
busy = view(stats(cpu_pct=100.0)).render(NOW)
|
||||||
|
box = (72, 54, 232, 78) # the CPU bar
|
||||||
|
assert count_colour(busy, INK, box) > count_colour(idle, INK, 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] >= 160 and bbox[2] <= 304 # 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
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
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()
|
||||||
|
outer = self
|
||||||
|
|
||||||
|
class Handler(socketserver.StreamRequestHandler):
|
||||||
|
def handle(self):
|
||||||
|
while self.rfile.readline() not in (b"\r\n", b""):
|
||||||
|
pass
|
||||||
|
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)
|
||||||
|
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):
|
||||||
|
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 == ()
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import copy
|
||||||
|
import json
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import weather_data
|
||||||
|
from weather_data import 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_today_max_min():
|
||||||
|
w = parse_weather(payload(), NOW)
|
||||||
|
assert (w.today_max, w.today_min) == (15.0, 6.0)
|
||||||
|
|
||||||
|
|
||||||
|
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.today_max, 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
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from PIL import ImageChops
|
||||||
|
|
||||||
|
from lcdkit import INK
|
||||||
|
from tests.helpers import count_colour
|
||||||
|
from view import Patch
|
||||||
|
from weather_data import Hour, Weather
|
||||||
|
from weather_view import WeatherView
|
||||||
|
|
||||||
|
NOW = datetime(2026, 10, 22, 12, 45, 8) # a Thursday
|
||||||
|
|
||||||
|
|
||||||
|
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 weather(temp=14.2, rain=(0, 0, 10, 20, 40, 70, 60, 50, 30, 20, 10, 0), code=2):
|
||||||
|
hours = tuple(Hour(datetime(2026, 10, 22, 12 + i, 0), p, 0.2) for i, p in enumerate(rain))
|
||||||
|
return Weather(temp=temp, code=code, today_max=16.0, today_min=7.0, hours=hours)
|
||||||
|
|
||||||
|
|
||||||
|
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 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 ImageChops.difference(region.convert("RGB"), patch.image.convert("RGB")).getbbox() is None
|
||||||
|
|
||||||
|
|
||||||
|
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 ImageChops.difference(a, b).getbbox() is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_weather_renders_without_error():
|
||||||
|
img = view(value=None, version=0, age=None).render(NOW)
|
||||||
|
assert img.size == (480, 320)
|
||||||
|
# weekday strip, 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] >= 160 and bbox[2] <= 204 and bbox[3] <= 186
|
||||||
|
|
||||||
|
|
||||||
|
def test_hundred_percent_fits():
|
||||||
|
rain = (100,) * 12
|
||||||
|
img = view(value=weather(rain=rain)).render(NOW)
|
||||||
|
box = ink_bbox(img, (14, 262, 204, 312))
|
||||||
|
assert box is not None and box[2] < 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_negative_temp_fits_and_draws_minus():
|
||||||
|
cold = view(value=weather(temp=-3.4)).render(NOW)
|
||||||
|
warm = view(value=weather(temp=3.4)).render(NOW)
|
||||||
|
cold_box = ink_bbox(cold, (84, 180, 204, 236))
|
||||||
|
assert cold_box is not None and cold_box[2] < 200
|
||||||
|
assert ImageChops.difference(cold.convert("RGB"), warm.convert("RGB")).getbbox() is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_sunday_inverts_last_weekday_cell():
|
||||||
|
sunday = datetime(2026, 10, 25, 9, 0, 0)
|
||||||
|
img = view(value=weather()).render(sunday)
|
||||||
|
assert img.getpixel((402 + 1, 15)) == INK # NE cell
|
||||||
|
assert img.getpixel((12 + 1, 15)) != INK # PO cell
|
||||||
|
|
||||||
|
|
||||||
|
def test_thursday_inverts_fourth_cell():
|
||||||
|
img = view(value=weather()).render(NOW)
|
||||||
|
assert img.getpixel((12 + 3 * 65 + 1, 15)) == INK # ČT
|
||||||
|
assert img.getpixel((12 + 1, 15)) != INK
|
||||||
|
|
||||||
|
|
||||||
|
def test_fewer_than_twelve_hours_still_renders():
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
||||||
|
def test_two_digit_negative_temps_stay_clear_of_the_divider():
|
||||||
|
for temp in (-10.4, -19.6):
|
||||||
|
img = view(value=weather(temp=temp)).render(NOW)
|
||||||
|
box = ink_bbox(img, (84, 180, 204, 236))
|
||||||
|
assert box is not None and box[2] < 200, temp
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
"""Wall-clock time independent of the container's own TZ."""
|
||||||
|
import os
|
||||||
|
from datetime import datetime
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
DEFAULT_TZ = "Europe/Prague"
|
||||||
|
|
||||||
|
|
||||||
|
def local_now(tz_name: str | None = None) -> datetime:
|
||||||
|
"""Naive wall-clock time in `tz_name` (default: env BOARD_TZ, else Europe/Prague)."""
|
||||||
|
name = tz_name or os.environ.get("BOARD_TZ", DEFAULT_TZ)
|
||||||
|
return datetime.now(ZoneInfo(name)).replace(tzinfo=None)
|
||||||
@@ -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)."""
|
||||||
+108
@@ -0,0 +1,108 @@
|
|||||||
|
"""Open-Meteo forecast for Zlín: fetching and parsing (no drawing)."""
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import 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 Weather:
|
||||||
|
temp: float | None
|
||||||
|
code: int | None
|
||||||
|
today_max: float | None
|
||||||
|
today_min: float | None
|
||||||
|
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 parse_weather(payload: dict, now: datetime) -> Weather:
|
||||||
|
current = payload.get("current") or {}
|
||||||
|
daily = payload.get("daily") or {}
|
||||||
|
hourly = payload.get("hourly") or {}
|
||||||
|
|
||||||
|
day = now.strftime("%Y-%m-%d")
|
||||||
|
days = daily.get("time") or []
|
||||||
|
d = days.index(day) if day in days else None
|
||||||
|
today_max = _at(daily.get("temperature_2m_max"), d) if d is not None else None
|
||||||
|
today_min = _at(daily.get("temperature_2m_min"), d) if d is not None else None
|
||||||
|
|
||||||
|
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"),
|
||||||
|
code=current.get("weather_code"),
|
||||||
|
today_max=today_max,
|
||||||
|
today_min=today_min,
|
||||||
|
hours=tuple(hours),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_weather(now: datetime, get=requests.get) -> Weather:
|
||||||
|
params = {
|
||||||
|
"latitude": LAT,
|
||||||
|
"longitude": LON,
|
||||||
|
"current": "temperature_2m,weather_code",
|
||||||
|
"hourly": "precipitation_probability,precipitation",
|
||||||
|
"daily": "temperature_2m_max,temperature_2m_min",
|
||||||
|
"timezone": TIMEZONE,
|
||||||
|
"forecast_days": 2,
|
||||||
|
}
|
||||||
|
response = get(URL, params=params, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
return parse_weather(response.json(), now)
|
||||||
+164
@@ -0,0 +1,164 @@
|
|||||||
|
"""Casio-style weather clock: time, date, current weather and a 12 hour rain forecast."""
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
import lcdkit
|
||||||
|
from lcdkit import BG, H, INK, W
|
||||||
|
from poller import Poller
|
||||||
|
from view import Patch
|
||||||
|
from weather_data import Icon, Weather, icon_for
|
||||||
|
|
||||||
|
WEEKDAYS = ["PO", "ÚT", "ST", "ČT", "PÁ", "SO", "NE"]
|
||||||
|
SECONDS_BOX = (370, 52, 466, 104) # region redrawn once per second
|
||||||
|
SECONDS_GEOMETRY = dict(x=378, y=58, w=24, h=42, t=6, gap=6)
|
||||||
|
GRAPH_X, GRAPH_PITCH, GRAPH_BOTTOM = 222, 21, 282
|
||||||
|
|
||||||
|
|
||||||
|
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 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())
|
||||||
|
|
||||||
|
def patch(self, now: datetime) -> Patch:
|
||||||
|
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 Patch(img, x0, y0)
|
||||||
|
|
||||||
|
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 = lcdkit.load_font(15), lcdkit.load_font(12)
|
||||||
|
|
||||||
|
d.rectangle((6, 6, W - 7, H - 7), outline=INK, width=2)
|
||||||
|
self._weekday_strip(d, now, f_small)
|
||||||
|
d.line((12, 46, W - 13, 46), fill=INK, width=2)
|
||||||
|
|
||||||
|
# time row: HH:MM, seconds and date on the right
|
||||||
|
lcdkit.number(d, now.strftime("%H:%M"), 24, 54, 54, 96, 12, 9)
|
||||||
|
x0, y0, _, _ = SECONDS_BOX
|
||||||
|
img.paste(self.patch(now).image, (x0, y0))
|
||||||
|
lcdkit.number(d, now.strftime("%-d.%-m."), 372, 112, 14, 34, 4, 4, ghost=False)
|
||||||
|
d.line((12, 160, W - 13, 160), fill=INK, width=2)
|
||||||
|
|
||||||
|
self._current_block(d, weather, f_small, f_tiny)
|
||||||
|
d.line((206, 168, 206, H - 14), fill=INK, width=2)
|
||||||
|
self._rain_graph(d, weather, f_small, f_tiny)
|
||||||
|
if self._is_stale():
|
||||||
|
label_w = d.textlength("ZLÍN NYNÍ", font=f_tiny)
|
||||||
|
lcdkit.tag(d, (int(22 + label_w + 8), 163), "STARÉ", f_tiny)
|
||||||
|
return img
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _weekday_strip(d: ImageDraw.ImageDraw, now: datetime, font) -> None:
|
||||||
|
cell = (W - 24) // 7
|
||||||
|
for i, name in enumerate(WEEKDAYS):
|
||||||
|
x0 = 12 + i * cell
|
||||||
|
colour = INK
|
||||||
|
if i == now.weekday():
|
||||||
|
d.rectangle((x0, 14, x0 + cell - 6, 38), fill=INK)
|
||||||
|
colour = BG
|
||||||
|
text_w = d.textlength(name, font=font)
|
||||||
|
d.text((x0 + (cell - 6 - text_w) / 2, 17), name, font=font, fill=colour)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _current_block(d: ImageDraw.ImageDraw, weather: Weather | None, f_small, f_tiny) -> None:
|
||||||
|
d.text((22, 166), "ZLÍN NYNÍ", font=f_tiny, fill=INK)
|
||||||
|
temp = weather.temp if weather else None
|
||||||
|
if weather:
|
||||||
|
draw_icon(d, icon_for(weather.code), 20, 182, 56)
|
||||||
|
text = lcdkit.fmt_temp(temp)
|
||||||
|
w, gap = (26, 7) if len(text) <= 2 else (22, 5) # a third glyph (-10) must stay clear of the divider
|
||||||
|
end = lcdkit.number(d, text, 90, 184, w, 46, 6, gap, ghost=False)
|
||||||
|
if temp is not None:
|
||||||
|
d.ellipse((end + 4, 184, end + 14, 194), outline=INK, width=3)
|
||||||
|
hi = lcdkit.fmt_temp(weather.today_max) if weather else "--"
|
||||||
|
lo = lcdkit.fmt_temp(weather.today_min) if weather else "--"
|
||||||
|
d.text((22, 244), f"MAX {hi}° MIN {lo}°", font=f_small, fill=INK)
|
||||||
|
|
||||||
|
d.text((22, 264), "DEŠŤ", font=f_tiny, fill=INK)
|
||||||
|
chances = [h.rain_pct for h in (weather.hours if weather else ()) if h.rain_pct is not None]
|
||||||
|
text = str(max(chances)) if chances else "--"
|
||||||
|
x = lcdkit.number(d, text, 22, 279, 18, 28, 4, 6, ghost=False)
|
||||||
|
if chances:
|
||||||
|
d.text((x + 4, 288), "%", font=f_small, fill=INK)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _rain_graph(d: ImageDraw.ImageDraw, weather: Weather | None, f_small, f_tiny) -> None:
|
||||||
|
d.text((220, 166), "DEŠŤ % / HOD", font=f_tiny, fill=INK)
|
||||||
|
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), 164), 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, 14, 16, 5, 1)
|
||||||
|
if hour is not None and i % 3 == 0:
|
||||||
|
label = f"{hour.time.hour:02d}"
|
||||||
|
d.text((bx + 7 - d.textlength(label, font=f_tiny) / 2, 290), label, font=f_tiny, fill=INK)
|
||||||
Reference in new issue
Block a user