Send each print as one job, queue web prints, and harden deploys
CI / test (3.10) (push) Failing after 56s
CI / test (3.12) (push) Failing after 42s
CI / test (3.13) (push) Failing after 47s

Render every print to a complete ESC/POS payload (reset, content, cut)
and send it once over a fresh connection. Only the connect is retried,
so a link that drops mid-job can no longer print a partial image followed
by a full one, and no text size leaks into the next job. Prints are
capped at about 1 m of paper: tall images shrink, over-long notes are
refused.

Replace the argparse/stdout plumbing with PrinterConfig, InvalidJob and
PrinterUnavailable, and one run_command() dispatcher shared by the CLI
and TUI. Status now really connects; before, escpos's lazy open meant
the web server always reported the printer ready. Rendering with the
TM-T20II profile makes QR centering take effect.

The web server validates and renders jobs in the request (400 on bad
input), queues them for a single worker and answers 202; the page
long-polls /api/jobs/{id}, so no request outlives nginx's proxy timeout
while its job still prints. Status reports busy instead of waiting, and
jobs are logged with the nginx user.

update.sh tests new commits in a scratch worktree before touching the
live clone, and rolls back if /healthz doesn't answer after the restart.
The unit runs from the venv, and the web server defaults to localhost.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-23 22:07:58 +01:00
co-authored by Claude Opus 5.5
parent 30d1b83817
commit 597bace442
10 changed files with 778 additions and 436 deletions
+253 -170
View File
@@ -12,6 +12,8 @@ import random
import subprocess
import sys
import textwrap
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import BinaryIO
@@ -47,12 +49,15 @@ DEFAULT_PRINTER_IP = _env_ip()
DEFAULT_PRINTER_PORT = _env_port()
USB_VENDOR_ID = 0x04B8
USB_PRODUCT_ID = 0x0202
PRINTER_PROFILE = "TM-T20II" # python-escpos profile; its 576px media width lets center= work
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
LINE_HEIGHT_DOTS = 30 # default line spacing (3.75 mm) at size 1
MAX_PRINT_HEIGHT_DOTS = 8000 # about 1 m of paper; longer jobs are shrunk or refused
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
DEFAULT_WEB_LISTEN = "127.0.0.1:8765" # deployments set RECEIPT_WEB_LISTEN to their Tailscale IP
BASE_DIR = Path(__file__).resolve().parent
IMG_DIR = BASE_DIR / "img"
@@ -67,20 +72,56 @@ PRINTABLE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}
Image.MAX_IMAGE_PIXELS = 32_000_000
def setup_network(args: argparse.Namespace | None = None) -> None:
"""Bring up the printer's network interface via the connect script."""
env = os.environ.copy()
if args and not getattr(args, "usb", False):
env["RECEIPT_PRINTER_IP"] = args.ip
env["RECEIPT_PRINTER_PORT"] = str(args.port)
subprocess.run(["bash", str(CONNECT_SCRIPT)], env=env, check=True) # noqa: S603, S607
class InvalidJob(Exception):
"""The job itself can't be printed (nothing to print, too long, not an image)."""
def setup_network_quiet(args: argparse.Namespace) -> None:
"""Run the connect script with output captured, so callers can redirect it (TUI, web)."""
class PrinterUnavailable(Exception):
"""The printer couldn't be reached, or the link dropped during a job."""
@dataclass(frozen=True)
class PrinterConfig:
"""How to reach the printer; built from the CLI's global options."""
ip: str = DEFAULT_PRINTER_IP
port: int = DEFAULT_PRINTER_PORT
usb: bool = False
no_setup: bool = False
quiet_setup: bool = False # capture the connect script's output (TUI); no sudo prompt
@classmethod
def from_args(cls, args: argparse.Namespace) -> PrinterConfig:
return cls(
ip=getattr(args, "ip", DEFAULT_PRINTER_IP),
port=getattr(args, "port", DEFAULT_PRINTER_PORT),
usb=getattr(args, "usb", False),
no_setup=getattr(args, "no_setup", False),
quiet_setup=getattr(args, "quiet_setup", False),
)
@property
def needs_setup(self) -> bool:
"""Ethernet needs the connect script, unless no_setup says the link is already up."""
return not self.usb and not self.no_setup
@property
def target(self) -> str:
return "USB" if self.usb else f"{self.ip}:{self.port}"
def setup_network(config: PrinterConfig) -> None:
"""Bring up the printer's network interface via the connect script.
With quiet_setup the output is captured and re-printed, so callers that
redirect stdout (the TUI) see it instead of it landing on the terminal.
"""
env = os.environ.copy()
env["RECEIPT_PRINTER_IP"] = args.ip
env["RECEIPT_PRINTER_PORT"] = str(args.port)
env["RECEIPT_PRINTER_IP"] = config.ip
env["RECEIPT_PRINTER_PORT"] = str(config.port)
if not config.quiet_setup:
subprocess.run(["bash", str(CONNECT_SCRIPT)], env=env, check=True) # noqa: S603, S607
return
bash_path = str(CONNECT_SCRIPT) # noqa: S607 - fixed project script
result = subprocess.run( # noqa: S603
["/bin/bash", bash_path],
@@ -98,22 +139,74 @@ def setup_network_quiet(args: argparse.Namespace) -> None:
raise RuntimeError(f"connect script failed (exit {result.returncode})")
def needs_setup(args: argparse.Namespace) -> bool:
"""Ethernet needs the connect script, unless --no-setup says the link is already up."""
return not args.usb and not getattr(args, "no_setup", False)
def get_printer(args: argparse.Namespace) -> printer.Escpos:
if args.usb:
def get_printer(config: PrinterConfig) -> printer.Escpos:
if config.usb:
return printer.Usb(USB_VENDOR_ID, USB_PRODUCT_ID)
return printer.Network(args.ip, port=args.port)
return printer.Network(config.ip, port=config.port)
def close_quietly(p: printer.Escpos) -> None:
"""Close a printer handle, ignoring errors from an already-dead socket."""
with contextlib.suppress(Exception):
p.close()
def connect(config: PrinterConfig) -> printer.Escpos:
"""Open a printer connection, rerunning setup and retrying once on failure.
escpos connects lazily on first write, so open() is called here: a
connection failure must surface before any of a job's bytes are sent.
"""
for attempt in (1, 2):
try:
if config.needs_setup:
setup_network(config)
p = get_printer(config)
p.open()
return p
except (OSError, escpos_exceptions.Error, subprocess.SubprocessError, RuntimeError) as e:
if attempt == 2:
raise PrinterUnavailable(f"can't reach {config.target}: {e}") from e
print(f"Connect failed ({e}); retrying...", file=sys.stderr)
raise AssertionError("unreachable")
def send(config: PrinterConfig, payload: bytes) -> None:
"""Send one rendered job over a fresh connection.
Only the connect is retried. Once bytes have gone out, a failure is
reported rather than replayed, so a dropped link can't print a job twice.
"""
p = connect(config)
try:
p._raw(payload) # escpos's raw-write hook; the payload is already complete ESC/POS
except (OSError, escpos_exceptions.Error) as e:
raise PrinterUnavailable(
f"the link to {config.target} dropped mid-job, so it may have printed partially ({e})"
) from e
finally:
close_quietly(p)
def render(build: Callable[[printer.Escpos], None]) -> bytes:
"""Render a job to bytes: printer reset, the job, then a cut.
ESC @ comes first so no mode an earlier job left set (e.g. text size) leaks in.
"""
job = printer.Dummy(profile=PRINTER_PROFILE)
job.hw("INIT")
build(job)
job.cut()
return job.output
def prepare_for_print(img_path: Path | BinaryIO) -> Image.Image:
"""Load an image resized to full printer width and dithered for thermal output.
Transparency is composited onto white (thermal paper), then the image is
autocontrast-stretched and Floyd-Steinberg dithered to 1-bit.
autocontrast-stretched and Floyd-Steinberg dithered to 1-bit. An image that
would print taller than MAX_PRINT_HEIGHT_DOTS is shrunk to that height and
centered instead.
"""
with Image.open(img_path) as img:
img.load() # DecompressionBombError and truncated files surface here, inside `with`
@@ -122,9 +215,18 @@ def prepare_for_print(img_path: Path | BinaryIO) -> Image.Image:
background = Image.new("RGBA", rgba.size, "white")
img = Image.alpha_composite(background, rgba)
width, height = img.size
new_width = PRINT_WIDTH_PX
new_height = max(1, round(PRINT_WIDTH_PX * height / width))
resized = img.resize((PRINT_WIDTH_PX, new_height), Image.LANCZOS)
return ImageOps.autocontrast(resized.convert("L")).convert("1")
if new_height > MAX_PRINT_HEIGHT_DOTS:
new_width = max(1, round(MAX_PRINT_HEIGHT_DOTS * width / height))
new_height = MAX_PRINT_HEIGHT_DOTS
resized = img.resize((new_width, new_height), Image.LANCZOS)
gray = ImageOps.autocontrast(resized.convert("L"))
if new_width < PRINT_WIDTH_PX:
canvas = Image.new("L", (PRINT_WIDTH_PX, new_height), 255)
canvas.paste(gray, ((PRINT_WIDTH_PX - new_width) // 2, 0))
gray = canvas
return gray.convert("1")
def wrap_text(text: str, columns: int = TEXT_COLUMNS) -> str:
@@ -135,6 +237,55 @@ def wrap_text(text: str, columns: int = TEXT_COLUMNS) -> str:
return "\n".join(lines)
def render_note(text: str, timestamp: bool = False, size: int = 1) -> bytes:
if not text.strip():
raise InvalidJob("Nothing to print.")
lines = wrap_text(text, TEXT_COLUMNS // size).split("\n")
header_lines = 2 if timestamp else 0
if (len(lines) * size + header_lines) * LINE_HEIGHT_DOTS > MAX_PRINT_HEIGHT_DOTS:
max_lines = (MAX_PRINT_HEIGHT_DOTS // LINE_HEIGHT_DOTS - header_lines) // size
raise InvalidJob(
f"Note is too long: {len(lines)} lines at size {size}, the limit is {max_lines}."
)
def build(p: printer.Escpos) -> None:
if timestamp:
p.textln(datetime.now().strftime("%Y-%m-%d %H:%M"))
p.textln("-" * TEXT_COLUMNS)
if size > 1:
p.set(custom_size=True, width=size, height=size)
p.textln("\n".join(lines))
return render(build)
def render_image(source: Path | BinaryIO, caption: str | None = None) -> bytes:
try:
prepared = prepare_for_print(source)
except (OSError, SyntaxError, ValueError, Image.DecompressionBombError) as e:
raise InvalidJob(f"Not a printable image: {e}") from e
def build(p: printer.Escpos) -> None:
if caption:
p.textln(wrap_text(caption))
p.image(prepared, impl="bitImageColumn")
return render(build)
def render_qr(content: str, caption: str | None = None) -> bytes:
if not content:
raise InvalidJob("Nothing to encode.")
def build(p: printer.Escpos) -> None:
if caption:
p.textln(wrap_text(caption))
# Size 8 is the largest module size that reliably fits 576px with quiet zones.
p.qr(content, size=8, center=True)
return render(build)
def _printable(thread: dict) -> bool:
"""True when the thread's OP image is safe to cache and print.
@@ -208,35 +359,7 @@ def cached_images() -> list[Path]:
)
def close_quietly(p: printer.Escpos) -> None:
"""Close a printer handle, ignoring errors from an already-dead socket."""
with contextlib.suppress(Exception):
p.close()
def print_image(
p: printer.Escpos, img_path: Path | BinaryIO, args: argparse.Namespace
) -> printer.Escpos:
"""Print an image, reconnecting and retrying once if the printer drops.
Returns the (possibly reconnected) printer so the caller keeps a live handle.
"""
prepared = prepare_for_print(img_path)
try:
p.image(prepared, impl="bitImageColumn")
except (OSError, escpos_exceptions.Error) as e:
print(f"Print failed ({e}); reconnecting...", file=sys.stderr)
close_quietly(p)
if needs_setup(args):
setup_network(args)
p = get_printer(args)
# Record it so main() closes the live handle, not the one it opened.
args._printer = p
p.image(prepared, impl="bitImageColumn")
return p
def cmd_image(p: printer.Escpos, args: argparse.Namespace) -> int:
def cmd_image(config: PrinterConfig, args: argparse.Namespace) -> int:
printed = 0
for _ in range(args.count):
img = download_random_bant_image()
@@ -244,9 +367,12 @@ def cmd_image(p: printer.Escpos, args: argparse.Namespace) -> int:
# Keep going: one skipped image shouldn't discard the rest of the run.
print("No printable image found; skipping.", file=sys.stderr)
continue
p.textln(img.stem)
p = print_image(p, img, args)
p.cut()
try:
payload = render_image(img, caption=img.stem)
except InvalidJob as e:
print(f"Skipping {img.name}: {e}", file=sys.stderr)
continue
send(config, payload)
printed += 1
if printed == 0:
print("No images printed.", file=sys.stderr)
@@ -254,82 +380,50 @@ def cmd_image(p: printer.Escpos, args: argparse.Namespace) -> int:
return 0
def cmd_note(p: printer.Escpos, args: argparse.Namespace) -> int:
def cmd_note(config: PrinterConfig, args: argparse.Namespace) -> int:
text = args.text
if text is None or text == "-":
text = sys.stdin.read().rstrip("\n")
if not text:
print("Nothing to print.", file=sys.stderr)
return 1
if args.timestamp:
p.textln(datetime.now().strftime("%Y-%m-%d %H:%M"))
p.textln("-" * TEXT_COLUMNS)
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()
send(config, render_note(text, args.timestamp, getattr(args, "size", 1)))
return 0
def cmd_print(p: printer.Escpos, args: argparse.Namespace) -> int:
# `data` is an in-memory upload (web server); it is never written to disk.
def cmd_print(config: PrinterConfig, args: argparse.Namespace) -> int:
# `data` is in-memory image bytes; it is never written to disk.
data = getattr(args, "data", None)
if data is not None:
source: Path | BinaryIO = io.BytesIO(data)
elif args.path.is_file():
source = args.path
else:
print(f"File not found: {args.path}", file=sys.stderr)
return 1
if args.message:
p.textln(wrap_text(args.message))
p = print_image(p, source, args)
p.cut()
raise InvalidJob(f"File not found: {args.path}")
send(config, render_image(source, args.message))
return 0
def cmd_qr(p: printer.Escpos, args: argparse.Namespace) -> int:
if args.message:
p.textln(wrap_text(args.message))
# Size 8 is the largest module size that reliably fits 576px with quiet zones.
p.qr(args.content, size=8, center=True)
p.cut()
def cmd_qr(config: PrinterConfig, args: argparse.Namespace) -> int:
send(config, render_qr(args.content, args.message))
return 0
def cmd_reprint(p: printer.Escpos, args: argparse.Namespace) -> int:
def cmd_reprint(config: PrinterConfig, args: argparse.Namespace) -> int:
images = cached_images()
if not images:
print("Image cache is empty.", file=sys.stderr)
return 1
raise InvalidJob("Image cache is empty.")
if args.name:
matches = [f for f in images if f.name == args.name or f.stem == args.name]
if not matches:
print(f"No cached image named {args.name!r}. Try './receipt.py list'.", file=sys.stderr)
return 1
raise InvalidJob(f"No cached image named {args.name!r}. Try './receipt.py list'.")
target = matches[0]
else:
target = images[0]
p.textln(target.stem)
p = print_image(p, target, args)
p.cut()
send(config, render_image(target, caption=target.stem))
return 0
def cmd_status(args: argparse.Namespace) -> int:
try:
if needs_setup(args):
setup_network(args)
p = get_printer(args)
p.close()
except Exception as e:
print(f"Printer unreachable: {e}", file=sys.stderr)
return 1
target = "USB" if args.usb else f"{args.ip}:{args.port}"
print(f"Printer reachable ({target}).")
def cmd_status(config: PrinterConfig) -> int:
close_quietly(connect(config))
print(f"Printer reachable ({config.target}).")
return 0
@@ -377,52 +471,63 @@ def cmd_clean(yes: bool = False) -> int:
return 0
def run_action(command: str, base: argparse.Namespace, **params) -> tuple[int, str]:
"""Run a command handler, capturing its terminal output (used by the TUI and web server).
Mirrors main(): every action connects fresh, so a dropped printer never
leaves the caller holding a dead handle. redirect_stdout is process-global,
so concurrent callers must serialize.
"""
args = argparse.Namespace(**{**vars(base), **params, "command": command})
buf = io.StringIO()
with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
try:
rc = _dispatch(command, args)
except Exception as e:
print(f"Error: {e}")
rc = 1
return rc, buf.getvalue().rstrip()
PRINT_COMMANDS = {
"image": cmd_image,
"note": cmd_note,
"print": cmd_print,
"qr": cmd_qr,
"reprint": cmd_reprint,
}
def _dispatch(command: str, args: argparse.Namespace) -> int:
def run_command(command: str, args: argparse.Namespace) -> int:
"""Run one subcommand. InvalidJob, PrinterUnavailable and download errors propagate."""
if command == "list":
return cmd_list()
# No TTY to prompt on: the button press is the confirmation.
if command == "clean":
return cmd_clean(yes=True)
return cmd_clean(getattr(args, "yes", False))
config = PrinterConfig.from_args(args)
if command == "status":
if needs_setup(args):
setup_network_quiet(args)
# Already up; cmd_status must not rerun the script with uncaptured output.
args = argparse.Namespace(**{**vars(args), "no_setup": True})
return cmd_status(args)
if needs_setup(args):
setup_network_quiet(args)
handlers = {
"image": cmd_image,
"note": cmd_note,
"print": cmd_print,
"qr": cmd_qr,
"reprint": cmd_reprint,
}
p = get_printer(args)
# print_image() may reconnect and stash the new handle here; close whichever is live.
args._printer = p
try:
return handlers[command](p, args)
finally:
close_quietly(args._printer)
return cmd_status(config)
return PRINT_COMMANDS[command](config, args)
@dataclass(frozen=True)
class ActionResult:
rc: int
output: str
error: str | None = None # "invalid", "unavailable" or "failed" whenever rc != 0
def run_action(command: str, base: argparse.Namespace, **params) -> ActionResult:
"""Run a command with its terminal output captured (used by the TUI).
Every action connects fresh, so a dropped printer never leaves the caller
holding a dead handle. redirect_stdout is process-global, so concurrent
callers must serialize.
"""
# No TTY to prompt on: the button press is the confirmation.
defaults = {"yes": True} if command == "clean" else {}
args = argparse.Namespace(
**{**vars(base), **defaults, **params, "command": command, "quiet_setup": True}
)
buf = io.StringIO()
error = None
with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
try:
rc = run_command(command, args)
except InvalidJob as e:
print(e)
rc, error = 1, "invalid"
except PrinterUnavailable as e:
print(f"Printer unavailable: {e}")
rc, error = 1, "unavailable"
except Exception as e:
print(f"Error: {e}")
rc, error = 1, "failed"
if rc != 0 and error is None:
error = "failed"
return ActionResult(rc, buf.getvalue().rstrip(), error)
def _valid_ip(value: str) -> str:
@@ -556,43 +661,21 @@ def main() -> int:
)
return 1
return serve(args)
if args.command == "list":
return cmd_list()
if args.command == "clean":
return cmd_clean(args.yes)
if args.command == "status":
return cmd_status(args)
try:
if needs_setup(args):
setup_network(args)
p = get_printer(args)
except Exception as e:
print(f"Could not connect to printer: {e}", file=sys.stderr)
return run_command(args.command, args)
except InvalidJob as e:
print(e, file=sys.stderr)
return 1
except PrinterUnavailable as e:
print(f"Printer unavailable: {e}", file=sys.stderr)
return 1
commands = {
"image": cmd_image,
"note": cmd_note,
"print": cmd_print,
"qr": cmd_qr,
"reprint": cmd_reprint,
}
# print_image() may reconnect and stash the new handle on args; close whichever is live.
args._printer = p
try:
return commands[args.command](p, args)
except requests.RequestException as e:
print(f"Download failed: {e}", file=sys.stderr)
return 1
except KeyboardInterrupt:
print("Aborted.", file=sys.stderr)
return 130
except (OSError, escpos_exceptions.Error, Image.UnidentifiedImageError) as e:
print(f"Print failed: {e}", file=sys.stderr)
return 1
finally:
close_quietly(args._printer)
if __name__ == "__main__":