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.
- printer_cli-0.1.0.dist-info/METADATA +229 -0
- printer_cli-0.1.0.dist-info/RECORD +33 -0
- printer_cli-0.1.0.dist-info/WHEEL +4 -0
- printer_cli-0.1.0.dist-info/entry_points.txt +3 -0
- printer_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
- prt/__init__.py +3 -0
- prt/__main__.py +3 -0
- prt/cache.py +43 -0
- prt/cli.py +834 -0
- prt/config.py +127 -0
- prt/discovery.py +121 -0
- prt/drivers/__init__.py +0 -0
- prt/drivers/base.py +90 -0
- prt/drivers/epson.py +88 -0
- prt/drivers/fake.py +86 -0
- prt/drivers/ipp.py +335 -0
- prt/drivers/registry.py +54 -0
- prt/fixtures/__init__.py +0 -0
- prt/fixtures/epson-xp6000.json +62 -0
- prt/maintenance.py +49 -0
- prt/media.py +60 -0
- prt/models.py +192 -0
- prt/printing.py +103 -0
- prt/style.py +325 -0
- prt/testpage.py +71 -0
- prt/transport/__init__.py +0 -0
- prt/transport/escl.py +201 -0
- prt/transport/ipp.py +364 -0
- prt/transport/snmp.py +140 -0
- prt/tui/__init__.py +0 -0
- prt/tui/app.py +495 -0
- prt/tui/app.tcss +308 -0
- prt/tui/widgets.py +181 -0
prt/drivers/ipp.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
"""Generic driver: any IPP Everywhere / AirPrint / Mopria printer, plus eSCL scanning.
|
|
2
|
+
|
|
3
|
+
Works for most network printers made since ~2012, whatever the brand. Vendor drivers
|
|
4
|
+
subclass this and add what IPP cannot do (maintenance, counters).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
from prt import media
|
|
16
|
+
from prt.drivers.base import Driver, PrinterError, Unreachable
|
|
17
|
+
from prt.models import (Alert, Capability, Ink, Job, PrinterInfo, PrintOptions, ScanSettings,
|
|
18
|
+
Severity, Status, Tray)
|
|
19
|
+
from prt.transport import ipp
|
|
20
|
+
from prt.transport.ipp import Attr, IPPClient, IPPError, as_list
|
|
21
|
+
|
|
22
|
+
# printer-state-reasons keyword (without -report/-warning/-error) → friendly message
|
|
23
|
+
REASONS = {
|
|
24
|
+
"marker-supply-low": "ink/toner low",
|
|
25
|
+
"marker-supply-empty": "ink/toner empty — replace the cartridge",
|
|
26
|
+
"marker-waste-almost-full": "waste ink pad almost full — service soon",
|
|
27
|
+
"marker-waste-full": "waste ink pad full — printer needs service",
|
|
28
|
+
"toner-low": "toner low",
|
|
29
|
+
"toner-empty": "toner empty",
|
|
30
|
+
"media-empty": "out of paper",
|
|
31
|
+
"media-needed": "load paper",
|
|
32
|
+
"media-low": "paper low",
|
|
33
|
+
"media-jam": "paper jam",
|
|
34
|
+
"cover-open": "cover open",
|
|
35
|
+
"door-open": "door open",
|
|
36
|
+
"input-tray-missing": "input tray missing",
|
|
37
|
+
"output-area-full": "output tray full",
|
|
38
|
+
"offline": "printer offline",
|
|
39
|
+
"paused": "printer paused",
|
|
40
|
+
"shutdown": "printer shutting down",
|
|
41
|
+
"spool-area-full": "printer memory full",
|
|
42
|
+
"interpreter-resource-unavailable": "printer busy (resources unavailable)",
|
|
43
|
+
"moving-to-paused": "pausing",
|
|
44
|
+
"connecting-to-device": "connecting",
|
|
45
|
+
"other": "attention needed (see printer panel)",
|
|
46
|
+
}
|
|
47
|
+
IGNORED_REASONS = {"none", ""}
|
|
48
|
+
|
|
49
|
+
QUALITY = {"draft": 3, "normal": 4, "high": 5}
|
|
50
|
+
|
|
51
|
+
# Formats the printer can take directly; anything else goes through CUPS (see prt.printing).
|
|
52
|
+
DIRECT_FORMATS = {".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".pwg": "image/pwg-raster",
|
|
53
|
+
".urf": "image/urf"}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def parse_reason(reason: str) -> Alert | None:
|
|
57
|
+
if reason in IGNORED_REASONS:
|
|
58
|
+
return None
|
|
59
|
+
base, severity = reason, Severity.ERROR # RFC 8011: no suffix means error
|
|
60
|
+
for suffix, sev in (("-report", Severity.INFO), ("-warning", Severity.WARNING),
|
|
61
|
+
("-error", Severity.ERROR)):
|
|
62
|
+
if reason.endswith(suffix):
|
|
63
|
+
base, severity = reason[: -len(suffix)], sev
|
|
64
|
+
break
|
|
65
|
+
if base in ("moving-to-paused", "connecting-to-device"):
|
|
66
|
+
severity = Severity.INFO
|
|
67
|
+
# Epson reports a nearly-full waste pad as "-report"; it still deserves a warning.
|
|
68
|
+
if base == "marker-waste-almost-full" and severity == Severity.INFO:
|
|
69
|
+
severity = Severity.WARNING
|
|
70
|
+
return Alert(reason, severity, REASONS.get(base, base.replace("-", " ")))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def parse_keyvals(value: str) -> dict[str, str]:
|
|
74
|
+
"""Parse 'type=x;name=Sheet\\ feeder;' (printer-input-tray) honouring backslash escapes."""
|
|
75
|
+
out: dict[str, str] = {}
|
|
76
|
+
for part in re.split(r"(?<!\\);", value):
|
|
77
|
+
if "=" in part:
|
|
78
|
+
k, v = part.split("=", 1)
|
|
79
|
+
out[k.strip()] = v.replace("\\ ", " ").replace("\\;", ";").replace("\\\\", "\\")
|
|
80
|
+
return out
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _int(v: Any) -> int | None:
|
|
84
|
+
try:
|
|
85
|
+
return int(v)
|
|
86
|
+
except (TypeError, ValueError):
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class IPPDriver(Driver):
|
|
91
|
+
name = "ipp"
|
|
92
|
+
vendor = "generic"
|
|
93
|
+
capabilities = frozenset({Capability.INFO, Capability.STATUS, Capability.JOBS,
|
|
94
|
+
Capability.PRINT, Capability.SCAN, Capability.IDENTIFY})
|
|
95
|
+
|
|
96
|
+
def __init__(self, target, timeout: float = 5.0, client: IPPClient | None = None):
|
|
97
|
+
super().__init__(target, timeout)
|
|
98
|
+
self.client = client or IPPClient(target.host, target.ipp_port, target.ipp_path,
|
|
99
|
+
target.ipp_tls, timeout)
|
|
100
|
+
self._attrs_cache: dict[str, Any] | None = None
|
|
101
|
+
self._fresh = False # True right after auto-detection fetched attributes
|
|
102
|
+
|
|
103
|
+
# --- transport helpers ---------------------------------------------------
|
|
104
|
+
def _call(self, fn, *args, **kwargs):
|
|
105
|
+
try:
|
|
106
|
+
return fn(*args, **kwargs)
|
|
107
|
+
except (httpx.TransportError, OSError) as exc:
|
|
108
|
+
raise Unreachable(self.target, type(exc).__name__) from exc
|
|
109
|
+
except IPPError as exc:
|
|
110
|
+
raise PrinterError(f"printer rejected the request: {exc}") from exc
|
|
111
|
+
|
|
112
|
+
def attributes(self, refresh: bool = True) -> dict[str, Any]:
|
|
113
|
+
if self._fresh and self._attrs_cache is not None:
|
|
114
|
+
self._fresh = False
|
|
115
|
+
return self._attrs_cache
|
|
116
|
+
if refresh or self._attrs_cache is None:
|
|
117
|
+
self._attrs_cache = self._call(self.client.get_printer_attributes, ["all"])
|
|
118
|
+
return self._attrs_cache
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def display_name(self) -> str:
|
|
122
|
+
if self._attrs_cache:
|
|
123
|
+
return str(self._attrs_cache.get("printer-make-and-model") or self.target.name)
|
|
124
|
+
return self.target.name
|
|
125
|
+
|
|
126
|
+
# --- parsing (shared with vendor subclasses) ----------------------------
|
|
127
|
+
def _device_id(self, a: dict[str, Any]) -> dict[str, str]:
|
|
128
|
+
out = {}
|
|
129
|
+
for part in str(a.get("printer-device-id") or "").split(";"):
|
|
130
|
+
if ":" in part:
|
|
131
|
+
k, v = part.split(":", 1)
|
|
132
|
+
out[k.strip()] = v.strip()
|
|
133
|
+
return out
|
|
134
|
+
|
|
135
|
+
def _serial(self, a: dict[str, Any]) -> str | None:
|
|
136
|
+
sn = self._device_id(a).get("SN")
|
|
137
|
+
if not sn:
|
|
138
|
+
return None
|
|
139
|
+
# Epson reports SN as hex; decode it when every byte is printable, else show raw hex.
|
|
140
|
+
if re.fullmatch(r"(?:[0-9A-Fa-f]{2}){4,}", sn):
|
|
141
|
+
raw = bytes.fromhex(sn)
|
|
142
|
+
printable = raw.rstrip(b"\x00")
|
|
143
|
+
if all(32 <= b < 127 for b in printable):
|
|
144
|
+
return printable.decode()
|
|
145
|
+
head = bytes(b for b in raw if 32 <= b < 127).decode()
|
|
146
|
+
return f"{head} (raw {sn})"
|
|
147
|
+
return sn
|
|
148
|
+
|
|
149
|
+
def parse_inks(self, a: dict[str, Any]) -> list[Ink]:
|
|
150
|
+
names = as_list(a.get("marker-names"))
|
|
151
|
+
levels = as_list(a.get("marker-levels"))
|
|
152
|
+
colors = as_list(a.get("marker-colors"))
|
|
153
|
+
lows = as_list(a.get("marker-low-levels"))
|
|
154
|
+
highs = as_list(a.get("marker-high-levels"))
|
|
155
|
+
kinds = as_list(a.get("marker-types"))
|
|
156
|
+
inks = []
|
|
157
|
+
for i, n in enumerate(names):
|
|
158
|
+
lvl = _int(levels[i]) if i < len(levels) else None
|
|
159
|
+
high = _int(highs[i]) if i < len(highs) else 100
|
|
160
|
+
if lvl is not None and lvl < 0:
|
|
161
|
+
lvl = None # -1 unknown, -2 unknown, -3 "some remaining"
|
|
162
|
+
elif lvl is not None and high and high != 100:
|
|
163
|
+
lvl = round(lvl * 100 / high)
|
|
164
|
+
inks.append(Ink(
|
|
165
|
+
name=str(n), color=str(colors[i]) if i < len(colors) else "#888888",
|
|
166
|
+
level=lvl, low=_int(lows[i]) if i < len(lows) else 15, high=100,
|
|
167
|
+
kind=str(kinds[i]) if i < len(kinds) else "ink-cartridge",
|
|
168
|
+
))
|
|
169
|
+
return inks
|
|
170
|
+
|
|
171
|
+
def parse_trays(self, a: dict[str, Any]) -> list[Tray]:
|
|
172
|
+
trays: list[Tray] = []
|
|
173
|
+
seen: set[tuple] = set()
|
|
174
|
+
for col in as_list(a.get("media-col-ready")):
|
|
175
|
+
if not isinstance(col, dict):
|
|
176
|
+
continue
|
|
177
|
+
size = col.get("media-size") or {}
|
|
178
|
+
tray = Tray(
|
|
179
|
+
source=str(col.get("media-source") or "auto"),
|
|
180
|
+
media=media.from_size(_int(size.get("x-dimension")), _int(size.get("y-dimension"))),
|
|
181
|
+
media_type=col.get("media-type"),
|
|
182
|
+
)
|
|
183
|
+
# Printers list the same loaded paper once per margin variant (an HP DeskJet sends
|
|
184
|
+
# bordered, borderless and bordered again); keep one entry per tray/size/type.
|
|
185
|
+
key = (tray.source, tray.media, tray.media_type)
|
|
186
|
+
if key not in seen:
|
|
187
|
+
seen.add(key)
|
|
188
|
+
trays.append(tray)
|
|
189
|
+
if not trays: # fall back to media-ready keywords
|
|
190
|
+
for kw in as_list(a.get("media-ready")):
|
|
191
|
+
trays.append(Tray(source="auto", media=media.friendly(str(kw))))
|
|
192
|
+
# Tray fill levels: only trust non-negative values (-2 = unknown, -3 = "some").
|
|
193
|
+
levels = []
|
|
194
|
+
for raw in as_list(a.get("printer-input-tray")):
|
|
195
|
+
kv = parse_keyvals(str(raw))
|
|
196
|
+
lvl, cap = _int(kv.get("level")), _int(kv.get("maxcapacity"))
|
|
197
|
+
levels.append(round(lvl * 100 / cap) if lvl is not None and cap and lvl >= 0 and cap > 0 else None)
|
|
198
|
+
for tray, lvl in zip(trays, levels):
|
|
199
|
+
tray.level = lvl
|
|
200
|
+
return trays
|
|
201
|
+
|
|
202
|
+
def parse_status(self, a: dict[str, Any]) -> Status:
|
|
203
|
+
reasons = [str(r) for r in as_list(a.get("printer-state-reasons"))]
|
|
204
|
+
alerts = [al for al in (parse_reason(r) for r in reasons) if al]
|
|
205
|
+
inks = self.parse_inks(a)
|
|
206
|
+
# Name the specific cartridges behind a generic "supply low" reason.
|
|
207
|
+
for ink in inks:
|
|
208
|
+
if ink.state == "replace":
|
|
209
|
+
alerts.append(Alert(f"ink-{ink.short.lower()}", Severity.ERROR,
|
|
210
|
+
f"{ink.name.replace(' ink', '')} {ink.level}% — replace cartridge"))
|
|
211
|
+
elif ink.state == "low":
|
|
212
|
+
alerts.append(Alert(f"ink-{ink.short.lower()}", Severity.WARNING,
|
|
213
|
+
f"{ink.name.replace(' ink', '')} {ink.level}% — low"))
|
|
214
|
+
if any(ink.state in ("low", "replace") for ink in inks):
|
|
215
|
+
alerts = [al for al in alerts if not al.code.startswith("marker-supply-low")]
|
|
216
|
+
alerts.sort(key=lambda al: [Severity.ERROR, Severity.WARNING, Severity.INFO].index(al.severity))
|
|
217
|
+
waste = None
|
|
218
|
+
if any(r.startswith("marker-waste-full") for r in reasons):
|
|
219
|
+
waste = "full"
|
|
220
|
+
elif any(r.startswith("marker-waste-almost-full") for r in reasons):
|
|
221
|
+
waste = "almost-full"
|
|
222
|
+
elif "marker-names" in a:
|
|
223
|
+
waste = "ok"
|
|
224
|
+
return Status(
|
|
225
|
+
state=ipp.PRINTER_STATES.get(_int(a.get("printer-state")) or 0, "unknown"),
|
|
226
|
+
accepting=bool(a.get("printer-is-accepting-jobs", True)),
|
|
227
|
+
inks=inks, trays=self.parse_trays(a), alerts=alerts, reasons=reasons,
|
|
228
|
+
waste=waste, queued_jobs=_int(a.get("queued-job-count")) or 0,
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
def parse_info(self, a: dict[str, Any]) -> PrinterInfo:
|
|
232
|
+
dev = self._device_id(a)
|
|
233
|
+
make_model = str(a.get("printer-make-and-model") or a.get("printer-info") or self.target.name)
|
|
234
|
+
sides = as_list(a.get("sides-supported"))
|
|
235
|
+
return PrinterInfo(
|
|
236
|
+
name=self.target.name, make_model=make_model,
|
|
237
|
+
vendor=(dev.get("MFG") or make_model.split()[0]).title() if make_model else "Unknown",
|
|
238
|
+
host=self.target.host, driver=self.name, model=dev.get("MDL"),
|
|
239
|
+
serial=self._serial(a), firmware=a.get("printer-firmware-string-version"),
|
|
240
|
+
uuid=str(a.get("printer-uuid") or "").removeprefix("urn:uuid:") or None,
|
|
241
|
+
uptime_seconds=_int(a.get("printer-up-time")),
|
|
242
|
+
color=a.get("color-supported"), duplex=any(str(s).startswith("two-sided") for s in sides),
|
|
243
|
+
ppm=_int(a.get("pages-per-minute")), ppm_color=_int(a.get("pages-per-minute-color")),
|
|
244
|
+
formats=[str(f) for f in as_list(a.get("document-format-supported"))],
|
|
245
|
+
media=[m for m in (media.friendly(str(k)) for k in as_list(a.get("media-supported"))) if m],
|
|
246
|
+
media_sources=[str(s) for s in as_list(a.get("media-source-supported"))],
|
|
247
|
+
resolutions=[str(r) for r in as_list(a.get("printer-resolution-supported"))],
|
|
248
|
+
ipp_versions=[str(v) for v in as_list(a.get("ipp-versions-supported"))],
|
|
249
|
+
uris=[str(u) for u in as_list(a.get("printer-uri-supported"))],
|
|
250
|
+
admin_url=a.get("printer-more-info"),
|
|
251
|
+
capabilities=sorted(c.value for c in self.capabilities),
|
|
252
|
+
extra={"kind": [str(k) for k in as_list(a.get("printer-kind"))],
|
|
253
|
+
"command_sets": dev.get("CMD", "").split(",") if dev.get("CMD") else []},
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
# --- Driver API -----------------------------------------------------------
|
|
257
|
+
def info(self) -> PrinterInfo:
|
|
258
|
+
return self.parse_info(self.attributes())
|
|
259
|
+
|
|
260
|
+
def status(self) -> Status:
|
|
261
|
+
return self.parse_status(self.attributes())
|
|
262
|
+
|
|
263
|
+
def jobs(self, include_completed: bool = False) -> list[Job]:
|
|
264
|
+
"""Active jobs; with include_completed, active + completed (IPP needs two calls for that)."""
|
|
265
|
+
which = ["not-completed", "completed"] if include_completed else ["not-completed"]
|
|
266
|
+
seen: dict[int, Job] = {}
|
|
267
|
+
for w in which:
|
|
268
|
+
resp = self._call(self.client.request, ipp.OP_GET_JOBS, operation_attrs=[
|
|
269
|
+
Attr("which-jobs", ipp.KEYWORD, w),
|
|
270
|
+
Attr("requested-attributes", ipp.KEYWORD, ["job-id", "job-name", "job-state",
|
|
271
|
+
"job-originating-user-name",
|
|
272
|
+
"job-impressions-completed",
|
|
273
|
+
"time-at-creation"]),
|
|
274
|
+
])
|
|
275
|
+
for j in resp.groups_of(ipp.TAG_JOB):
|
|
276
|
+
job = self._job(j)
|
|
277
|
+
seen.setdefault(job.id, job)
|
|
278
|
+
return sorted(seen.values(), key=lambda j: j.id)
|
|
279
|
+
|
|
280
|
+
@staticmethod
|
|
281
|
+
def _job(j: dict[str, Any]) -> Job:
|
|
282
|
+
return Job(id=_int(j.get("job-id")) or 0, name=str(j.get("job-name") or "untitled"),
|
|
283
|
+
state=ipp.JOB_STATES.get(_int(j.get("job-state")) or 0, "unknown"),
|
|
284
|
+
user=j.get("job-originating-user-name"),
|
|
285
|
+
pages=_int(j.get("job-impressions-completed")),
|
|
286
|
+
created=_int(j.get("time-at-creation")))
|
|
287
|
+
|
|
288
|
+
def cancel_job(self, job_id: int) -> None:
|
|
289
|
+
self._call(self.client.request, ipp.OP_CANCEL_JOB,
|
|
290
|
+
operation_attrs=[Attr("job-id", ipp.INTEGER, job_id),
|
|
291
|
+
Attr("requesting-user-name", ipp.NAME, "prt")])
|
|
292
|
+
|
|
293
|
+
def identify(self) -> None:
|
|
294
|
+
self._call(self.client.request, ipp.OP_IDENTIFY_PRINTER,
|
|
295
|
+
operation_attrs=[Attr("identify-actions", ipp.KEYWORD, "flash")])
|
|
296
|
+
|
|
297
|
+
def submit(self, data: bytes, mime: str, options: PrintOptions) -> int:
|
|
298
|
+
"""Send document bytes straight to the printer with IPP Print-Job."""
|
|
299
|
+
job_attrs = [Attr("copies", ipp.INTEGER, max(1, options.copies))]
|
|
300
|
+
if options.media or options.tray:
|
|
301
|
+
col: dict[str, tuple[int, Any]] = {}
|
|
302
|
+
if options.media:
|
|
303
|
+
kw = media.resolve_alias(options.media)
|
|
304
|
+
size = media.size_of(kw)
|
|
305
|
+
if size:
|
|
306
|
+
col["media-size"] = (ipp.BEG_COLLECTION, {"x-dimension": (ipp.INTEGER, size[0]),
|
|
307
|
+
"y-dimension": (ipp.INTEGER, size[1])})
|
|
308
|
+
if options.tray:
|
|
309
|
+
col["media-source"] = (ipp.KEYWORD, options.tray)
|
|
310
|
+
if col:
|
|
311
|
+
job_attrs.append(Attr("media-col", ipp.BEG_COLLECTION, col))
|
|
312
|
+
if options.mono:
|
|
313
|
+
job_attrs.append(Attr("print-color-mode", ipp.KEYWORD, "monochrome"))
|
|
314
|
+
if options.quality:
|
|
315
|
+
job_attrs.append(Attr("print-quality", ipp.ENUM, QUALITY[options.quality]))
|
|
316
|
+
if options.duplex:
|
|
317
|
+
job_attrs.append(Attr("sides", ipp.KEYWORD, "two-sided-long-edge"))
|
|
318
|
+
resp = self._call(self.client.request, ipp.OP_PRINT_JOB, operation_attrs=[
|
|
319
|
+
Attr("requesting-user-name", ipp.NAME, "prt"),
|
|
320
|
+
Attr("job-name", ipp.NAME, options.job_name or "prt job"),
|
|
321
|
+
Attr("document-format", ipp.MIME, mime),
|
|
322
|
+
], job_attrs=job_attrs, data=data, timeout=max(self.timeout, 60))
|
|
323
|
+
return _int(resp.group(ipp.TAG_JOB).get("job-id")) or 0
|
|
324
|
+
|
|
325
|
+
def print_file(self, path: Path, options: PrintOptions) -> int:
|
|
326
|
+
from prt import printing
|
|
327
|
+
return printing.print_file(self, path, options)
|
|
328
|
+
|
|
329
|
+
def scan(self, settings: ScanSettings, progress=None) -> bytes:
|
|
330
|
+
from prt.transport.escl import ESCLClient
|
|
331
|
+
client = ESCLClient.for_target(self.target, self.timeout)
|
|
332
|
+
try:
|
|
333
|
+
return client.scan(settings, progress=progress)
|
|
334
|
+
except (httpx.TransportError, OSError) as exc:
|
|
335
|
+
raise Unreachable(self.target, f"scanner: {type(exc).__name__}") from exc
|
prt/drivers/registry.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Driver registry: pick a driver from the config or by asking the printer who it is.
|
|
2
|
+
|
|
3
|
+
To add a vendor: write `drivers/<vendor>.py` subclassing IPPDriver (or Driver), then add it
|
|
4
|
+
to DRIVERS and, if it can be auto-detected, to MATCHERS.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from prt.drivers.base import Driver, PrinterError
|
|
10
|
+
from prt.drivers.epson import EpsonDriver
|
|
11
|
+
from prt.drivers.ipp import IPPDriver
|
|
12
|
+
from prt.models import Target
|
|
13
|
+
|
|
14
|
+
DRIVERS: dict[str, type[Driver]] = {
|
|
15
|
+
"ipp": IPPDriver,
|
|
16
|
+
"epson": EpsonDriver,
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
# (substring of make-and-model / MFG, lowercased) → driver name
|
|
20
|
+
MATCHERS: list[tuple[str, str]] = [
|
|
21
|
+
("epson", "epson"),
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def driver_names() -> list[str]:
|
|
26
|
+
return ["auto", *DRIVERS, "fake"]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def detect(make_model: str) -> str:
|
|
30
|
+
mm = make_model.lower()
|
|
31
|
+
for needle, name in MATCHERS:
|
|
32
|
+
if needle in mm:
|
|
33
|
+
return name
|
|
34
|
+
return "ipp"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def make_driver(target: Target, timeout: float = 5.0) -> Driver:
|
|
38
|
+
if target.driver == "fake" or target.host == "demo":
|
|
39
|
+
from prt.drivers.fake import FakeDriver
|
|
40
|
+
return FakeDriver(target, timeout)
|
|
41
|
+
if target.driver != "auto":
|
|
42
|
+
cls = DRIVERS.get(target.driver)
|
|
43
|
+
if cls is None:
|
|
44
|
+
raise PrinterError(f"unknown driver '{target.driver}'",
|
|
45
|
+
hint="choose one of: " + ", ".join(driver_names()), exit_code=2)
|
|
46
|
+
return cls(target, timeout)
|
|
47
|
+
# Auto: one IPP round-trip tells us the make; reuse the fetched attributes.
|
|
48
|
+
probe = IPPDriver(target, timeout)
|
|
49
|
+
attrs = probe.attributes()
|
|
50
|
+
name = detect(str(attrs.get("printer-make-and-model") or attrs.get("printer-device-id") or ""))
|
|
51
|
+
driver = DRIVERS[name](target, timeout, client=probe.client)
|
|
52
|
+
driver._attrs_cache = attrs
|
|
53
|
+
driver._fresh = True
|
|
54
|
+
return driver
|
prt/fixtures/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
{
|
|
2
|
+
"_comment": "Captured from a real EPSON XP-6000 (firmware 20.50.NU30Q6) via Get-Printer-Attributes; serial and UUID scrubbed.",
|
|
3
|
+
"printer": {
|
|
4
|
+
"copies-supported": [1, 99],
|
|
5
|
+
"sides-supported": ["one-sided", "two-sided-short-edge", "two-sided-long-edge"],
|
|
6
|
+
"media-default": "iso_a4_210x297mm",
|
|
7
|
+
"media-supported": ["iso_a4_210x297mm", "na_index-4x6_4x6in", "na_5x7_5x7in", "na_govt-letter_8x10in", "iso_a5_148x210mm", "iso_a6_105x148mm", "na_letter_8.5x11in", "na_legal_8.5x14in", "oe_photo-l_3.5x5in", "jis_b5_182x257mm", "na_number-10_4.125x9.5in", "iso_dl_110x220mm", "disc_12cm_18x120mm"],
|
|
8
|
+
"printer-resolution-supported": ["360dpi", "720dpi", "5760x1440dpi"],
|
|
9
|
+
"print-quality-supported": [4, 5],
|
|
10
|
+
"print-color-mode-supported": ["color", "monochrome", "auto-monochrome", "process-monochrome", "auto"],
|
|
11
|
+
"media-ready": ["iso_a4_210x297mm", "na_index-4x6_4x6in", "disc_12cm_18x120mm"],
|
|
12
|
+
"media-col-ready": [
|
|
13
|
+
{"media-size": {"x-dimension": 21000, "y-dimension": 29700}, "media-type": "stationery", "media-source": "main"},
|
|
14
|
+
{"media-size": {"x-dimension": 10160, "y-dimension": 15240}, "media-type": "photographic", "media-source": "photo"},
|
|
15
|
+
{"media-size": {"x-dimension": 12000, "y-dimension": 12000}, "media-type": "disc", "media-source": "disc"}
|
|
16
|
+
],
|
|
17
|
+
"media-type-supported": ["stationery", "photographic-high-gloss", "photographic", "photographic-semi-gloss", "photographic-glossy", "photographic-matte", "stationery-coated", "labels", "envelope", "disc"],
|
|
18
|
+
"media-source-supported": ["auto", "main", "photo", "disc"],
|
|
19
|
+
"color-supported": true,
|
|
20
|
+
"document-format-supported": ["application/octet-stream", "image/pwg-raster", "image/urf", "image/jpeg"],
|
|
21
|
+
"ipp-versions-supported": ["1.0", "1.1", "2.0"],
|
|
22
|
+
"operations-supported": [2, 4, 5, 6, 8, 9, 10, 11, 17, 60],
|
|
23
|
+
"pages-per-minute": 9,
|
|
24
|
+
"pages-per-minute-color": 9,
|
|
25
|
+
"printer-alert": "code=markerInkAlmostEmpty",
|
|
26
|
+
"printer-alert-description": "ink low",
|
|
27
|
+
"printer-device-id": "MFG:EPSON;CMD:ESCPL2,BDC,D4,D4PX,ESCPR7,END4,GENEP,URF;MDL:XP-6000 Series;CLS:PRINTER;DES:EPSON XP-6000 Series;CID:EpsonRGB;RID:40;SN:583030303030303030;",
|
|
28
|
+
"printer-info": "EPSON XP-6000 Series",
|
|
29
|
+
"printer-is-accepting-jobs": true,
|
|
30
|
+
"printer-location": "",
|
|
31
|
+
"printer-make-and-model": "EPSON XP-6000 Series",
|
|
32
|
+
"printer-more-info": "http://printer.local:80/PRESENTATION/BONJOUR",
|
|
33
|
+
"printer-state": 3,
|
|
34
|
+
"printer-state-reasons": ["marker-supply-low-warning", "marker-waste-almost-full-report"],
|
|
35
|
+
"printer-up-time": 14545,
|
|
36
|
+
"printer-uri-supported": ["ipps://printer.local:631/ipp/print", "ipp://printer.local:631/ipp/print"],
|
|
37
|
+
"queued-job-count": 0,
|
|
38
|
+
"identify-actions-supported": "flash",
|
|
39
|
+
"marker-names": ["Photo Black ink", "Cyan ink", "Magenta ink", "Yellow ink", "Black ink"],
|
|
40
|
+
"marker-colors": ["#000000", "#00FFFF", "#FF00FF", "#FFFF00", "#000000"],
|
|
41
|
+
"marker-types": ["ink-cartridge", "ink-cartridge", "ink-cartridge", "ink-cartridge", "ink-cartridge"],
|
|
42
|
+
"marker-low-levels": [15, 15, 15, 15, 15],
|
|
43
|
+
"marker-high-levels": [100, 100, 100, 100, 100],
|
|
44
|
+
"marker-levels": [92, 1, 1, 12, 89],
|
|
45
|
+
"printer-uuid": "urn:uuid:00000000-0000-4000-8000-000000000000",
|
|
46
|
+
"printer-dns-sd-name": "EPSON XP-6000 Series",
|
|
47
|
+
"printer-kind": ["document", "envelope", "label", "photo", "disc"],
|
|
48
|
+
"printer-firmware-name": "Firmware",
|
|
49
|
+
"printer-firmware-string-version": "20.50.NU30Q6",
|
|
50
|
+
"printer-input-tray": [
|
|
51
|
+
"type=other;dimunit=micrometers;mediafeed=297000;mediaxfeed=210000;maxcapacity=-2;level=-2;status=0;name=Sheet\\ feeder\\ bin\\ 1;",
|
|
52
|
+
"type=sheetFeedAutoNonRemovableTray;dimunit=micrometers;mediafeed=297000;mediaxfeed=210000;maxcapacity=-2;level=-2;status=0;name=Sheet\\ feeder\\ bin\\ 1;"
|
|
53
|
+
],
|
|
54
|
+
"printer-output-tray": "type=unRemovableBin;maxcapacity=50;remaining=-3;status=0;name=Face-up\\ Tray;stackingorder=lastToFirst;pagedelivery=faceUp;"
|
|
55
|
+
},
|
|
56
|
+
"snmp": {"page_count": 1538, "sys_descr": "EPSON Built-in 11b/g/n Print Server"},
|
|
57
|
+
"jobs": [
|
|
58
|
+
{"job-id": 41, "job-name": "boarding-pass.pdf", "job-state": 9, "job-originating-user-name": "alex", "job-impressions-completed": 1, "time-at-creation": 13900},
|
|
59
|
+
{"job-id": 42, "job-name": "nozzle-check", "job-state": 9, "job-originating-user-name": "prt", "job-impressions-completed": 1, "time-at-creation": 14200}
|
|
60
|
+
],
|
|
61
|
+
"scanner": {"make_model": "EPSON XP-6000 Series", "sources": ["platen"], "resolutions": [100, 200, 300, 600, 1200], "color_modes": ["BlackAndWhite1", "Grayscale8", "RGB24"], "formats": ["application/pdf", "image/jpeg"], "max_width": 2550, "max_height": 3510, "duplex": false}
|
|
62
|
+
}
|
prt/maintenance.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Safety checks that run before ink-consuming maintenance."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
|
|
7
|
+
from prt.models import Status
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class Preflight:
|
|
12
|
+
ok: bool
|
|
13
|
+
blockers: list[str] = field(default_factory=list)
|
|
14
|
+
warnings: list[str] = field(default_factory=list)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def head_clean_preflight(status: Status) -> Preflight:
|
|
18
|
+
"""Head cleaning flushes ink into the waste pad. Refuse when that would hurt."""
|
|
19
|
+
blockers, warnings = [], []
|
|
20
|
+
if status.state in ("unknown", "") or not status.inks:
|
|
21
|
+
blockers.append("printer status is unknown — refresh and try again")
|
|
22
|
+
for ink in status.inks:
|
|
23
|
+
if ink.level is None:
|
|
24
|
+
blockers.append(f"{ink.name} level is unknown")
|
|
25
|
+
elif ink.level <= ink.low:
|
|
26
|
+
blockers.append(f"{ink.name} is at {ink.level}% (low level {ink.low}%) — "
|
|
27
|
+
"cleaning may empty it; replace the cartridge first")
|
|
28
|
+
if status.waste in ("almost-full", "full"):
|
|
29
|
+
blockers.append(f"waste ink pad is {status.waste.replace('-', ' ')} — "
|
|
30
|
+
"each cleaning adds to it; the printer may lock up when it is full")
|
|
31
|
+
if status.state == "processing":
|
|
32
|
+
blockers.append("printer is busy printing — wait for the job to finish")
|
|
33
|
+
if status.state == "offline":
|
|
34
|
+
blockers.append("printer is offline")
|
|
35
|
+
if not blockers:
|
|
36
|
+
warnings.append("head cleaning uses ink; run a nozzle check first to see if it is needed")
|
|
37
|
+
return Preflight(ok=not blockers, blockers=blockers, warnings=warnings)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def nozzle_check_preflight(status: Status) -> Preflight:
|
|
41
|
+
blockers, warnings = [], []
|
|
42
|
+
if status.state == "offline":
|
|
43
|
+
blockers.append("printer is offline")
|
|
44
|
+
if status.state == "processing":
|
|
45
|
+
blockers.append("printer is busy printing — wait for the job to finish")
|
|
46
|
+
if not any(t.media for t in status.trays):
|
|
47
|
+
warnings.append("no paper reported in any tray — load A4/Letter paper first")
|
|
48
|
+
warnings.append("prints one page using a small amount of each ink")
|
|
49
|
+
return Preflight(ok=not blockers, blockers=blockers, warnings=warnings)
|
prt/media.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Turn PWG self-describing media names (RFC 5101 / PWG 5101.1) into human labels."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
FRIENDLY = {
|
|
6
|
+
"a3": "A3", "a4": "A4", "a5": "A5", "a6": "A6", "b5": "B5", "letter": "Letter",
|
|
7
|
+
"legal": "Legal", "govt-letter": "8×10", "index-4x6": "4×6", "index-5x8": "5×8",
|
|
8
|
+
"5x7": "5×7", "photo-l": "L (3.5×5)", "hagaki": "Hagaki", "number-10": "#10 env",
|
|
9
|
+
"dl": "DL env", "c6": "C6 env", "foolscap": "Foolscap", "hivision": "HiVision",
|
|
10
|
+
"16k": "16K",
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
# User-facing shortcuts accepted by `prt print --media` and `--area`.
|
|
14
|
+
ALIASES = {
|
|
15
|
+
"a4": "iso_a4_210x297mm", "a5": "iso_a5_148x210mm", "a6": "iso_a6_105x148mm",
|
|
16
|
+
"letter": "na_letter_8.5x11in", "legal": "na_legal_8.5x14in", "4x6": "na_index-4x6_4x6in",
|
|
17
|
+
"5x7": "na_5x7_5x7in", "8x10": "na_govt-letter_8x10in", "disc": "disc_12cm_18x120mm",
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
# Sizes in hundredths of a millimetre, used to match media-col-ready collections.
|
|
21
|
+
SIZES = {
|
|
22
|
+
(21000, 29700): "A4", (14800, 21000): "A5", (10500, 14800): "A6", (21590, 27940): "Letter",
|
|
23
|
+
(21590, 35560): "Legal", (10160, 15240): "4×6", (12700, 17780): "5×7", (20320, 25400): "8×10",
|
|
24
|
+
(12000, 12000): "Disc", (8890, 12700): "L (3.5×5)",
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def friendly(keyword: str | None) -> str | None:
|
|
29
|
+
"""'iso_a4_210x297mm' → 'A4'; unknown names fall back to their middle segment."""
|
|
30
|
+
if not keyword:
|
|
31
|
+
return None
|
|
32
|
+
if keyword.startswith("disc_"):
|
|
33
|
+
return "Disc"
|
|
34
|
+
parts = keyword.split("_")
|
|
35
|
+
if len(parts) >= 3:
|
|
36
|
+
name = parts[1]
|
|
37
|
+
return FRIENDLY.get(name, name.replace("-", " ").title())
|
|
38
|
+
return keyword
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def from_size(x: int | None, y: int | None) -> str | None:
|
|
42
|
+
if x is None or y is None:
|
|
43
|
+
return None
|
|
44
|
+
return SIZES.get((x, y)) or SIZES.get((y, x)) or f"{x / 100:g}×{y / 100:g} mm"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def resolve_alias(name: str) -> str:
|
|
48
|
+
return ALIASES.get(name.lower(), name)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def size_of(keyword: str) -> tuple[int, int] | None:
|
|
52
|
+
"""Media size in hundredths of mm, parsed from a PWG name like 'iso_a4_210x297mm'."""
|
|
53
|
+
import re
|
|
54
|
+
|
|
55
|
+
m = re.search(r"_(\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)(mm|in)$", keyword)
|
|
56
|
+
if not m:
|
|
57
|
+
return None
|
|
58
|
+
x, y, unit = float(m.group(1)), float(m.group(2)), m.group(3)
|
|
59
|
+
factor = 100 if unit == "mm" else 2540
|
|
60
|
+
return round(x * factor), round(y * factor)
|