From 30d1b83817d7c4fc32aec810ae7961db714c4a9a Mon Sep 17 00:00:00 2001 From: Adam French Date: Fri, 23 Oct 2026 21:48:54 +0100 Subject: [PATCH] Add a note text size option; document the printer cabled to stppi - note --size 1|2|3 magnifies the text and wraps to 48/24/16 columns, then resets the printer to normal size - Web page gets a Size menu defaulting to Large; the API validates it - README/CLAUDE.md: the printer has no Wi-Fi (UB-E04 needs an adapter), so it is cabled to stppi's eth0 at 192.168.192.168 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- README.md | 11 ++++++----- receipt.py | 20 +++++++++++++++++--- receipt_web.py | 18 ++++++++++++++---- tests/conftest.py | 3 +++ tests/test_receipt.py | 15 ++++++++++++++- tests/test_web.py | 15 +++++++++++++++ 7 files changed, 70 insertions(+), 14 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index a6bdc4d..f8f9fb6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,7 +6,7 @@ CLI that prints images, notes, and QR codes to an Epson TM-T20II thermal receipt - `receipt.py` — the CLI; subcommand per `cmd_*` function - `receipt_tui.py` — Textual TUI (`tui` subcommand); thin layer over the `cmd_*` handlers via `receipt.run_action()`, which connects fresh per action and captures stdout/stderr for the log panel. `textual` is an optional dependency (`[tui]` extra); the CLI works without it -- `receipt_web.py` — FastAPI server (`serve` subcommand, `[web]` extra) behind the site's nginx `/receipt/` over Tailscale; requires the `X-Receipt-Token` header nginx adds, and `X-Requested-With: receipt` on POSTs. Serializes jobs with a lock around `run_action()`; uploads print from memory. Always runs with `no_setup` (no sudo; the printer must already be reachable). Deployed on stppi, which reaches the printer on the home Wi-Fi (192.168.178.250) +- `receipt_web.py` — FastAPI server (`serve` subcommand, `[web]` extra) behind the site's nginx `/receipt/` over Tailscale; requires the `X-Receipt-Token` header nginx adds, and `X-Requested-With: receipt` on POSTs. Serializes jobs with a lock around `run_action()`; uploads print from memory. Always runs with `no_setup` (no sudo; the printer must already be reachable). Deployed on stppi, which is online over Wi-Fi and has the printer cabled to its `eth0` (printer 192.168.192.168, Pi 192.168.192.10 via the `receipt-printer` nmcli profile) - `deploy/` — systemd user units; `update.sh` (run by `receipt-update.timer`) fast-forwards the server's clone from Gitea, runs the tests, and restarts `receipt-web`, rolling back if they fail. Pushing to Gitea `master` is the deploy - `connect_receipt.sh` — brings up the printer's network interface (needs sudo); run automatically before any print over Ethernet. The TUI runs it with output captured (`setup_network_quiet`) so it can't corrupt the screen - `tests/` — pytest suite; uses `FakePrinter` + mocked `requests`, never touches hardware or network diff --git a/README.md b/README.md index 28be06d..be3c172 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ pip install python-escpos Pillow requests ./receipt.py note "your message here" fortune | ./receipt.py note ./receipt.py note -t "with a date/time header" +./receipt.py note --size 2 "bigger text" # 2x: 24 columns, 3x: 16 columns # Print a local image (with optional caption) ./receipt.py print path/to/image.jpg @@ -67,16 +68,16 @@ Images are prepared for thermal output automatically: transparency is composited ## Printing from the website -`./receipt.py serve` runs a small web server (`receipt_web.py`, needs `pip install '.[web]'`) with a page for printing a note or an uploaded image. It runs on stppi (the Raspberry Pi). The printer is on the home Wi-Fi at a fixed `192.168.178.250`, so the Pi reaches it over the LAN. The site's nginx on stpvm gates `https://www.adam-french.co.uk/receipt/` on the admin login, then forwards over Tailscale to this server and adds an `X-Receipt-Token` header. The server answers nothing but `/healthz` without that token. +`./receipt.py serve` runs a small web server (`receipt_web.py`, needs `pip install '.[web]'`) with a page for printing a note or an uploaded image. It runs on stppi (the Raspberry Pi). The printer has no Wi-Fi (its UB-E04 interface needs an optional Epson wireless adapter), so it is cabled to the Pi's `eth0` at its default `192.168.192.168`; the Pi itself is online over Wi-Fi. The site's nginx on stpvm gates `https://www.adam-french.co.uk/receipt/` on the admin login, then forwards over Tailscale to this server and adds an `X-Receipt-Token` header. The server answers nothing but `/healthz` without that token. ``` -browser ─https─> nginx (stpvm, admin auth_request) ─Tailscale─> receipt serve (stppi:8765) ─LAN─> printer +browser ─https─> nginx (stpvm, admin auth_request) ─Tailscale─> receipt serve (stppi:8765) ─eth0─> printer ``` -`serve` never runs the sudo connect script (`--no-setup` does the same for other commands), so the printer must already be reachable. On Wi-Fi it is. A printer cabled to the server's own Ethernet port instead needs a permanent address on that port: +`serve` never runs the sudo connect script (`--no-setup` does the same for other commands), so the printer must already be reachable. The printer doesn't hand out addresses, so the port it is cabled to needs a permanent one: ```bash -sudo nmcli con add type ethernet ifname con-name receipt-printer \ +sudo nmcli con add type ethernet ifname eth0 con-name receipt-printer connection.autoconnect-priority 10 \ ipv4.method manual ipv4.addresses 192.168.192.10/24 ipv4.never-default yes ipv6.method disabled ``` @@ -93,7 +94,7 @@ sudo nmcli con add type ethernet ifname con-name receipt-printer \ 2. Create the settings file. Put the same token in the web_server `.env` as `RECEIPT_WEB_TOKEN`: ```bash - (umask 077; printf 'RECEIPT_WEB_TOKEN=%s\nRECEIPT_WEB_LISTEN=%s:8765\nRECEIPT_PRINTER_IP=192.168.178.250\n' \ + (umask 077; printf 'RECEIPT_WEB_TOKEN=%s\nRECEIPT_WEB_LISTEN=%s:8765\nRECEIPT_PRINTER_IP=192.168.192.168\n' \ "$(openssl rand -hex 32)" "$(tailscale ip -4)" > ~/.config/receipt-web.env) ``` diff --git a/receipt.py b/receipt.py index 46ea36a..ed0d19f 100755 --- a/receipt.py +++ b/receipt.py @@ -49,6 +49,7 @@ USB_VENDOR_ID = 0x04B8 USB_PRODUCT_ID = 0x0202 PRINT_WIDTH_PX = 576 # printable width of the TM-T20II at 203 dpi TEXT_COLUMNS = 48 # font A columns on 80mm paper +TEXT_SIZES = (1, 2, 3) # note character magnifications; columns shrink to match HTTP_TIMEOUT = 15 # seconds MAX_IMAGE_BYTES = 16 * 1024 * 1024 # cap on a single downloaded or uploaded image DEFAULT_WEB_LISTEN = "100.107.152.119:8765" # stppi's Tailscale IP; nginx on stpvm proxies here @@ -126,11 +127,11 @@ def prepare_for_print(img_path: Path | BinaryIO) -> Image.Image: return ImageOps.autocontrast(resized.convert("L")).convert("1") -def wrap_text(text: str) -> str: +def wrap_text(text: str, columns: int = TEXT_COLUMNS) -> str: """Word-wrap text to the printer's column width, preserving blank lines.""" lines = [] for line in text.splitlines(): - lines.append(textwrap.fill(line, TEXT_COLUMNS) if line.strip() else "") + lines.append(textwrap.fill(line, columns) if line.strip() else "") return "\n".join(lines) @@ -263,7 +264,12 @@ def cmd_note(p: printer.Escpos, args: argparse.Namespace) -> int: if args.timestamp: p.textln(datetime.now().strftime("%Y-%m-%d %H:%M")) p.textln("-" * TEXT_COLUMNS) - p.textln(wrap_text(text)) + size = getattr(args, "size", 1) + if size > 1: + p.set(custom_size=True, width=size, height=size) + p.textln(wrap_text(text, TEXT_COLUMNS // size)) + if size > 1: + p.set(normal_textsize=True) # the mode outlives this connection p.cut() return 0 @@ -483,6 +489,14 @@ def build_parser() -> argparse.ArgumentParser: action="store_true", help="Print a date/time header above the note", ) + note_p.add_argument( + "-s", + "--size", + type=int, + choices=TEXT_SIZES, + default=1, + help="Text magnification (default: 1, 48 columns; 2 is 24, 3 is 16)", + ) print_p = subparsers.add_parser("print", help="Print a local image") print_p.add_argument("path", type=Path, help="Path to the image file") diff --git a/receipt_web.py b/receipt_web.py index 7a0eac5..1b31a11 100644 --- a/receipt_web.py +++ b/receipt_web.py @@ -36,6 +36,7 @@ CSRF_HEADER_VALUE = "receipt" class Note(BaseModel): text: str = Field(min_length=1, max_length=MAX_NOTE_CHARS) timestamp: bool = False + size: int = Field(default=1, ge=min(receipt.TEXT_SIZES), le=max(receipt.TEXT_SIZES)) def create_app(base: argparse.Namespace, token: str) -> FastAPI: @@ -78,7 +79,7 @@ def create_app(base: argparse.Namespace, token: str) -> FastAPI: def note(body: Note) -> JSONResponse: if not body.text.strip(): raise HTTPException(400, "Nothing to print.") - return run("note", text=body.text, timestamp=body.timestamp) + return run("note", text=body.text, timestamp=body.timestamp, size=body.size) @app.post("/api/image", dependencies=posting) def image( @@ -152,10 +153,11 @@ PAGE = """ section { background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 16px; } - textarea, input[type=text] { + textarea, input[type=text], select { width: 100%; padding: 8px 10px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); font: inherit; } + select { width: auto; padding: 4px 6px; margin-left: 4px; } textarea { min-height: 140px; font-family: ui-monospace, monospace; resize: vertical; } .row { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-top: 10px; flex-wrap: wrap; } @@ -195,9 +197,16 @@ PAGE = """

Note

- +
+
@@ -275,7 +284,8 @@ $("note-form").addEventListener("submit", async (e) => { const ok = await submit(e.target, "api/note", { method: "POST", headers: {"Content-Type": "application/json"}, - body: JSON.stringify({text: $("note").value, timestamp: $("timestamp").checked}), + body: JSON.stringify({text: $("note").value, timestamp: $("timestamp").checked, + size: Number($("size").value)}), }); if (ok) $("note").value = ""; }); diff --git a/tests/conftest.py b/tests/conftest.py index 768cb64..c802576 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -18,6 +18,9 @@ class FakePrinter: def qr(self, content, **kwargs): self.calls.append(("qr", content)) + def set(self, **kwargs): + self.calls.append(("set", kwargs)) + def cut(self): self.calls.append(("cut", None)) diff --git a/tests/test_receipt.py b/tests/test_receipt.py index 861bbd5..fe9db6e 100644 --- a/tests/test_receipt.py +++ b/tests/test_receipt.py @@ -134,6 +134,16 @@ def test_cmd_note_wraps_and_cuts(): assert p.calls[-1] == ("cut", None) +def test_cmd_note_large_size_wraps_narrower_and_resets(): + p = FakePrinter() + rc = receipt.cmd_note(p, make_args(text="hello " * 20, size=2)) + + assert rc == 0 + assert p.calls[0] == ("set", {"custom_size": True, "width": 2, "height": 2}) + assert all(len(line) <= receipt.TEXT_COLUMNS // 2 for line in p.calls[1][1].split("\n")) + assert p.calls[2:] == [("set", {"normal_textsize": True}), ("cut", None)] + + def test_cmd_note_timestamp_header(): p = FakePrinter() rc = receipt.cmd_note(p, make_args(text="hi", timestamp=True)) @@ -214,7 +224,10 @@ def test_parser_handles_all_subcommands(): assert args.usb and args.text == "hello" and args.timestamp args = parser.parse_args(["note"]) - assert args.text is None # stdin mode + assert args.text is None and args.size == 1 # stdin mode + + args = parser.parse_args(["note", "big", "--size", "3"]) + assert args.size == 3 args = parser.parse_args(["--ip", "10.0.0.5", "--port", "9101", "status"]) assert args.ip == "10.0.0.5" and args.port == 9101 diff --git a/tests/test_web.py b/tests/test_web.py index e2ecf7c..3432241 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -76,6 +76,21 @@ def test_note_prints(client, fake_printer): assert fake_printer.calls[-2:] == [("cut", None), ("close", None)] +def test_note_size(client, fake_printer): + res = client.post("/api/note", headers=HEADERS, json={"text": "hello", "size": 3}) + + assert res.status_code == 200 + assert ("set", {"custom_size": True, "width": 3, "height": 3}) in fake_printer.calls + + +@pytest.mark.parametrize("size", [0, 4]) +def test_note_rejects_bad_size(client, fake_printer, size): + res = client.post("/api/note", headers=HEADERS, json={"text": "hi", "size": size}) + + assert res.status_code == 422 + assert fake_printer.calls == [] + + @pytest.mark.parametrize("text", ["", " ", "x" * (receipt_web.MAX_NOTE_CHARS + 1)]) def test_note_rejects_empty_and_long(client, fake_printer, text): res = client.post("/api/note", headers=HEADERS, json={"text": text})