"""Brother QL printer access through brother_ql (pyusb backend), serialized by a lock.""" from __future__ import annotations import logging import threading from pathlib import Path from typing import Any from PIL import Image from brother_ql.backends.helpers import send as bq_send from brother_ql.backends.helpers import status as bq_status from brother_ql.conversion import convert from brother_ql.raster import BrotherQLRaster from .config import Config from .label import find_label log = logging.getLogger("worker.printer") DIE_CUT_MEDIA = "Die-cut labels" CONTINUOUS_MEDIA = "Continuous length tape" DRYRUN_DIR = Path("/tmp/dryrun") def map_status(raw: dict[str, Any], expected_label: str) -> dict[str, Any]: """Translate a brother_ql status dict into the heartbeat printer block.""" errors = [str(e) for e in (raw.get("errors") or [])] identified = raw.get("identified_media") label_id = getattr(identified, "identifier", None) media_type = raw.get("media_type") media = {"Die-cut labels": "die-cut", "Continuous length tape": "continuous"}.get( str(media_type) ) if media is None and str(media_type) == "No media": errors.append("no media loaded") if expected_label not in ("auto", "") and label_id and label_id != expected_label: errors.append(f"wrong roll: loaded {label_id}, expected {expected_label}") connected = str(raw.get("status_type", "")) == "Reply to status request" phase_ok = str(raw.get("phase_type", "")) == "Waiting to receive" ready = connected and phase_ok and not errors and label_id is not None return { "connected": connected, "model": raw.get("model_name"), "ready": ready, "media_type": media, "label_id": label_id, "media_width_mm": raw.get("media_width"), "media_length_mm": raw.get("media_length"), "errors": errors, } class Printer: def __init__(self, cfg: Config): self._model = cfg.brother_model self._identifier = cfg.printer_identifier self._expected_label = cfg.brother_label self._threshold = cfg.threshold self._dither = cfg.dither self._dry_run = cfg.dry_run self._lock = threading.Lock() if self._dry_run: log.warning("DRY_RUN active: nothing is sent to the printer") def get_status(self) -> dict[str, Any]: if self._dry_run: label_id = None if self._expected_label == "auto" else self._expected_label label_id = label_id or "103x164" spec = find_label(label_id) return { "connected": True, "model": f"{self._model} (dry-run)", "ready": True, "media_type": "die-cut" if spec.die_cut else "continuous", "label_id": label_id, "media_width_mm": int(spec.width_px * 25.4 // 300), "media_length_mm": int(spec.height_px * 25.4 // 300) if spec.die_cut else 0, "errors": [], } try: with self._lock: st, _raw = bq_status( printer_model=self._model, printer_identifier=self._identifier, backend_identifier="pyusb", ) except Exception as err: # noqa: BLE001 — USB stack raises many types log.debug("status failed: %r", err) return { "connected": False, "model": None, "ready": False, "media_type": None, "label_id": None, "media_width_mm": None, "media_length_mm": None, "errors": [f"printer unreachable: {type(err).__name__}"], } return map_status(st if isinstance(st, dict) else {}, self._expected_label) def print_image(self, img: Image.Image, label_id: str) -> dict[str, Any]: if self._dry_run: out = DRYRUN_DIR out.mkdir(parents=True, exist_ok=True) path = out / f"dryrun-{threading.get_ident()}.png" img.save(path) log.info("dry-run: saved %s (%dx%d)", path, img.width, img.height) return { "instructions_sent": True, "outcome": "printed", "did_print": True, "ready_for_next_job": True, } qlr = BrotherQLRaster(self._model) qlr.exception_on_warning = True instructions = convert( qlr, [img], label_id, rotate="0", threshold=self._threshold, dither=self._dither, cut=True, ) with self._lock: result = bq_send( instructions, self._identifier, backend_identifier="pyusb", blocking=True, ) return result if isinstance(result, dict) else {"outcome": "unknown"}