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/transport/escl.py ADDED
@@ -0,0 +1,201 @@
1
+ """eSCL (AirScan / Mopria Scan) client: capabilities, status, and a flatbed scan job.
2
+
3
+ Flow: POST /eSCL/ScanJobs (ScanSettings XML) → 201 + Location → GET <job>/NextDocument
4
+ until the scanner returns 404. Many scanners answer 503 while the head is still moving.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import time
10
+ import xml.etree.ElementTree as ET
11
+ from dataclasses import dataclass, field
12
+ from urllib.parse import urlparse
13
+
14
+ import httpx
15
+
16
+ from prt.models import ScanSettings, Target
17
+
18
+ NS_SCAN = "http://schemas.hp.com/imaging/escl/2011/05/03"
19
+ NS_PWG = "http://www.pwg.org/schemas/2010/12/sm"
20
+
21
+ # Regions in 1/300 inch.
22
+ AREAS = {"a4": (2480, 3508), "letter": (2550, 3300), "a5": (1748, 2480)}
23
+ MODES = {"color": "RGB24", "gray": "Grayscale8", "bw": "BlackAndWhite1"}
24
+ FORMATS = {"pdf": "application/pdf", "jpeg": "image/jpeg", "jpg": "image/jpeg"}
25
+
26
+
27
+ class ScanError(Exception):
28
+ pass
29
+
30
+
31
+ @dataclass
32
+ class ScannerCaps:
33
+ make_model: str = ""
34
+ version: str = ""
35
+ sources: list[str] = field(default_factory=list)
36
+ resolutions: list[int] = field(default_factory=list)
37
+ color_modes: list[str] = field(default_factory=list)
38
+ formats: list[str] = field(default_factory=list)
39
+ max_width: int = 2550
40
+ max_height: int = 3510
41
+
42
+
43
+ def _local(tag: str) -> str:
44
+ return tag.rsplit("}", 1)[-1]
45
+
46
+
47
+ def parse_capabilities(xml: str | bytes) -> ScannerCaps:
48
+ root = ET.fromstring(xml)
49
+ caps = ScannerCaps()
50
+ for el in root.iter():
51
+ name, text = _local(el.tag), (el.text or "").strip()
52
+ if name == "MakeAndModel":
53
+ caps.make_model = text
54
+ elif name == "Version" and not caps.version:
55
+ caps.version = text
56
+ elif name == "Platen":
57
+ caps.sources.append("platen")
58
+ elif name == "Adf":
59
+ caps.sources.append("adf")
60
+ elif name == "XResolution" and text.isdigit() and int(text) not in caps.resolutions:
61
+ caps.resolutions.append(int(text))
62
+ elif name == "ColorMode" and text not in caps.color_modes:
63
+ caps.color_modes.append(text)
64
+ elif name in ("DocumentFormat", "DocumentFormatExt") and text not in caps.formats:
65
+ caps.formats.append(text)
66
+ elif name == "MaxWidth" and text.isdigit():
67
+ caps.max_width = int(text)
68
+ elif name == "MaxHeight" and text.isdigit():
69
+ caps.max_height = int(text)
70
+ caps.resolutions.sort()
71
+ return caps
72
+
73
+
74
+ def parse_state(xml: str | bytes) -> str:
75
+ for el in ET.fromstring(xml).iter():
76
+ if _local(el.tag) == "State":
77
+ return (el.text or "").strip()
78
+ return "Unknown"
79
+
80
+
81
+ def build_settings(settings: ScanSettings, caps: ScannerCaps | None = None) -> str:
82
+ if settings.format not in FORMATS:
83
+ raise ScanError(f"unsupported scan format '{settings.format}' (use pdf or jpeg)")
84
+ if settings.mode not in MODES:
85
+ raise ScanError(f"unsupported colour mode '{settings.mode}' (use color, gray or bw)")
86
+ max_w, max_h = (caps.max_width, caps.max_height) if caps else (2550, 3510)
87
+ w, h = (max_w, max_h) if settings.area == "full" else AREAS.get(settings.area, AREAS["a4"])
88
+ w, h = min(w, max_w), min(h, max_h)
89
+ fmt = FORMATS[settings.format]
90
+ return (
91
+ '<?xml version="1.0" encoding="UTF-8"?>'
92
+ f'<scan:ScanSettings xmlns:scan="{NS_SCAN}" xmlns:pwg="{NS_PWG}">'
93
+ "<pwg:Version>2.63</pwg:Version>"
94
+ "<pwg:ScanRegions><pwg:ScanRegion>"
95
+ f"<pwg:Height>{h}</pwg:Height>"
96
+ "<pwg:ContentRegionUnits>escl:ThreeHundredthsOfInches</pwg:ContentRegionUnits>"
97
+ f"<pwg:Width>{w}</pwg:Width><pwg:XOffset>0</pwg:XOffset><pwg:YOffset>0</pwg:YOffset>"
98
+ "</pwg:ScanRegion></pwg:ScanRegions>"
99
+ "<pwg:InputSource>Platen</pwg:InputSource>"
100
+ f"<scan:ColorMode>{MODES[settings.mode]}</scan:ColorMode>"
101
+ f"<scan:XResolution>{settings.dpi}</scan:XResolution>"
102
+ f"<scan:YResolution>{settings.dpi}</scan:YResolution>"
103
+ f"<pwg:DocumentFormat>{fmt}</pwg:DocumentFormat>"
104
+ f"<scan:DocumentFormatExt>{fmt}</scan:DocumentFormatExt>"
105
+ "</scan:ScanSettings>"
106
+ )
107
+
108
+
109
+ class ESCLClient:
110
+ """TLS verification is disabled for this one scanner host only: embedded devices
111
+ use self-signed certificates and there is no CA to check them against."""
112
+
113
+ def __init__(self, base_url: str, timeout: float = 5.0, transport: httpx.BaseTransport | None = None):
114
+ self.base = base_url.rstrip("/")
115
+ self.timeout = timeout
116
+ self._transport = transport
117
+
118
+ def _client(self, timeout: float | None = None) -> httpx.Client:
119
+ return httpx.Client(verify=False, timeout=timeout or self.timeout, transport=self._transport)
120
+
121
+ @classmethod
122
+ def for_target(cls, target: Target, timeout: float = 5.0) -> "ESCLClient":
123
+ path = "/" + target.scan_path.strip("/")
124
+ if target.scan_port is not None:
125
+ tls = target.scan_tls if target.scan_tls is not None else target.scan_port == 443
126
+ return cls(f"{'https' if tls else 'http'}://{target.host}:{target.scan_port}{path}", timeout)
127
+ # Probe HTTPS first (Epson only answers eSCL there), then plain HTTP.
128
+ for scheme, port in (("https", 443), ("http", 80)):
129
+ client = cls(f"{scheme}://{target.host}:{port}{path}", timeout)
130
+ try:
131
+ with client._client(timeout=min(timeout, 4)) as c:
132
+ r = c.get(f"{client.base}/ScannerCapabilities")
133
+ if r.status_code == 200 and b"ScannerCapabilities" in r.content:
134
+ return client
135
+ except httpx.HTTPError:
136
+ continue
137
+ raise httpx.ConnectError(f"no eSCL scanner answered on {target.host}")
138
+
139
+ def capabilities(self) -> ScannerCaps:
140
+ with self._client() as c:
141
+ r = c.get(f"{self.base}/ScannerCapabilities")
142
+ r.raise_for_status()
143
+ return parse_capabilities(r.content)
144
+
145
+ def state(self) -> str:
146
+ with self._client() as c:
147
+ r = c.get(f"{self.base}/ScannerStatus")
148
+ r.raise_for_status()
149
+ return parse_state(r.content)
150
+
151
+ def _job_url(self, location: str) -> str:
152
+ # Some scanners return an http:// Location even when contacted over https; keep our origin.
153
+ path = urlparse(location).path or location
154
+ origin = urlparse(self.base)
155
+ return f"{origin.scheme}://{origin.netloc}{path}"
156
+
157
+ def scan(self, settings: ScanSettings, progress=None, poll: float = 1.0, max_wait: float = 180) -> bytes:
158
+ def report(stage: str) -> None:
159
+ if progress:
160
+ progress(stage)
161
+
162
+ caps = None
163
+ try:
164
+ caps = self.capabilities()
165
+ except httpx.HTTPError:
166
+ pass
167
+ if caps and caps.resolutions and settings.dpi not in caps.resolutions:
168
+ raise ScanError(f"{settings.dpi} dpi not supported; choose one of "
169
+ + ", ".join(map(str, caps.resolutions)))
170
+ body = build_settings(settings, caps)
171
+ report("starting")
172
+ with self._client(timeout=max(self.timeout, 30)) as c:
173
+ r = c.post(f"{self.base}/ScanJobs", content=body, headers={"Content-Type": "text/xml"})
174
+ if r.status_code == 503:
175
+ raise ScanError("scanner is busy — try again in a moment")
176
+ if r.status_code not in (200, 201) or "location" not in r.headers:
177
+ raise ScanError(f"scanner refused the job (HTTP {r.status_code})")
178
+ job = self._job_url(r.headers["location"])
179
+ report("scanning")
180
+ start = time.monotonic()
181
+ pages: list[bytes] = []
182
+ while True:
183
+ r = c.get(f"{job}/NextDocument", timeout=max(self.timeout, 120))
184
+ if r.status_code == 200:
185
+ pages.append(r.content)
186
+ report("receiving")
187
+ if settings.format == "pdf":
188
+ break # platen PDF = one document
189
+ continue
190
+ if r.status_code == 404 and pages:
191
+ break
192
+ if r.status_code in (503, 404) and time.monotonic() - start < max_wait:
193
+ time.sleep(poll)
194
+ continue
195
+ raise ScanError(f"scan failed (HTTP {r.status_code} from NextDocument)")
196
+ try:
197
+ c.delete(job)
198
+ except httpx.HTTPError:
199
+ pass
200
+ report("done")
201
+ return pages[0] if len(pages) == 1 else b"".join(pages)
prt/transport/ipp.py ADDED
@@ -0,0 +1,364 @@
1
+ """Minimal, dependency-free IPP/1.1–2.0 codec and HTTP client (RFC 8010 / RFC 8011).
2
+
3
+ Only what a printer dashboard needs: encode a request, decode any response
4
+ (including collections and 1setOf values), and POST it over http/https.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import struct
10
+ from dataclasses import dataclass, field
11
+ from datetime import datetime, timedelta, timezone
12
+ from typing import Any
13
+
14
+ import httpx
15
+
16
+ # --- Tags ------------------------------------------------------------------
17
+
18
+ TAG_OPERATION = 0x01
19
+ TAG_JOB = 0x02
20
+ TAG_END = 0x03
21
+ TAG_PRINTER = 0x04
22
+ TAG_UNSUPPORTED_GROUP = 0x05
23
+ DELIMITERS = {TAG_OPERATION, TAG_JOB, TAG_END, TAG_PRINTER, TAG_UNSUPPORTED_GROUP, 0x06, 0x07, 0x08, 0x09}
24
+
25
+ UNSUPPORTED = 0x10
26
+ UNKNOWN = 0x12
27
+ NO_VALUE = 0x13
28
+ INTEGER = 0x21
29
+ BOOLEAN = 0x22
30
+ ENUM = 0x23
31
+ OCTET_STRING = 0x30
32
+ DATETIME = 0x31
33
+ RESOLUTION = 0x32
34
+ RANGE = 0x33
35
+ BEG_COLLECTION = 0x34
36
+ TEXT_WITH_LANG = 0x35
37
+ NAME_WITH_LANG = 0x36
38
+ END_COLLECTION = 0x37
39
+ TEXT = 0x41
40
+ NAME = 0x42
41
+ KEYWORD = 0x44
42
+ URI = 0x45
43
+ URI_SCHEME = 0x46
44
+ CHARSET = 0x47
45
+ LANGUAGE = 0x48
46
+ MIME = 0x49
47
+ MEMBER_NAME = 0x4A
48
+
49
+ TRACE = False # set by `prt --verbose`: one line per request/response on stderr
50
+
51
+ OP_NAMES = {0x0002: "Print-Job", 0x0004: "Validate-Job", 0x0008: "Cancel-Job", 0x0009: "Get-Job-Attributes",
52
+ 0x000A: "Get-Jobs", 0x000B: "Get-Printer-Attributes", 0x003C: "Identify-Printer"}
53
+
54
+
55
+ def trace(message: str) -> None:
56
+ if TRACE:
57
+ import sys
58
+ sys.stderr.write(f"· {message}\n")
59
+
60
+
61
+ STRING_TAGS = {TEXT, NAME, KEYWORD, URI, URI_SCHEME, CHARSET, LANGUAGE, MIME, MEMBER_NAME, OCTET_STRING}
62
+
63
+ # --- Operations & status ----------------------------------------------------
64
+
65
+ OP_PRINT_JOB = 0x0002
66
+ OP_VALIDATE_JOB = 0x0004
67
+ OP_CANCEL_JOB = 0x0008
68
+ OP_GET_JOB_ATTRIBUTES = 0x0009
69
+ OP_GET_JOBS = 0x000A
70
+ OP_GET_PRINTER_ATTRIBUTES = 0x000B
71
+ OP_IDENTIFY_PRINTER = 0x003C
72
+
73
+ PRINTER_STATES = {3: "idle", 4: "processing", 5: "stopped"}
74
+ JOB_STATES = {
75
+ 3: "pending", 4: "pending-held", 5: "processing", 6: "processing-stopped",
76
+ 7: "canceled", 8: "aborted", 9: "completed",
77
+ }
78
+
79
+
80
+ class IPPError(Exception):
81
+ """An IPP-level failure (bad status code or malformed message)."""
82
+
83
+ def __init__(self, message: str, status: int | None = None):
84
+ super().__init__(message)
85
+ self.status = status
86
+
87
+
88
+ @dataclass
89
+ class Resolution:
90
+ x: int
91
+ y: int
92
+ units: int = 3 # 3 = dpi, 4 = dots per cm
93
+
94
+ def __str__(self) -> str:
95
+ unit = "dpi" if self.units == 3 else "dpcm"
96
+ return f"{self.x}{unit}" if self.x == self.y else f"{self.x}x{self.y}{unit}"
97
+
98
+
99
+ @dataclass
100
+ class Attr:
101
+ """An attribute to encode. ``tag`` selects the wire syntax; ``value`` may be a list."""
102
+
103
+ name: str
104
+ tag: int
105
+ value: Any
106
+
107
+
108
+ @dataclass
109
+ class Response:
110
+ version: tuple[int, int]
111
+ status: int
112
+ request_id: int
113
+ groups: list[tuple[int, dict[str, Any]]] = field(default_factory=list)
114
+
115
+ @property
116
+ def ok(self) -> bool:
117
+ return self.status < 0x0100
118
+
119
+ def group(self, tag: int) -> dict[str, Any]:
120
+ """Merge every group with this delimiter tag (first wins)."""
121
+ merged: dict[str, Any] = {}
122
+ for gtag, attrs in self.groups:
123
+ if gtag == tag:
124
+ for k, v in attrs.items():
125
+ merged.setdefault(k, v)
126
+ return merged
127
+
128
+ def groups_of(self, tag: int) -> list[dict[str, Any]]:
129
+ return [attrs for gtag, attrs in self.groups if gtag == tag]
130
+
131
+ @property
132
+ def printer(self) -> dict[str, Any]:
133
+ return self.group(TAG_PRINTER)
134
+
135
+ @property
136
+ def operation(self) -> dict[str, Any]:
137
+ return self.group(TAG_OPERATION)
138
+
139
+
140
+ # --- Encoding ----------------------------------------------------------------
141
+
142
+
143
+ def _encode_value(tag: int, value: Any) -> bytes:
144
+ if tag in (INTEGER, ENUM):
145
+ return struct.pack(">i", int(value))
146
+ if tag == BOOLEAN:
147
+ return b"\x01" if value else b"\x00"
148
+ if tag in (NO_VALUE, UNKNOWN, UNSUPPORTED):
149
+ return b""
150
+ if tag == RANGE:
151
+ lo, hi = value
152
+ return struct.pack(">ii", lo, hi)
153
+ if tag == RESOLUTION:
154
+ r = value if isinstance(value, Resolution) else Resolution(*value)
155
+ return struct.pack(">iib", r.x, r.y, r.units)
156
+ if isinstance(value, bytes):
157
+ return value
158
+ return str(value).encode("utf-8")
159
+
160
+
161
+ def _encode_attr(name: str, tag: int, value: Any) -> bytes:
162
+ values = value if isinstance(value, list) else [value]
163
+ out = bytearray()
164
+ for i, v in enumerate(values):
165
+ n = name.encode() if i == 0 else b""
166
+ if tag == BEG_COLLECTION:
167
+ out += struct.pack(">BH", BEG_COLLECTION, len(n)) + n + struct.pack(">H", 0)
168
+ for member_name, (member_tag, member_value) in v.items():
169
+ mn = member_name.encode()
170
+ out += struct.pack(">BHH", MEMBER_NAME, 0, len(mn)) + mn
171
+ member = _encode_attr("", member_tag, member_value)
172
+ out += member
173
+ out += struct.pack(">BHH", END_COLLECTION, 0, 0)
174
+ else:
175
+ data = _encode_value(tag, v)
176
+ out += struct.pack(">BH", tag, len(n)) + n + struct.pack(">H", len(data)) + data
177
+ return bytes(out)
178
+
179
+
180
+ def encode_request(
181
+ operation: int,
182
+ printer_uri: str,
183
+ *,
184
+ request_id: int = 1,
185
+ version: tuple[int, int] = (1, 1),
186
+ operation_attrs: list[Attr] | None = None,
187
+ job_attrs: list[Attr] | None = None,
188
+ data: bytes = b"",
189
+ ) -> bytes:
190
+ """Build a complete IPP request message (header + groups + optional document data)."""
191
+ out = bytearray(struct.pack(">BBHI", version[0], version[1], operation, request_id))
192
+ out.append(TAG_OPERATION)
193
+ out += _encode_attr("attributes-charset", CHARSET, "utf-8")
194
+ out += _encode_attr("attributes-natural-language", LANGUAGE, "en")
195
+ out += _encode_attr("printer-uri", URI, printer_uri)
196
+ for a in operation_attrs or []:
197
+ out += _encode_attr(a.name, a.tag, a.value)
198
+ if job_attrs:
199
+ out.append(TAG_JOB)
200
+ for a in job_attrs:
201
+ out += _encode_attr(a.name, a.tag, a.value)
202
+ out.append(TAG_END)
203
+ return bytes(out) + data
204
+
205
+
206
+ # --- Decoding ----------------------------------------------------------------
207
+
208
+
209
+ def _decode_value(tag: int, raw: bytes) -> Any:
210
+ if tag in (INTEGER, ENUM):
211
+ return struct.unpack(">i", raw)[0] if len(raw) == 4 else None
212
+ if tag == BOOLEAN:
213
+ return bool(raw[0]) if raw else False
214
+ if tag in (NO_VALUE, UNKNOWN, UNSUPPORTED):
215
+ return None
216
+ if tag == RANGE and len(raw) == 8:
217
+ return struct.unpack(">ii", raw)
218
+ if tag == RESOLUTION and len(raw) == 9:
219
+ return Resolution(*struct.unpack(">iib", raw))
220
+ if tag == DATETIME and len(raw) == 11:
221
+ y, mo, d, h, mi, s, ds, sign, oh, om = struct.unpack(">HBBBBBBcBB", raw)
222
+ offset = timedelta(hours=oh, minutes=om) * (-1 if sign == b"-" else 1)
223
+ return datetime(y, mo, d, h, mi, s, ds * 100000, tzinfo=timezone(offset))
224
+ if tag in (TEXT_WITH_LANG, NAME_WITH_LANG) and len(raw) >= 4:
225
+ lang_len = struct.unpack(">H", raw[:2])[0]
226
+ text_len = struct.unpack(">H", raw[2 + lang_len : 4 + lang_len])[0]
227
+ return raw[4 + lang_len : 4 + lang_len + text_len].decode("utf-8", "replace")
228
+ # Strings and octetStrings: decode as UTF-8 text (printer octetStrings are textual in practice).
229
+ return raw.decode("utf-8", "replace")
230
+
231
+
232
+ class _Reader:
233
+ def __init__(self, data: bytes):
234
+ self.data = data
235
+ self.pos = 0
236
+
237
+ def take(self, n: int) -> bytes:
238
+ if self.pos + n > len(self.data):
239
+ raise IPPError("truncated IPP message")
240
+ chunk = self.data[self.pos : self.pos + n]
241
+ self.pos += n
242
+ return chunk
243
+
244
+ def u8(self) -> int:
245
+ return self.take(1)[0]
246
+
247
+ def u16(self) -> int:
248
+ return struct.unpack(">H", self.take(2))[0]
249
+
250
+ def peek(self) -> int:
251
+ if self.pos >= len(self.data):
252
+ raise IPPError("truncated IPP message")
253
+ return self.data[self.pos]
254
+
255
+
256
+ def _read_collection(r: _Reader) -> dict[str, Any]:
257
+ """Read members after a begCollection header until the matching endCollection."""
258
+ result: dict[str, Any] = {}
259
+ current: str | None = None
260
+ while True:
261
+ tag = r.u8()
262
+ r.take(r.u16()) # name (always empty inside collections)
263
+ raw = r.take(r.u16())
264
+ if tag == END_COLLECTION:
265
+ return result
266
+ if tag == MEMBER_NAME:
267
+ current = raw.decode("utf-8", "replace")
268
+ continue
269
+ value = _read_collection(r) if tag == BEG_COLLECTION else _decode_value(tag, raw)
270
+ if current is None:
271
+ continue
272
+ if current in result: # additional value of a 1setOf member
273
+ existing = result[current]
274
+ result[current] = (existing if isinstance(existing, list) else [existing]) + [value]
275
+ else:
276
+ result[current] = value
277
+
278
+
279
+ def decode_response(data: bytes) -> Response:
280
+ """Decode an IPP response. Multi-valued attributes become lists."""
281
+ r = _Reader(data)
282
+ major, minor = r.u8(), r.u8()
283
+ status = r.u16()
284
+ request_id = struct.unpack(">I", r.take(4))[0]
285
+ resp = Response((major, minor), status, request_id)
286
+ group: dict[str, Any] | None = None
287
+ last_name: str | None = None
288
+ while r.pos < len(data):
289
+ tag = r.u8()
290
+ if tag == TAG_END:
291
+ break
292
+ if tag in DELIMITERS:
293
+ group = {}
294
+ resp.groups.append((tag, group))
295
+ last_name = None
296
+ continue
297
+ if group is None:
298
+ raise IPPError("attribute outside of a group")
299
+ name = r.take(r.u16()).decode("utf-8", "replace")
300
+ raw = r.take(r.u16())
301
+ value = _read_collection(r) if tag == BEG_COLLECTION else _decode_value(tag, raw)
302
+ if name:
303
+ last_name = name
304
+ group[name] = value
305
+ elif last_name is not None: # additional value → 1setOf
306
+ existing = group[last_name]
307
+ group[last_name] = (existing if isinstance(existing, list) else [existing]) + [value]
308
+ return resp
309
+
310
+
311
+ def as_list(value: Any) -> list[Any]:
312
+ """Normalise a decoded attribute to a list (1setOf with one value decodes as a scalar)."""
313
+ if value is None:
314
+ return []
315
+ return value if isinstance(value, list) else [value]
316
+
317
+
318
+ # --- HTTP client --------------------------------------------------------------
319
+
320
+
321
+ class IPPClient:
322
+ """Synchronous IPP over HTTP(S). TLS verification is skipped only for this printer host,
323
+ because embedded printers ship self-signed certificates."""
324
+
325
+ def __init__(self, host: str, port: int = 631, path: str = "/ipp/print", tls: bool = False,
326
+ timeout: float = 5.0):
327
+ self.host, self.port, self.path, self.tls = host, port, path, tls
328
+ self.timeout = timeout
329
+ self._request_id = 0
330
+
331
+ @property
332
+ def printer_uri(self) -> str:
333
+ scheme = "ipps" if self.tls else "ipp"
334
+ return f"{scheme}://{self.host}:{self.port}{self.path}"
335
+
336
+ @property
337
+ def http_url(self) -> str:
338
+ scheme = "https" if self.tls else "http"
339
+ return f"{scheme}://{self.host}:{self.port}{self.path}"
340
+
341
+ def request(self, operation: int, *, operation_attrs: list[Attr] | None = None,
342
+ job_attrs: list[Attr] | None = None, data: bytes = b"",
343
+ timeout: float | None = None) -> Response:
344
+ self._request_id += 1
345
+ body = encode_request(operation, self.printer_uri, request_id=self._request_id,
346
+ operation_attrs=operation_attrs, job_attrs=job_attrs, data=data)
347
+ trace(f"IPP → {OP_NAMES.get(operation, hex(operation))} {self.http_url} ({len(body)} bytes)")
348
+ with httpx.Client(verify=False, timeout=timeout or self.timeout) as client:
349
+ http = client.post(self.http_url, content=body,
350
+ headers={"Content-Type": "application/ipp"})
351
+ if http.status_code != 200:
352
+ raise IPPError(f"HTTP {http.status_code} from {self.http_url}")
353
+ resp = decode_response(http.content)
354
+ trace(f"IPP ← status 0x{resp.status:04x} ({len(http.content)} bytes)")
355
+ if not resp.ok:
356
+ msg = resp.operation.get("status-message") or f"IPP status 0x{resp.status:04x}"
357
+ raise IPPError(str(msg), resp.status)
358
+ return resp
359
+
360
+ def get_printer_attributes(self, requested: list[str] | None = None) -> dict[str, Any]:
361
+ resp = self.request(OP_GET_PRINTER_ATTRIBUTES, operation_attrs=[
362
+ Attr("requested-attributes", KEYWORD, requested or ["all"]),
363
+ ])
364
+ return resp.printer