Add a note text size option; document the printer cabled to stppi
CI / test (3.10) (push) Failing after 47s
CI / test (3.12) (push) Failing after 54s
CI / test (3.13) (push) Failing after 48s

- 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 <[email protected]>
This commit is contained in:
2026-10-23 21:48:54 +01:00
co-authored by Claude Opus 5.5
parent f55b20fb82
commit 30d1b83817
7 changed files with 70 additions and 14 deletions
+1 -1
View File
@@ -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.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_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 - `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 - `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 - `tests/` — pytest suite; uses `FakePrinter` + mocked `requests`, never touches hardware or network
+6 -5
View File
@@ -34,6 +34,7 @@ pip install python-escpos Pillow requests
./receipt.py note "your message here" ./receipt.py note "your message here"
fortune | ./receipt.py note fortune | ./receipt.py note
./receipt.py note -t "with a date/time header" ./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) # Print a local image (with optional caption)
./receipt.py print path/to/image.jpg ./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 ## 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 ```bash
sudo nmcli con add type ethernet ifname <port> 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 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 <port> con-name receipt-printer \
2. Create the settings file. Put the same token in the web_server `.env` as `RECEIPT_WEB_TOKEN`: 2. Create the settings file. Put the same token in the web_server `.env` as `RECEIPT_WEB_TOKEN`:
```bash ```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) "$(openssl rand -hex 32)" "$(tailscale ip -4)" > ~/.config/receipt-web.env)
``` ```
+17 -3
View File
@@ -49,6 +49,7 @@ USB_VENDOR_ID = 0x04B8
USB_PRODUCT_ID = 0x0202 USB_PRODUCT_ID = 0x0202
PRINT_WIDTH_PX = 576 # printable width of the TM-T20II at 203 dpi PRINT_WIDTH_PX = 576 # printable width of the TM-T20II at 203 dpi
TEXT_COLUMNS = 48 # font A columns on 80mm paper 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 HTTP_TIMEOUT = 15 # seconds
MAX_IMAGE_BYTES = 16 * 1024 * 1024 # cap on a single downloaded or uploaded image 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 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") 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.""" """Word-wrap text to the printer's column width, preserving blank lines."""
lines = [] lines = []
for line in text.splitlines(): 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) return "\n".join(lines)
@@ -263,7 +264,12 @@ def cmd_note(p: printer.Escpos, args: argparse.Namespace) -> int:
if args.timestamp: if args.timestamp:
p.textln(datetime.now().strftime("%Y-%m-%d %H:%M")) p.textln(datetime.now().strftime("%Y-%m-%d %H:%M"))
p.textln("-" * TEXT_COLUMNS) 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() p.cut()
return 0 return 0
@@ -483,6 +489,14 @@ def build_parser() -> argparse.ArgumentParser:
action="store_true", action="store_true",
help="Print a date/time header above the note", 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 = subparsers.add_parser("print", help="Print a local image")
print_p.add_argument("path", type=Path, help="Path to the image file") print_p.add_argument("path", type=Path, help="Path to the image file")
+14 -4
View File
@@ -36,6 +36,7 @@ CSRF_HEADER_VALUE = "receipt"
class Note(BaseModel): class Note(BaseModel):
text: str = Field(min_length=1, max_length=MAX_NOTE_CHARS) text: str = Field(min_length=1, max_length=MAX_NOTE_CHARS)
timestamp: bool = False 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: 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: def note(body: Note) -> JSONResponse:
if not body.text.strip(): if not body.text.strip():
raise HTTPException(400, "Nothing to print.") 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) @app.post("/api/image", dependencies=posting)
def image( def image(
@@ -152,10 +153,11 @@ PAGE = """<!doctype html>
section { section {
background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 16px; 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; width: 100%; padding: 8px 10px; border: 1px solid var(--border); border-radius: 6px;
background: var(--bg); color: var(--text); font: inherit; 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; } textarea { min-height: 140px; font-family: ui-monospace, monospace; resize: vertical; }
.row { display: flex; align-items: center; justify-content: space-between; gap: 12px; .row { display: flex; align-items: center; justify-content: space-between; gap: 12px;
margin-top: 10px; flex-wrap: wrap; } margin-top: 10px; flex-wrap: wrap; }
@@ -195,9 +197,16 @@ PAGE = """<!doctype html>
<section> <section>
<h2>Note</h2> <h2>Note</h2>
<form id="note-form"> <form id="note-form">
<textarea id="note" maxlength="4000" placeholder="Wrapped to 48 columns" required></textarea> <textarea id="note" maxlength="4000" placeholder="Your note" required></textarea>
<div class="row"> <div class="row">
<label class="muted"><input type="checkbox" id="timestamp"> Date/time header</label> <label class="muted"><input type="checkbox" id="timestamp"> Date/time header</label>
<label class="muted">Size
<select id="size">
<option value="1">Normal (48 per line)</option>
<option value="2" selected>Large (24 per line)</option>
<option value="3">Huge (16 per line)</option>
</select>
</label>
<button type="submit">Print note</button> <button type="submit">Print note</button>
</div> </div>
</form> </form>
@@ -275,7 +284,8 @@ $("note-form").addEventListener("submit", async (e) => {
const ok = await submit(e.target, "api/note", { const ok = await submit(e.target, "api/note", {
method: "POST", method: "POST",
headers: {"Content-Type": "application/json"}, 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 = ""; if (ok) $("note").value = "";
}); });
+3
View File
@@ -18,6 +18,9 @@ class FakePrinter:
def qr(self, content, **kwargs): def qr(self, content, **kwargs):
self.calls.append(("qr", content)) self.calls.append(("qr", content))
def set(self, **kwargs):
self.calls.append(("set", kwargs))
def cut(self): def cut(self):
self.calls.append(("cut", None)) self.calls.append(("cut", None))
+14 -1
View File
@@ -134,6 +134,16 @@ def test_cmd_note_wraps_and_cuts():
assert p.calls[-1] == ("cut", None) 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(): def test_cmd_note_timestamp_header():
p = FakePrinter() p = FakePrinter()
rc = receipt.cmd_note(p, make_args(text="hi", timestamp=True)) 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 assert args.usb and args.text == "hello" and args.timestamp
args = parser.parse_args(["note"]) 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"]) args = parser.parse_args(["--ip", "10.0.0.5", "--port", "9101", "status"])
assert args.ip == "10.0.0.5" and args.port == 9101 assert args.ip == "10.0.0.5" and args.port == 9101
+15
View File
@@ -76,6 +76,21 @@ def test_note_prints(client, fake_printer):
assert fake_printer.calls[-2:] == [("cut", None), ("close", None)] 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)]) @pytest.mark.parametrize("text", ["", " ", "x" * (receipt_web.MAX_NOTE_CHARS + 1)])
def test_note_rejects_empty_and_long(client, fake_printer, text): def test_note_rejects_empty_and_long(client, fake_printer, text):
res = client.post("/api/note", headers=HEADERS, json={"text": text}) res = client.post("/api/note", headers=HEADERS, json={"text": text})