printer-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
prt/config.py ADDED
@@ -0,0 +1,127 @@
1
+ """Configuration: ~/.config/prt/config.toml, env overrides, and printer resolution.
2
+
3
+ Precedence: CLI flags > environment (PRT_PRINTER, PRT_CONFIG, PRT_TIMEOUT) > config file > defaults.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import tomllib
10
+ from dataclasses import asdict, dataclass, field, fields
11
+ from pathlib import Path
12
+
13
+ from prt.drivers.base import PrinterError
14
+ from prt.models import Target
15
+
16
+ DEFAULT_TIMEOUT = 5.0
17
+
18
+
19
+ def config_path(explicit: str | Path | None = None) -> Path:
20
+ if explicit:
21
+ return Path(explicit).expanduser()
22
+ if os.environ.get("PRT_CONFIG"):
23
+ return Path(os.environ["PRT_CONFIG"]).expanduser()
24
+ base = os.environ.get("XDG_CONFIG_HOME") or "~/.config"
25
+ return Path(base).expanduser() / "prt" / "config.toml"
26
+
27
+
28
+ def cache_dir() -> Path:
29
+ base = os.environ.get("XDG_CACHE_HOME") or "~/.cache"
30
+ return Path(base).expanduser() / "prt"
31
+
32
+
33
+ @dataclass
34
+ class Config:
35
+ path: Path
36
+ default: str | None = None
37
+ timeout: float = DEFAULT_TIMEOUT
38
+ printers: dict[str, Target] = field(default_factory=dict)
39
+
40
+ @classmethod
41
+ def load(cls, explicit: str | Path | None = None) -> "Config":
42
+ path = config_path(explicit)
43
+ cfg = cls(path=path)
44
+ if path.exists():
45
+ try:
46
+ data = tomllib.loads(path.read_text())
47
+ except tomllib.TOMLDecodeError as exc:
48
+ raise PrinterError(f"invalid config file {path}: {exc}",
49
+ hint="fix the TOML syntax or delete the file", exit_code=3) from exc
50
+ cfg.default = data.get("default")
51
+ cfg.timeout = float(data.get("timeout", DEFAULT_TIMEOUT))
52
+ known = {f.name for f in fields(Target)}
53
+ for name, entry in (data.get("printers") or {}).items():
54
+ if not isinstance(entry, dict) or "host" not in entry:
55
+ raise PrinterError(f"printer '{name}' in {path} has no host", exit_code=3)
56
+ cfg.printers[name] = Target(name=name, **{k: v for k, v in entry.items()
57
+ if k in known and k != "name"})
58
+ if os.environ.get("PRT_TIMEOUT"):
59
+ try:
60
+ cfg.timeout = float(os.environ["PRT_TIMEOUT"])
61
+ except ValueError:
62
+ raise PrinterError("PRT_TIMEOUT must be a number of seconds", exit_code=2)
63
+ return cfg
64
+
65
+ def save(self) -> None:
66
+ self.path.parent.mkdir(parents=True, exist_ok=True)
67
+ lines = ["# prt configuration — edit freely or use `prt printers add/remove/default`"]
68
+ if self.default:
69
+ lines.append(f"default = {_q(self.default)}")
70
+ if self.timeout != DEFAULT_TIMEOUT:
71
+ lines.append(f"timeout = {self.timeout}")
72
+ defaults = asdict(Target(name="", host=""))
73
+ for name, t in self.printers.items():
74
+ lines.append("")
75
+ lines.append(f"[printers.{_key(name)}]")
76
+ for k, v in asdict(t).items():
77
+ if k == "name" or (k != "host" and v == defaults[k]):
78
+ continue
79
+ lines.append(f"{k} = {_toml_value(v)}")
80
+ self.path.write_text("\n".join(lines) + "\n")
81
+
82
+ def resolve(self, selector: str | None = None) -> Target:
83
+ """Find the printer to talk to. `selector` is a saved name or a host/IP."""
84
+ selector = selector or os.environ.get("PRT_PRINTER") or self.default
85
+ if selector:
86
+ if selector in self.printers:
87
+ return self.printers[selector]
88
+ if selector == "demo":
89
+ return Target(name="demo", host="demo", driver="fake")
90
+ if _looks_like_host(selector):
91
+ return Target(name=selector, host=selector)
92
+ raise PrinterError(f"no saved printer named '{selector}'",
93
+ hint="run `prt printers list`, or pass a hostname/IP with --printer",
94
+ exit_code=2)
95
+ if len(self.printers) == 1:
96
+ return next(iter(self.printers.values()))
97
+ from prt.discovery import discover
98
+ found = [p for p in discover(timeout=2.0) if p.ipp]
99
+ if len(found) == 1:
100
+ return found[0].to_target()
101
+ if not found:
102
+ raise PrinterError("no printer configured and none found on the network",
103
+ hint="run `prt discover`, then `prt printers add NAME HOST --default`",
104
+ exit_code=2)
105
+ raise PrinterError(f"{len(found)} printers found; which one?",
106
+ hint="pick one with --printer, or set a default: `prt printers default NAME`",
107
+ exit_code=2)
108
+
109
+
110
+ def _looks_like_host(s: str) -> bool:
111
+ return "." in s or ":" in s or s.endswith(".local") or s == "localhost"
112
+
113
+
114
+ def _q(s: str) -> str:
115
+ return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
116
+
117
+
118
+ def _key(s: str) -> str:
119
+ return s if all(c.isalnum() or c in "-_" for c in s) else _q(s)
120
+
121
+
122
+ def _toml_value(v) -> str:
123
+ if isinstance(v, bool):
124
+ return "true" if v else "false"
125
+ if isinstance(v, (int, float)):
126
+ return str(v)
127
+ return _q(str(v))
prt/discovery.py ADDED
@@ -0,0 +1,121 @@
1
+ """Find printers and scanners on the LAN with mDNS/DNS-SD (Bonjour)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from dataclasses import dataclass, field
7
+
8
+ from prt.models import Target
9
+
10
+ SERVICES = ["_ipp._tcp.local.", "_ipps._tcp.local.", "_uscan._tcp.local.", "_uscans._tcp.local."]
11
+
12
+
13
+ @dataclass
14
+ class Discovered:
15
+ name: str # Bonjour instance name, e.g. "EPSON XP-6000 Series"
16
+ host: str # e.g. "EPSON721655.local"
17
+ addresses: list[str] = field(default_factory=list)
18
+ make_model: str | None = None
19
+ uuid: str | None = None
20
+ ipp: bool = False
21
+ ipp_port: int = 631
22
+ ipp_path: str = "/ipp/print"
23
+ ipp_tls: bool = False
24
+ scanner: bool = False
25
+ scan_port: int | None = None
26
+ scan_tls: bool | None = None
27
+ scan_path: str = "/eSCL"
28
+ admin_url: str | None = None
29
+
30
+ @property
31
+ def services(self) -> list[str]:
32
+ out = []
33
+ if self.ipp:
34
+ out.append("ipps" if self.ipp_tls else "ipp")
35
+ if self.scanner:
36
+ out.append("escl")
37
+ return out
38
+
39
+ def suggested_name(self) -> str:
40
+ base = (self.make_model or self.name).lower()
41
+ for junk in (" series", "epson ", "hp ", "canon ", "brother "):
42
+ base = base.replace(junk, " ")
43
+ return "-".join(base.split())[:24] or "printer"
44
+
45
+ def to_target(self, name: str | None = None) -> Target:
46
+ return Target(name=name or self.suggested_name(), host=self.host, ipp_port=self.ipp_port,
47
+ ipp_path=self.ipp_path, ipp_tls=self.ipp_tls, scan_port=self.scan_port,
48
+ scan_tls=self.scan_tls, scan_path=self.scan_path)
49
+
50
+
51
+ def _txt(info) -> dict[str, str]:
52
+ out = {}
53
+ for k, v in (info.properties or {}).items():
54
+ key = k.decode(errors="replace") if isinstance(k, bytes) else str(k)
55
+ val = v.decode(errors="replace") if isinstance(v, bytes) else ("" if v is None else str(v))
56
+ out[key.lower()] = val
57
+ return out
58
+
59
+
60
+ def merge(found: dict[str, Discovered], service: str, instance: str, host: str,
61
+ port: int, addresses: list[str], txt: dict[str, str]) -> None:
62
+ """Fold one DNS-SD record into the per-device table (keyed by UUID, else host)."""
63
+ key = (txt.get("uuid") or host).lower()
64
+ d = found.get(key)
65
+ if d is None:
66
+ d = found[key] = Discovered(name=instance, host=host)
67
+ d.addresses = sorted(set(d.addresses) | set(addresses))
68
+ d.make_model = d.make_model or txt.get("ty") or None
69
+ d.uuid = d.uuid or txt.get("uuid") or None
70
+ d.admin_url = d.admin_url or txt.get("adminurl") or None
71
+ if service.startswith("_ipp"):
72
+ tls = service.startswith("_ipps")
73
+ if not d.ipp or (d.ipp_tls and not tls): # prefer plain IPP: fewer TLS quirks on embedded devices
74
+ d.ipp, d.ipp_port, d.ipp_tls = True, port, tls
75
+ d.ipp_path = "/" + (txt.get("rp") or "ipp/print").strip("/")
76
+ elif service.startswith("_uscan"):
77
+ tls = service.startswith("_uscans") or port == 443
78
+ d.scanner, d.scan_port, d.scan_tls = True, port, tls
79
+ d.scan_path = "/" + (txt.get("rs") or "eSCL").strip("/")
80
+
81
+
82
+ def discover(timeout: float = 3.0) -> list[Discovered]:
83
+ from zeroconf import ServiceBrowser, ServiceListener, Zeroconf
84
+
85
+ found: dict[str, Discovered] = {}
86
+ pending: list[tuple[str, str]] = []
87
+
88
+ class Listener(ServiceListener):
89
+ def add_service(self, zc, type_, name):
90
+ pending.append((type_, name))
91
+
92
+ def update_service(self, zc, type_, name):
93
+ pending.append((type_, name))
94
+
95
+ def remove_service(self, zc, type_, name):
96
+ pass
97
+
98
+ zc = Zeroconf()
99
+ try:
100
+ browsers = [ServiceBrowser(zc, s, Listener()) for s in SERVICES]
101
+ deadline = time.monotonic() + timeout
102
+ seen: set[tuple[str, str]] = set()
103
+ while time.monotonic() < deadline or pending:
104
+ if not pending:
105
+ time.sleep(0.1)
106
+ continue
107
+ type_, name = pending.pop(0)
108
+ if (type_, name) in seen:
109
+ continue
110
+ seen.add((type_, name))
111
+ info = zc.get_service_info(type_, name, timeout=1500)
112
+ if not info or not info.server:
113
+ continue
114
+ instance = name.removesuffix("." + type_)
115
+ merge(found, type_, instance, info.server.rstrip("."), info.port or 0,
116
+ info.parsed_addresses(), _txt(info))
117
+ for b in browsers:
118
+ b.cancel()
119
+ finally:
120
+ zc.close()
121
+ return sorted(found.values(), key=lambda d: d.name.lower())
File without changes
prt/drivers/base.py ADDED
@@ -0,0 +1,90 @@
1
+ """The driver contract. One driver per vendor/protocol family; the CLI and TUI only talk to this."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from pathlib import Path
7
+
8
+ from prt.models import Capability, Job, PrinterInfo, PrintOptions, ScanSettings, Status, Target
9
+
10
+
11
+ class PrinterError(Exception):
12
+ """A user-facing failure. ``hint`` tells the user how to fix it."""
13
+
14
+ def __init__(self, message: str, hint: str | None = None, exit_code: int = 1):
15
+ super().__init__(message)
16
+ self.hint = hint
17
+ self.exit_code = exit_code
18
+
19
+
20
+ class Unreachable(PrinterError):
21
+ def __init__(self, target: Target, detail: str = ""):
22
+ super().__init__(
23
+ f"cannot reach printer '{target.name}' at {target.host}" + (f" ({detail})" if detail else ""),
24
+ hint="the printer may be asleep or off — press a button on it, or check `prt discover`",
25
+ )
26
+
27
+
28
+ class Unsupported(PrinterError):
29
+ def __init__(self, driver: "Driver", capability: Capability):
30
+ super().__init__(
31
+ f"{driver.display_name} does not support {capability.value.replace('_', ' ')} "
32
+ f"(capability: {capability.value}, driver: {driver.name})",
33
+ hint="run `prt overview` to see what this printer supports",
34
+ )
35
+
36
+
37
+ class Driver(ABC):
38
+ """Base class. Subclasses declare ``capabilities`` and override the matching methods."""
39
+
40
+ name: str = "base"
41
+ vendor: str = "generic"
42
+ capabilities: frozenset[Capability] = frozenset()
43
+
44
+ def __init__(self, target: Target, timeout: float = 5.0):
45
+ self.target = target
46
+ self.timeout = timeout
47
+
48
+ @property
49
+ def display_name(self) -> str:
50
+ return self.target.name
51
+
52
+ def supports(self, cap: Capability) -> bool:
53
+ return cap in self.capabilities
54
+
55
+ def require(self, cap: Capability) -> None:
56
+ if not self.supports(cap):
57
+ raise Unsupported(self, cap)
58
+
59
+ # --- read --------------------------------------------------------------
60
+ @abstractmethod
61
+ def info(self) -> PrinterInfo: ...
62
+
63
+ @abstractmethod
64
+ def status(self) -> Status: ...
65
+
66
+ def jobs(self, include_completed: bool = False) -> list[Job]:
67
+ raise Unsupported(self, Capability.JOBS)
68
+
69
+ # --- act ---------------------------------------------------------------
70
+ def cancel_job(self, job_id: int) -> None:
71
+ raise Unsupported(self, Capability.JOBS)
72
+
73
+ def print_file(self, path: Path, options: PrintOptions) -> int:
74
+ """Submit a file; returns the job id."""
75
+ raise Unsupported(self, Capability.PRINT)
76
+
77
+ def scan(self, settings: ScanSettings, progress=None) -> bytes:
78
+ raise Unsupported(self, Capability.SCAN)
79
+
80
+ def identify(self) -> None:
81
+ raise Unsupported(self, Capability.IDENTIFY)
82
+
83
+ def nozzle_check(self) -> None:
84
+ raise Unsupported(self, Capability.NOZZLE_CHECK)
85
+
86
+ def head_clean(self) -> None:
87
+ raise Unsupported(self, Capability.HEAD_CLEAN)
88
+
89
+ def test_page(self) -> int:
90
+ raise Unsupported(self, Capability.TEST_PAGE)
prt/drivers/epson.py ADDED
@@ -0,0 +1,88 @@
1
+ """Epson inkjets: everything the generic IPP driver does, plus SNMP page counters and
2
+ maintenance (nozzle check, head cleaning) through ESC/P2 "remote mode" commands on port 9100.
3
+
4
+ The remote-mode byte sequences are taken from gutenprint's escputil
5
+ (src/escputil/escputil.c: exit_packet_mode_old, start/end_remote_sequence,
6
+ do_head_clean, do_nozzle_check, do_print_cmd).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import socket
12
+
13
+ from prt.drivers.base import PrinterError, Unreachable
14
+ from prt.drivers.ipp import IPPDriver
15
+ from prt.models import Capability, PrinterInfo, PrintOptions, Status
16
+ from prt.transport import snmp
17
+
18
+ # --- ESC/P2 remote mode (escputil.c) ------------------------------------------
19
+ EXIT_PACKET_MODE = b"\x00\x00\x00\x1b\x01@EJL 1284.4\n@EJL \n\x1b@"
20
+ REMOTE_START = b"\x1b@\x1b(R\x08\x00\x00REMOTE1"
21
+ REMOTE_END = b"\x1b\x00\x00\x00\x1b\x00"
22
+ JOB_END = b"\x0c\x1b\x00\x1b\x00"
23
+
24
+
25
+ def remote_cmd(cmd: bytes, *args: int) -> bytes:
26
+ """Two-letter command, 16-bit little-endian arg count, then the args."""
27
+ return cmd + bytes([len(args) & 0xFF, (len(args) >> 8) & 0xFF]) + bytes(args)
28
+
29
+
30
+ def head_clean_payload() -> bytes:
31
+ return EXIT_PACKET_MODE + REMOTE_START + remote_cmd(b"CH", 0, 0) + REMOTE_END + JOB_END
32
+
33
+
34
+ def nozzle_check_payload() -> bytes:
35
+ return (EXIT_PACKET_MODE + REMOTE_START + remote_cmd(b"VI", 0, 0) + remote_cmd(b"NC", 0, 0x10)
36
+ + remote_cmd(b"NC", 0, 0) + REMOTE_END + JOB_END)
37
+
38
+
39
+ class EpsonDriver(IPPDriver):
40
+ name = "epson"
41
+ vendor = "epson"
42
+ capabilities = IPPDriver.capabilities | frozenset({
43
+ Capability.NOZZLE_CHECK, Capability.HEAD_CLEAN, Capability.TEST_PAGE, Capability.COUNTERS,
44
+ })
45
+
46
+ # --- side channels (overridden by the replay driver) ----------------------
47
+ def snmp_page_count(self) -> int | None:
48
+ try:
49
+ values = snmp.get(self.target.host, [snmp.PRT_LIFETIME_COUNT],
50
+ self.target.snmp_community, timeout=min(self.timeout, 2.0))
51
+ except (snmp.SNMPError, OSError):
52
+ return None
53
+ value = values.get(snmp.PRT_LIFETIME_COUNT)
54
+ return value if isinstance(value, int) else None
55
+
56
+ def send_raw(self, payload: bytes) -> None:
57
+ from prt.transport.ipp import trace
58
+ trace(f"RAW → {self.target.host}:{self.target.raw_port} ({len(payload)} bytes ESC/P2 remote mode)")
59
+ try:
60
+ with socket.create_connection((self.target.host, self.target.raw_port),
61
+ timeout=self.timeout) as sock:
62
+ sock.sendall(payload)
63
+ except OSError as exc:
64
+ raise Unreachable(self.target, f"raw port {self.target.raw_port}: {exc}") from exc
65
+
66
+ # --- enriched reads ----------------------------------------------------------
67
+ def info(self) -> PrinterInfo:
68
+ info = super().info()
69
+ info.page_count = self.snmp_page_count()
70
+ return info
71
+
72
+ def status(self) -> Status:
73
+ return super().status()
74
+
75
+ # --- maintenance --------------------------------------------------------------
76
+ def nozzle_check(self) -> None:
77
+ self.send_raw(nozzle_check_payload())
78
+
79
+ def head_clean(self) -> None:
80
+ self.send_raw(head_clean_payload())
81
+
82
+ def test_page(self) -> int:
83
+ from prt.testpage import render_jpeg
84
+ try:
85
+ data = render_jpeg(self.display_name)
86
+ except ImportError as exc: # pragma: no cover - Pillow is a dependency
87
+ raise PrinterError("test page needs Pillow", hint="uv pip install pillow") from exc
88
+ return self.submit(data, "image/jpeg", PrintOptions(job_name="prt test page", media="a4"))
prt/drivers/fake.py ADDED
@@ -0,0 +1,86 @@
1
+ """Replay driver: answers from a captured fixture. Used by tests, demos, and `prt -p demo`.
2
+
3
+ It runs the *real* parsing code of the IPP/Epson drivers, so tests exercise the same
4
+ paths as a live printer — only the transport is replaced.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ import json
11
+ from importlib import resources
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from prt.drivers.epson import EpsonDriver
16
+ from prt.models import ScanSettings, Target
17
+ from prt.transport import ipp
18
+
19
+ FIXTURE = "epson-xp6000.json"
20
+
21
+ # A tiny valid one-page PDF used as the fake scan result.
22
+ _PDF = (b"%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n"
23
+ b"2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n"
24
+ b"3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 595 842]>>endobj\n"
25
+ b"trailer<</Root 1 0 R>>\n%%EOF\n")
26
+ _JPEG = bytes.fromhex("ffd8ffe000104a46494600010100000100010000ffd9")
27
+
28
+
29
+ def load_fixture(name: str = FIXTURE) -> dict[str, Any]:
30
+ path = Path(name)
31
+ if path.exists():
32
+ return json.loads(path.read_text())
33
+ return json.loads(resources.files("prt.fixtures").joinpath(name).read_text())
34
+
35
+
36
+ class FakeIPPClient:
37
+ """Stands in for IPPClient; records every request it receives."""
38
+
39
+ def __init__(self, fixture: dict[str, Any]):
40
+ self.fixture = fixture
41
+ self.requests: list[tuple[int, list, list, bytes]] = []
42
+ self.next_job_id = 100
43
+ self.printer_uri = "ipp://demo:631/ipp/print"
44
+
45
+ def get_printer_attributes(self, requested=None) -> dict[str, Any]:
46
+ return copy.deepcopy(self.fixture["printer"])
47
+
48
+ def request(self, operation, *, operation_attrs=None, job_attrs=None, data=b"", timeout=None):
49
+ self.requests.append((operation, operation_attrs or [], job_attrs or [], data))
50
+ resp = ipp.Response((1, 1), 0, len(self.requests))
51
+ if operation == ipp.OP_GET_JOBS:
52
+ which = next((a.value for a in operation_attrs or [] if a.name == "which-jobs"), "")
53
+ for j in self.fixture.get("jobs", []):
54
+ done = j.get("job-state", 9) >= 7
55
+ if (which == "completed") == done: # like a real printer: the two sets are disjoint
56
+ resp.groups.append((ipp.TAG_JOB, dict(j)))
57
+ elif operation == ipp.OP_PRINT_JOB:
58
+ self.next_job_id += 1
59
+ resp.groups.append((ipp.TAG_JOB, {"job-id": self.next_job_id, "job-state": 3}))
60
+ return resp
61
+
62
+
63
+ class FakeDriver(EpsonDriver):
64
+ name = "fake"
65
+
66
+ def __init__(self, target: Target | None = None, timeout: float = 5.0, fixture: str = FIXTURE):
67
+ self.fixture = load_fixture(fixture)
68
+ target = target or Target(name="demo", host="demo", driver="fake")
69
+ super().__init__(target, timeout, client=FakeIPPClient(self.fixture))
70
+ self.raw_sent: list[bytes] = []
71
+
72
+ # Replace the network side-channels with fixture data / recorders.
73
+ def snmp_page_count(self) -> int | None:
74
+ return self.fixture.get("snmp", {}).get("page_count")
75
+
76
+ def send_raw(self, payload: bytes) -> None:
77
+ self.raw_sent.append(payload)
78
+
79
+ def scan(self, settings: ScanSettings, progress=None) -> bytes:
80
+ for stage in ("starting", "scanning", "receiving", "done"):
81
+ if progress:
82
+ progress(stage)
83
+ return _PDF if settings.format == "pdf" else _JPEG
84
+
85
+ def scanner_info(self) -> dict[str, Any]:
86
+ return dict(self.fixture.get("scanner", {}))