chore: import clock container, design spec and implementation plan

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
rickzkmandClaude Sonnet 5.5 committed 2026-10-07 00:17:55 +02:00
commit 817ed3a45f
11 files changed
+2151

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
.git
__pycache__/
*.pyc
.env
README.md
+3
View File
@@ -0,0 +1,3 @@
__pycache__/
*.pyc
.env
+22
View File
@@ -0,0 +1,22 @@
FROM python:3.12-slim
# Pinned commit of the Turing Smart Screen library (we only need library/ and the fonts).
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' '*/res/fonts' \
&& rm /tmp/lcd.tar.gz
ENV LCD_LIB_PATH=/opt/lcd \
PYTHONUNBUFFERED=1 \
TZ=Europe/Prague
COPY render.py clock.py ./
CMD ["python", "clock.py"]
+42
View File
@@ -0,0 +1,42 @@
# bus-department-schedule
Drives a 3.5" Turing Smart Screen (Rev A, 320x480, USB serial) from a Docker
container on the Coolify server. Goal: show local bus departures.
**Current stage: hardware smoke test.** `clock.py` draws a clock. Once it runs
on the server, it gets replaced by the departure board.
## Run on the server
Find a stable device path (survives replug/reboot, unlike `ttyACM0`):
ls -l /dev/serial/by-id/
Then, from this folder on the server:
SCREEN_DEVICE=/dev/serial/by-id/<your-device> docker compose up --build
In Coolify: new resource -> Docker Compose from the Gitea repo, and set
`SCREEN_DEVICE` in the environment variables.
## If the screen stays blank
1. `docker compose logs screen` - permission denied or "could not open port"?
2. ModemManager grabbing the port: `systemctl status ModemManager`. Fix with
`sudo systemctl disable --now ModemManager` (or a udev rule marking the
device `ID_MM_DEVICE_IGNORE=1`).
3. Wrong orientation: change `SCREEN_ORIENTATION` (PORTRAIT, REVERSE_PORTRAIT,
LANDSCAPE, REVERSE_LANDSCAPE).
4. Only one process can hold the port - make sure nothing else uses it.
## Config (env vars)
| Variable | Default | |
|---|---|---|
| `SCREEN_DEVICE` | `/dev/ttyACM0` | serial device, also passed into the container |
| `SCREEN_ORIENTATION` | `REVERSE_LANDSCAPE` | flip to `LANDSCAPE` if the picture is upside-down |
| `SCREEN_BRIGHTNESS` | `50` | 0-100 |
| `TZ` | `Europe/Prague` | clock timezone |
The screen library is pinned to one upstream commit in the `Dockerfile`
(`LCD_COMMIT`).
+67
View File
@@ -0,0 +1,67 @@
"""Clock face for the Turing Smart Screen, run as a container on the Coolify server.
Placeholder until the bus departure board replaces it. Drawing lives in render.py;
this file only owns the display and the update loop.
"""
import logging
import os
import signal
import sys
import time
from datetime import datetime
LIB = os.environ.get("LCD_LIB_PATH", "/opt/lcd")
sys.path.insert(0, LIB)
from PIL import Image # noqa: E402
import render # noqa: E402
from library.lcd.lcd_comm import Orientation # noqa: E402
from library.lcd.lcd_comm_rev_a import LcdCommRevA # noqa: E402
# 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("clock")
DEVICE = os.environ.get("SCREEN_DEVICE", "AUTO")
ORIENTATION = Orientation[os.environ.get("SCREEN_ORIENTATION", "REVERSE_LANDSCAPE")]
BRIGHTNESS = int(os.environ.get("SCREEN_BRIGHTNESS", "50"))
def main() -> None:
log.info("Opening display on %s (%s)", DEVICE, ORIENTATION.name)
lcd = LcdCommRevA(com_port=DEVICE) if DEVICE != "AUTO" else LcdCommRevA()
lcd.InitializeComm()
lcd.SetOrientation(ORIENTATION)
lcd.SetBrightness(BRIGHTNESS)
fonts = render.load_fonts(LIB)
running = True
def stop(*_):
nonlocal running
running = False
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
lcd.DisplayPILImage(Image.new("RGB", (render.W, render.H), render.BG), 0, 0) # clear once
log.info("Display ready")
last_second = last_minute = None
while running:
now = datetime.now()
if now.second != last_second:
if now.minute != last_minute: # the digital panel only changes once a minute
lcd.DisplayPILImage(render.render_info(now, fonts), render.DIAL_W, 0)
last_minute = now.minute
lcd.DisplayPILImage(render.render_dial(now), 0, 0)
last_second = now.second
time.sleep(0.05)
lcd.closeSerial()
log.info("Stopped")
if __name__ == "__main__":
main()
+12
View File
@@ -0,0 +1,12 @@
services:
screen:
build: .
restart: unless-stopped
environment:
# Prefer the stable by-id path (see README); /dev/ttyACM0 can change after replug/reboot.
SCREEN_DEVICE: ${SCREEN_DEVICE:-/dev/ttyACM0}
SCREEN_ORIENTATION: REVERSE_LANDSCAPE
SCREEN_BRIGHTNESS: "50"
TZ: Europe/Prague
devices:
- "${SCREEN_DEVICE:-/dev/ttyACM0}:${SCREEN_DEVICE:-/dev/ttyACM0}"
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,149 @@
# Bus departure board — design
Date: 2026-10-06 · Status: draft for review
## Goal
Show the next bus/trolleybus departures from the two stops near home on the
3.5" Turing Smart Screen (320x480 panel used in 480x320 landscape), driven by a
Docker container on the Coolify home server. The screen is plugged into the
server over USB; this is already proven by the clock container.
**Success:** glancing at the screen answers "when is my next bus, from which
stop, which line?" with a minutes countdown, without touching anything.
## What the user said / decisions
- Stops: **Štípa,u potoka** and **Štípa,družstvo** (Zlín, operator DSZO).
- Lines and source pages (one page per line per stop, direction implied by the page):
| Line | Stop | Source page (DSZO) |
|---|---|---|
| 4 (trolleybus) | Štípa,u potoka | `/bank1/trolejbusy/04b_22.html` |
| 5 (trolleybus) | Štípa,u potoka | `/bank1/trolejbusy/05a_03.html` |
| 35 (bus) | Štípa,družstvo | `/bank1/autobusy/35b_06.html` |
| 36 (bus) | Štípa,družstvo | `/bank1/autobusy/36b_06.html` |
Pages are fetched as `https://www.dszo.cz/jr/workhtml.php?htmlfile=<base64 of path>&grafikon=<opaque>`;
the exact URLs the user supplied go into `lines.yaml` verbatim.
- **Scheduled times only.** No live delays needed.
- Display per departure: line number, stop name, departure time, minutes countdown.
The next departure additionally gets a large countdown.
## Assumptions (not confirmed by the user)
- Each supplied page is the direction the user wants; other directions are out of scope.
- Time zone Europe/Prague.
- The analog clock stays in the repo as a fallback view, not on the default screen.
## Screen layout
```
┌────────────────────────────────────────────┐
│ [4] Štípa,u potoka 23:52 │ header: next bus + small clock
│ ► 4 min odj. 23:56 │ big countdown
├────────────────────────────────────────────┤
│ [36] Štípa,družstvo 00:12 za 20 m │
│ [5] Štípa,u potoka 00:31 za 39 m │
│ [4] Štípa,u potoka 04:16 zítra │
│ [35] Štípa,družstvo 04:40 zítra │
└────────────────────────────────────────────┘
```
- Departures of both stops are merged into one list sorted by time.
- Top block: the very next departure; under one minute the countdown reads `teď`.
- Below: the following four departures. Departures on the next calendar day are
marked `zítra`, so the board is never empty after the last bus.
- Redraw once per minute on the minute boundary (no per-second motion needed).
- Visual style follows the clock: near-black background, one orange accent, Roboto,
Czech text.
## Components
One job per file; `schedule.py` and `timetable.py` have no screen or network side
effects in their pure functions so they are unit-testable.
| File | Responsibility | Depends on |
|---|---|---|
| `lines.yaml` | List of `{line, stop, url}` entries | — |
| `timetable.py` | Download a page, parse into a `Timetable` (columns + departures); disk cache read/write | requests/urllib, stdlib html parsing |
| `schedule.py` | Pick the applicable column for a date; `next_departures(timetables, now, n)` | `holidays` |
| `render.py` | Draw the analog clock face (exists; fallback view) | Pillow |
| `board.py` | Draw the departure board image | Pillow, `schedule.Upcoming` |
| `store.py` | Read `lines.yaml`, download + cache pages, staleness | `timetable.py` |
| `app.py` | Testable glue: local time, refresh timing, board-or-nothing | `schedule.py`, `board.py` |
| `main.py` (replaces `clock.py`) | Own the display and the update loop | all of the above |
### Data model
- `Departure`: `line`, `stop`, `time` (HH:MM), `mark` (footnote letter or None).
- `Timetable`: per source page, a list of **columns**, each with `label`,
`valid_from` (date), optional explicit `dates` (special days) and `day_kind`
(`workday` / `rest_day` / `special`), plus its departures.
### Parsing (timetable.py)
- The page is UTF-8 HTML. Departures are in `table.stop-timetable`: one row per hour
(`td.hour-cell`), one `td.minutes-cell` per column, minutes space-separated.
- Column headers give the kind and validity, e.g. `Pracovní dny / platnost od 1.10.2026`,
`Dny pracovního klidu / platnost od 3.10.2026`,
`Prac.dny–školní prázdniny / platnost 29.–30.10.2026, 23.12.2026`.
Date ranges and lists in the header are parsed into explicit dates.
- Footnote marks (`<span class="idx">v</span>`) are stored in `mark`. They describe
per-trip route variations (e.g. `v` = continues to depot), not cancellations, so
every departure is kept and marks are not displayed in v1.
- Parse result with **zero departures is treated as a failure**.
### Choosing the column (schedule.py)
For a given date:
1. If the date is in a `special` column's explicit dates → that column.
2. Else if it is a Saturday, Sunday or Czech state holiday → the `rest_day` column.
3. Else → the `workday` column.
Among columns of the same kind, use the one with the latest `valid_from <= date`;
if none yet applies, use the earliest. Steps 1–3 are the proposed default order
(special date beats holiday/weekend); the user writes and may change this function,
see "User-written code" below.
`next_departures` looks at today's selected column from `now`, and rolls into the
next day(s) until it has `n` entries, flagging those not on today's date.
## Data handling and errors
- Fetch on container start and daily at ~03:00 local time; cache raw HTML plus the
fetch timestamp in the `/data` Docker volume.
- Download fails or parse yields zero departures → keep the existing cache, log the
error, continue to show the board from cache.
- Cache older than 3 days, or no cache at all and no download → show a small
`jízdní řád zastaralý` marker on the board; with no data at all, fall back to the
clock face.
- A column whose `valid_from` lies in the future is used only from that date; this
covers timetable changes announced on the page.
- Pages are fetched politely: four requests a day, one User-Agent string identifying the project.
## Testing
- Save the four real pages as fixtures in `tests/fixtures/`.
- Unit tests: parser (counts, column labels, special dates, marks), column selection
(workday, Saturday, state holiday, special school-holiday date, validity switch),
`next_departures` (rollover past midnight, `zítra` flag, fewer than n today).
- Render tests generate PNG previews (committed preview of the board for review).
- On-device check on the server: container logs plus a photo of the screen.
## Out of scope (v1)
Live delays or vehicle positions, other directions or stops, showing footnote marks,
touch input, anything beyond the four listed pages.
## User-written code
`schedule.py: select_column(columns, date)` — the precedence rule above (special date
vs. holiday vs. weekend) is a small piece of real judgment; the user writes it
(about 8 lines) when we reach that step.
## Delivery
Deployed as a Docker Compose resource in Coolify from the Gitea repo, with the
`/data` volume and the screen device by its `/dev/serial/by-id/` path. The manual
copy in `~/bus-board-test` on the server is removed afterwards.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

+99
View File
@@ -0,0 +1,99 @@
"""Landscape clock face: analog dial on the left, digital time + date on the right.
Pure drawing code (Pillow only) so it can be previewed on any machine without the
screen: `render_frame(now, fonts)` returns the whole 480x320 image. The container
sends `render_dial` every second and `render_info` once a minute.
"""
import math
from datetime import datetime
from PIL import Image, ImageDraw, ImageFont
W, H = 480, 320
DIAL_W = 300 # dial region is (0, 0, DIAL_W, H); info panel is the rest
INFO_W = W - DIAL_W
BG = (9, 11, 16)
FACE = (17, 21, 30)
RING = (44, 52, 70)
TICK = (110, 120, 140)
TICK_HOUR = (232, 236, 245)
HAND = (240, 244, 250)
ACCENT = (255, 112, 67)
TEXT = (245, 247, 252)
TEXT_DIM = (140, 148, 165)
DAYS = ["Pondělí", "Úterý", "Středa", "Čtvrtek", "Pátek", "Sobota", "Neděle"]
MONTHS = ["ledna", "února", "března", "dubna", "května", "června",
"července", "srpna", "září", "října", "listopadu", "prosince"]
SS = 4 # supersampling factor for the dial (smooth edges on a 320x480 panel)
def load_fonts(lib: str) -> dict:
root = f"{lib}/res/fonts"
return {
"time": ImageFont.truetype(f"{root}/roboto/Roboto-Light.ttf", 56),
"weekday": ImageFont.truetype(f"{root}/roboto/Roboto-Medium.ttf", 24),
"date": ImageFont.truetype(f"{root}/roboto/Roboto-Regular.ttf", 28),
"year": ImageFont.truetype(f"{root}/roboto/Roboto-Light.ttf", 22),
}
def _polar(cx, cy, r, deg):
a = math.radians(deg)
return cx + r * math.sin(a), cy - r * math.cos(a)
def _hand(d, cx, cy, deg, length, tail, width, color):
x1, y1 = _polar(cx, cy, length, deg)
x0, y0 = _polar(cx, cy, -tail, deg)
d.line([(x0, y0), (x1, y1)], fill=color, width=width)
r = width / 2
for x, y in ((x0, y0), (x1, y1)): # round the ends
d.ellipse([x - r, y - r, x + r, y + r], fill=color)
def render_dial(now: datetime) -> Image.Image:
img = Image.new("RGB", (DIAL_W * SS, H * SS), BG)
d = ImageDraw.Draw(img)
cx, cy, R = 150 * SS, 160 * SS, 138 * SS
d.ellipse([cx - R, cy - R, cx + R, cy + R], fill=FACE, outline=RING, width=3 * SS)
for i in range(60):
hour = i % 5 == 0
r_out = R - 9 * SS
r_in = R - (26 if hour else 17) * SS
d.line([_polar(cx, cy, r_in, i * 6), _polar(cx, cy, r_out, i * 6)],
fill=TICK_HOUR if hour else TICK, width=(4 if hour else 2) * SS)
h, m, s = now.hour % 12, now.minute, now.second
_hand(d, cx, cy, (h + m / 60) * 30, 72 * SS, 0, 7 * SS, HAND)
_hand(d, cx, cy, (m + s / 60) * 6, 108 * SS, 0, 5 * SS, HAND)
_hand(d, cx, cy, s * 6, 118 * SS, 28 * SS, 2 * SS, ACCENT)
for r, color in ((9 * SS, ACCENT), (4 * SS, FACE)): # centre cap
d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=color)
return img.resize((DIAL_W, H), Image.LANCZOS)
def render_info(now: datetime, fonts: dict) -> Image.Image:
img = Image.new("RGB", (INFO_W, H), BG)
d = ImageDraw.Draw(img)
mid = INFO_W // 2 + 2
d.text((mid, 112), now.strftime("%H:%M"), font=fonts["time"], fill=TEXT, anchor="mm")
d.line([(mid - 28, 160), (mid + 28, 160)], fill=ACCENT, width=3)
d.text((mid, 192), DAYS[now.weekday()].upper(), font=fonts["weekday"], fill=ACCENT, anchor="mm")
d.text((mid, 230), f"{now.day}. {MONTHS[now.month - 1]}", font=fonts["date"], fill=TEXT, anchor="mm")
d.text((mid, 262), str(now.year), font=fonts["year"], fill=TEXT_DIM, anchor="mm")
return img
def render_frame(now: datetime, fonts: dict) -> Image.Image:
frame = Image.new("RGB", (W, H), BG)
frame.paste(render_dial(now), (0, 0))
frame.paste(render_info(now, fonts), (DIAL_W, 0))
return frame
+3
View File
@@ -0,0 +1,3 @@
pyserial~=3.5
Pillow>=11.0
numpy>=2.0