agent-iot / modules /paper_printer /paper_print.py
ASown's picture
Consolidate project history under ASown
f368481
Raw History Blame Contribute Delete
9.59 kB
"""
Print to a network printer over IPP — WITH auto-discovery.
If no reachable printer is configured, the agent scans the local /24 subnet for
open printer ports (631 IPP, 9100 raw), confirms each candidate by asking it for
IPP attributes, picks a real printer (preferring Brother), remembers it in
printer.json, and prints. So it "finds and connects" on its own.
Env: PAPER_PRINTER_HOST (optional pin). Otherwise discovered + cached.
"""
from __future__ import annotations
import concurrent.futures
import io
import ipaddress
import json
import os
import socket
import struct
from pathlib import Path
from typing import Optional
import requests
from PIL import Image
CACHE_FILE = Path(__file__).resolve().parent / "printer.json"
PRINTER_HOST: Optional[str] = os.getenv("PAPER_PRINTER_HOST") or None
# ---- IPP encoding ----------------------------------------------------------
OP_ATTRS_TAG, END_TAG = 0x01, 0x03
T_INT, T_ENUM = 0x21, 0x23
T_CHARSET, T_LANG, T_URI, T_NAME, T_KEYWORD, T_MIME = 0x47, 0x48, 0x45, 0x42, 0x44, 0x49
def _attr(tag: int, name: str, value: str, first: bool = True) -> bytes:
nm = name.encode() if first else b""
val = value.encode()
return bytes([tag]) + struct.pack(">H", len(nm)) + nm + struct.pack(">H", len(val)) + val
def _op_header(op_id: int, req_id: int = 1) -> bytes:
return bytes([0x02, 0x00]) + struct.pack(">H", op_id) + struct.pack(">I", req_id)
def _base_op_attrs(host: str) -> bytes:
return (bytes([OP_ATTRS_TAG])
+ _attr(T_CHARSET, "attributes-charset", "utf-8")
+ _attr(T_LANG, "attributes-natural-language", "en")
+ _attr(T_URI, "printer-uri", f"ipp://{host}/ipp/print")
+ _attr(T_NAME, "requesting-user-name", "agent"))
def _post(host: str, body: bytes, timeout: int = 15) -> bytes:
r = requests.post(f"http://{host}/ipp/print", data=body,
headers={"Content-Type": "application/ipp"}, timeout=timeout)
r.raise_for_status()
return r.content
def _parse(resp: bytes) -> tuple[int, dict]:
status = int.from_bytes(resp[2:4], "big")
i, name, attrs = 8, None, {}
while i < len(resp):
tag = resp[i]; i += 1
if tag in (0x00, 0x01, 0x02, 0x03, 0x04, 0x05):
if tag == END_TAG:
break
continue
nlen = int.from_bytes(resp[i:i+2], "big"); i += 2
nm = resp[i:i+nlen].decode("utf-8", "replace"); i += nlen
vlen = int.from_bytes(resp[i:i+2], "big"); i += 2
val = resp[i:i+vlen]; i += vlen
if nlen > 0:
name = nm
v = int.from_bytes(val, "big") if tag in (T_INT, T_ENUM) else val.decode("utf-8", "replace")
attrs.setdefault(name, []).append(v)
return status, attrs
def get_attributes(host: str, timeout: int = 8) -> Optional[dict]:
"""Ask a host for IPP printer attributes. Returns dict, or None if it isn't
an IPP printer / unreachable."""
body = (_op_header(0x000B) + _base_op_attrs(host)
+ _attr(T_KEYWORD, "requested-attributes", "printer-make-and-model")
+ _attr(T_KEYWORD, "", "printer-state", first=False)
+ _attr(T_KEYWORD, "", "document-format-supported", first=False)
+ _attr(T_KEYWORD, "", "media-default", first=False)
+ bytes([END_TAG]))
try:
status, attrs = _parse(_post(host, body, timeout))
except Exception:
return None
if not attrs.get("document-format-supported"):
return None
return {"host": host, "ipp_status": hex(status),
"model": (attrs.get("printer-make-and-model") or ["?"])[0],
"state": (attrs.get("printer-state") or [None])[0],
"formats": attrs.get("document-format-supported"),
"media": (attrs.get("media-default") or [None])[0]}
# ---- discovery -------------------------------------------------------------
def local_ipv4() -> str:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
finally:
s.close()
def _port_open(host: str, port: int, timeout: float = 0.35) -> bool:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
try:
return s.connect_ex((host, port)) == 0
except Exception:
return False
finally:
s.close()
def scan_subnet(ports=(631, 9100), timeout: float = 0.35) -> list[str]:
"""Return IPs on the local /24 that have a printer port open."""
net = ipaddress.ip_network(local_ipv4() + "/24", strict=False)
hosts = [str(h) for h in net.hosts()]
found: set[str] = set()
with concurrent.futures.ThreadPoolExecutor(max_workers=128) as ex:
futs = {ex.submit(_port_open, h, p, timeout): h for h in hosts for p in ports}
for f in concurrent.futures.as_completed(futs):
if f.result():
found.add(futs[f])
return sorted(found, key=lambda x: int(x.split(".")[-1]))
def discover_printer() -> Optional[dict]:
"""Scan the LAN, confirm printers via IPP, prefer Brother. Returns info or None."""
candidates = scan_subnet()
printers = []
for ip in candidates:
info = get_attributes(ip)
if info:
printers.append(info)
if not printers:
return None
printers.sort(key=lambda p: 0 if "brother" in str(p["model"]).lower() else 1)
return printers[0]
def resolve_host(force: bool = False) -> str:
"""Return a reachable printer host: pinned env -> cache -> live discovery."""
global PRINTER_HOST
if not force and PRINTER_HOST and get_attributes(PRINTER_HOST):
return PRINTER_HOST
if not force and CACHE_FILE.exists():
try:
ip = json.loads(CACHE_FILE.read_text()).get("ip")
if ip and get_attributes(ip):
PRINTER_HOST = ip
return ip
except Exception:
pass
info = discover_printer()
if not info:
raise RuntimeError("No printer found on the network (scanned local /24).")
PRINTER_HOST = info["host"]
CACHE_FILE.write_text(json.dumps({"ip": info["host"], "model": info["model"]},
ensure_ascii=False, indent=2), encoding="utf-8")
return PRINTER_HOST
# ---- page building + printing ----------------------------------------------
def image_to_a4_jpeg(image_path: str, *, dpi: int = 150, margin_mm: float = 12,
width_mm: Optional[float] = None, height_mm: Optional[float] = None,
stretch: bool = False, align: str = "center") -> tuple[bytes, tuple[int, int], bool]:
"""Lay an image on a white A4 page -> (JPEG bytes, placed_mm, clamped)."""
W, H = int(210 / 25.4 * dpi), int(297 / 25.4 * dpi)
px = lambda mm: max(1, int(round(mm / 25.4 * dpi)))
req_w = px(width_mm) if width_mm else W - 2 * px(margin_mm)
req_h = px(height_mm) if height_mm else H - 2 * px(margin_mm)
boxw, boxh = min(req_w, W), min(req_h, H)
clamped = boxw < req_w or boxh < req_h
page = Image.new("RGB", (W, H), "white")
img = Image.open(image_path).convert("RGB")
if stretch and width_mm and height_mm:
img = img.resize((boxw, boxh))
else:
s = min(boxw / img.width, boxh / img.height)
img = img.resize((max(1, round(img.width * s)), max(1, round(img.height * s))))
x = (W - img.width) // 2
y = px(margin_mm) if align == "top" else (H - img.height - px(margin_mm) if align == "bottom" else (H - img.height) // 2)
page.paste(img, (x, y))
out = io.BytesIO()
page.save(out, "JPEG", quality=92, dpi=(dpi, dpi))
placed_mm = (round(img.width / dpi * 25.4), round(img.height / dpi * 25.4))
return out.getvalue(), placed_mm, clamped
def print_data(data: bytes, doc_format: str, job_name: str = "agent-job",
host: Optional[str] = None) -> dict:
host = host or resolve_host()
body = (_op_header(0x0002) + _base_op_attrs(host)
+ _attr(T_NAME, "job-name", job_name)
+ _attr(T_MIME, "document-format", doc_format)
+ bytes([END_TAG]) + data)
status, attrs = _parse(_post(host, body, timeout=60))
return {"printer": host, "ipp_status": hex(status), "ok": status < 0x0100,
"job-id": attrs.get("job-id"), "job-state": attrs.get("job-state")}
def print_image(image_path: str, **size_opts) -> dict:
host = resolve_host()
data, placed, clamped = image_to_a4_jpeg(image_path, **size_opts)
res = print_data(data, "image/jpeg", job_name=Path(image_path).stem, host=host)
res["placed_mm"] = f"{placed[0]}x{placed[1]}mm"
if clamped:
res["note"] = "requested size exceeded A4 (210x297mm) — clamped to sheet"
return res
if __name__ == "__main__":
import sys
cmd = sys.argv[1] if len(sys.argv) > 1 else ""
if cmd == "discover":
print("Scanning local network for printers...")
info = discover_printer()
if info:
CACHE_FILE.write_text(json.dumps({"ip": info["host"], "model": info["model"]},
ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps(info, indent=2, ensure_ascii=False))
else:
print("No printer found on the local subnet.")
elif cmd == "attrs":
print(json.dumps(get_attributes(resolve_host()), indent=2, ensure_ascii=False))
elif cmd:
print(json.dumps(print_image(cmd), indent=2, ensure_ascii=False))
else:
print("usage: paper_print.py discover | attrs | <image>")