feat(printkit): 增强 IPP 打印与表格排版,发布 0.1.2
This commit is contained in:
@@ -71,6 +71,13 @@ p.supports("sides-supported", "two-sided-long-edge")
|
|||||||
`ipp-attribute-fidelity=true`,设备也只回 `successful-ok` 然后静默按单面打。
|
`ipp-attribute-fidelity=true`,设备也只回 `successful-ok` 然后静默按单面打。
|
||||||
所以 SDK 在客户端侧做能力预检并降级(`Printer._adjust`),并打日志。
|
所以 SDK 在客户端侧做能力预检并降级(`Printer._adjust`),并打日志。
|
||||||
4. **一张连续表跨页**,不是每人一单:行不跨页拆断,表头每页重复,续页页脚带「(续)」。
|
4. **一张连续表跨页**,不是每人一单:行不跨页拆断,表头每页重复,续页页脚带「(续)」。
|
||||||
|
5. **设备一次只吃一份作业**。上一份还没出完纸就提交下一份,回 `0x0507
|
||||||
|
server-error-busy`(日志「Print-Job 失败: 0x0507 server-error-busy」)。所以
|
||||||
|
`Printer.print()` 逐页等出纸再提交下一页、`print_job()` 对忙状态先
|
||||||
|
`wait_idle()` 再退避重试(`busy_retries` / `busy_wait` / `page_wait` 可调);
|
||||||
|
参数错、格式不支持这类硬错误立即抛,不重试。
|
||||||
|
6. **多页中途失败不要去整份重打**:异常的 `printed_pages` / `total_pages` 属性
|
||||||
|
说明已经出了几页,重打整份会重复出纸。
|
||||||
|
|
||||||
## 依赖
|
## 依赖
|
||||||
|
|
||||||
|
|||||||
+10
-5
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"schema_version": 1,
|
"schema_version": 1,
|
||||||
"sdk_id": "printkit",
|
"sdk_id": "printkit",
|
||||||
"version": "0.1.1",
|
"version": "0.1.2",
|
||||||
"modules": {
|
"modules": {
|
||||||
"printkit": {
|
"printkit": {
|
||||||
"exports": [
|
"exports": [
|
||||||
@@ -54,7 +54,7 @@
|
|||||||
],
|
],
|
||||||
"signatures": {
|
"signatures": {
|
||||||
"IppError": "(status_code: 'int', status_text: 'str', operation: 'str' = '')",
|
"IppError": "(status_code: 'int', status_text: 'str', operation: 'str' = '')",
|
||||||
"Printer": "(target: 'str | None' = None, *, timeout: 'float' = 30.0, log=None, info: 'PrinterInfo | None' = None)",
|
"Printer": "(target: 'str | None' = None, *, timeout: 'float' = 30.0, log=None, info: 'PrinterInfo | None' = None, busy_retries: 'int' = 4, busy_wait: 'float' = 8.0, page_wait: 'float' = 120.0, page_interval: 'float' = 2.0)",
|
||||||
"PrinterInfo": "(id: 'str', ip: 'str', name: 'str' = '', port: 'int' = 631, path: 'str' = '/ipp/print', secure: 'bool' = True, note: 'str' = '', extra: 'dict' = <factory>) -> None",
|
"PrinterInfo": "(id: 'str', ip: 'str', name: 'str' = '', port: 'int' = 631, path: 'str' = '/ipp/print', secure: 'bool' = True, note: 'str' = '', extra: 'dict' = <factory>) -> None",
|
||||||
"configure": "(path: 'str | os.PathLike | None' = None, printers: 'list[dict] | None' = None, default: 'str | None' = None) -> 'list[dict]'",
|
"configure": "(path: 'str | os.PathLike | None' = None, printers: 'list[dict] | None' = None, default: 'str | None' = None) -> 'list[dict]'",
|
||||||
"default_id": "() -> 'str'",
|
"default_id": "() -> 'str'",
|
||||||
@@ -80,7 +80,7 @@
|
|||||||
],
|
],
|
||||||
"all": [],
|
"all": [],
|
||||||
"signatures": {
|
"signatures": {
|
||||||
"Printer": "(target: 'str | None' = None, *, timeout: 'float' = 30.0, log=None, info: 'PrinterInfo | None' = None)",
|
"Printer": "(target: 'str | None' = None, *, timeout: 'float' = 30.0, log=None, info: 'PrinterInfo | None' = None, busy_retries: 'int' = 4, busy_wait: 'float' = 8.0, page_wait: 'float' = 120.0, page_interval: 'float' = 2.0)",
|
||||||
"cmd_info": "(args) -> 'int'",
|
"cmd_info": "(args) -> 'int'",
|
||||||
"cmd_list": "(args) -> 'int'",
|
"cmd_list": "(args) -> 'int'",
|
||||||
"cmd_send": "(args, use_sheet: 'bool') -> 'int'",
|
"cmd_send": "(args, use_sheet: 'bool') -> 'int'",
|
||||||
@@ -126,7 +126,7 @@
|
|||||||
"signatures": {
|
"signatures": {
|
||||||
"IppError": "(status_code: 'int', status_text: 'str', operation: 'str' = '')",
|
"IppError": "(status_code: 'int', status_text: 'str', operation: 'str' = '')",
|
||||||
"Path": "(*args, **kwargs)",
|
"Path": "(*args, **kwargs)",
|
||||||
"Printer": "(target: 'str | None' = None, *, timeout: 'float' = 30.0, log=None, info: 'PrinterInfo | None' = None)",
|
"Printer": "(target: 'str | None' = None, *, timeout: 'float' = 30.0, log=None, info: 'PrinterInfo | None' = None, busy_retries: 'int' = 4, busy_wait: 'float' = 8.0, page_wait: 'float' = 120.0, page_interval: 'float' = 2.0)",
|
||||||
"PrinterInfo": "(id: 'str', ip: 'str', name: 'str' = '', port: 'int' = 631, path: 'str' = '/ipp/print', secure: 'bool' = True, note: 'str' = '', extra: 'dict' = <factory>) -> None",
|
"PrinterInfo": "(id: 'str', ip: 'str', name: 'str' = '', port: 'int' = 631, path: 'str' = '/ipp/print', secure: 'bool' = True, note: 'str' = '', extra: 'dict' = <factory>) -> None",
|
||||||
"default_printer": "(**kw) -> 'Printer'"
|
"default_printer": "(**kw) -> 'Printer'"
|
||||||
}
|
}
|
||||||
@@ -156,6 +156,7 @@
|
|||||||
"OP_PRINT_JOB",
|
"OP_PRINT_JOB",
|
||||||
"OP_SEND_DOCUMENT",
|
"OP_SEND_DOCUMENT",
|
||||||
"OP_VALIDATE_JOB",
|
"OP_VALIDATE_JOB",
|
||||||
|
"RETRYABLE_CODES",
|
||||||
"STATUS_TEXT",
|
"STATUS_TEXT",
|
||||||
"SUCCESS_CODES",
|
"SUCCESS_CODES",
|
||||||
"T_BOOLEAN",
|
"T_BOOLEAN",
|
||||||
@@ -177,10 +178,12 @@
|
|||||||
"build_request",
|
"build_request",
|
||||||
"decode_value",
|
"decode_value",
|
||||||
"flatten",
|
"flatten",
|
||||||
|
"is_retryable",
|
||||||
"parse_response",
|
"parse_response",
|
||||||
"post",
|
"post",
|
||||||
"socket",
|
"socket",
|
||||||
"ssl",
|
"ssl",
|
||||||
|
"status_text",
|
||||||
"struct"
|
"struct"
|
||||||
],
|
],
|
||||||
"all": [],
|
"all": [],
|
||||||
@@ -189,8 +192,10 @@
|
|||||||
"build_request": "(op: 'int', uri: 'str', operation_attrs: 'list[bytes] | None' = None, job_attrs: 'list[bytes] | None' = None, req_id: 'int' = 1, user: 'str' = '37du-plugin') -> 'bytes'",
|
"build_request": "(op: 'int', uri: 'str', operation_attrs: 'list[bytes] | None' = None, job_attrs: 'list[bytes] | None' = None, req_id: 'int' = 1, user: 'str' = '37du-plugin') -> 'bytes'",
|
||||||
"decode_value": "(tag: 'int', raw: 'bytes')",
|
"decode_value": "(tag: 'int', raw: 'bytes')",
|
||||||
"flatten": "(attrs: 'dict[str, list[tuple[int, bytes]]]') -> 'dict[str, list]'",
|
"flatten": "(attrs: 'dict[str, list[tuple[int, bytes]]]') -> 'dict[str, list]'",
|
||||||
|
"is_retryable": "(status: 'int') -> 'bool'",
|
||||||
"parse_response": "(payload: 'bytes') -> 'tuple[int, dict[str, list[tuple[int, bytes]]]]'",
|
"parse_response": "(payload: 'bytes') -> 'tuple[int, dict[str, list[tuple[int, bytes]]]]'",
|
||||||
"post": "(host: 'str', port: 'int', path: 'str', body: 'bytes', document: 'bytes' = b'', secure: 'bool' = True, timeout: 'float' = 30.0) -> 'tuple[int, bytes]'"
|
"post": "(host: 'str', port: 'int', path: 'str', body: 'bytes', document: 'bytes' = b'', secure: 'bool' = True, timeout: 'float' = 30.0) -> 'tuple[int, bytes]'",
|
||||||
|
"status_text": "(status: 'int') -> 'str'"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"printkit.registry": {
|
"printkit.registry": {
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ id 型号 部门(备注) 地址 / 说明
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
__version__ = "0.1.1"
|
__version__ = "0.1.2"
|
||||||
|
|
||||||
from . import client, errors, ipp, registry, render, sheet
|
from . import client, errors, ipp, registry, render, sheet
|
||||||
from .client import Printer, default_printer
|
from .client import Printer, default_printer
|
||||||
|
|||||||
@@ -230,6 +230,99 @@ def _render_jpeg():
|
|||||||
return f"{len(pages)} 页 {len(pages[0])/1024:.0f}KB"
|
return f"{len(pages)} 页 {len(pages[0])/1024:.0f}KB"
|
||||||
|
|
||||||
|
|
||||||
|
@case("ipp:忙状态可读可辨识")
|
||||||
|
def _ipp_status_text():
|
||||||
|
assert ipp.status_text(0x0507) == "server-error-busy", ipp.status_text(0x0507)
|
||||||
|
assert ipp.is_retryable(0x0507) and ipp.is_retryable(0x0506)
|
||||||
|
assert not ipp.is_retryable(0x0409), "格式不支持属于硬错误,不能重试"
|
||||||
|
# 未知码不能回落成空串(否则日志里会出现「0x0507 0x0507」这种重复)
|
||||||
|
assert ipp.status_text(0x0FFF) == "0x0FFF", ipp.status_text(0x0FFF)
|
||||||
|
return "ok"
|
||||||
|
|
||||||
|
|
||||||
|
@case("client:0x0507 设备忙 → 退避重试后成功")
|
||||||
|
def _client_busy_retry():
|
||||||
|
from .client import Printer
|
||||||
|
from .errors import IppError
|
||||||
|
|
||||||
|
p = Printer("l6570")
|
||||||
|
p._caps = {"sides-supported": ["one-sided"],
|
||||||
|
"document-format-supported": ["image/jpeg"]}
|
||||||
|
p.busy_wait = 0.0
|
||||||
|
p.page_wait = 0.0
|
||||||
|
waits = []
|
||||||
|
|
||||||
|
def fake_idle(timeout=0.0, interval=0.0):
|
||||||
|
waits.append(timeout)
|
||||||
|
return True
|
||||||
|
|
||||||
|
p.wait_idle = fake_idle
|
||||||
|
|
||||||
|
calls = {"n": 0}
|
||||||
|
|
||||||
|
def fake_request(op, operation_attrs=None, job_attrs=None,
|
||||||
|
document=b"", doc_format=None):
|
||||||
|
calls["n"] += 1
|
||||||
|
if calls["n"] < 3: # 前两次设备忙
|
||||||
|
return 0x0507, {}
|
||||||
|
return 0x0000, {"job-id": [11]}
|
||||||
|
|
||||||
|
p._request = fake_request
|
||||||
|
r = p.print_job(b"\xff\xd8jpg", "image/jpeg", "t")
|
||||||
|
assert r["ok"] and calls["n"] == 3, (r, calls)
|
||||||
|
assert waits, "忙重试前应当等打印机空闲"
|
||||||
|
|
||||||
|
# 硬错误(参数/格式)立即抛,不浪费时间重试
|
||||||
|
calls["n"] = 0
|
||||||
|
|
||||||
|
def hard_error(op, operation_attrs=None, job_attrs=None,
|
||||||
|
document=b"", doc_format=None):
|
||||||
|
calls["n"] += 1
|
||||||
|
return 0x0409, {}
|
||||||
|
|
||||||
|
p._request = hard_error
|
||||||
|
try:
|
||||||
|
p.print_job(b"\xff\xd8jpg", "image/jpeg", "t")
|
||||||
|
except IppError as e:
|
||||||
|
assert e.status_code == 0x0409 and calls["n"] == 1, (e, calls)
|
||||||
|
else:
|
||||||
|
raise AssertionError("0x0409 应当直接抛 IppError")
|
||||||
|
return "ok"
|
||||||
|
|
||||||
|
|
||||||
|
@case("client:多页中断不重复出纸(失败带已出页数)")
|
||||||
|
def _client_partial_pages():
|
||||||
|
from . import render
|
||||||
|
from .client import Printer
|
||||||
|
|
||||||
|
p = Printer("l6570")
|
||||||
|
p._caps = {"document-format-supported": ["image/jpeg"]}
|
||||||
|
pages = [b"\xff\xd8a", b"\xff\xd8b", b"\xff\xd8c"]
|
||||||
|
served = []
|
||||||
|
old = render.to_jpegs
|
||||||
|
render.to_jpegs = lambda src, dpi=300, quality=92: pages
|
||||||
|
p.wait_idle = lambda timeout=120.0, interval=2.0: True
|
||||||
|
|
||||||
|
def fake_job(document, doc_format="image/jpeg", job_name="x", **opts):
|
||||||
|
if len(served) == 1: # 第 2 页失败
|
||||||
|
raise OSError("打印机掉线")
|
||||||
|
served.append(document)
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
p.print_job = fake_job
|
||||||
|
try:
|
||||||
|
p.print("x.pdf")
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
assert getattr(e, "printed_pages", None) == 1, e
|
||||||
|
assert getattr(e, "total_pages", None) == 3, e
|
||||||
|
else:
|
||||||
|
raise AssertionError("第 2 页失败应当抛异常")
|
||||||
|
finally:
|
||||||
|
render.to_jpegs = old
|
||||||
|
assert served == [pages[0]], served
|
||||||
|
return "ok"
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- #
|
# --------------------------------------------------------------------------- #
|
||||||
def main(argv: list[str] | None = None) -> int:
|
def main(argv: list[str] | None = None) -> int:
|
||||||
argv = list(sys.argv[1:] if argv is None else argv)
|
argv = list(sys.argv[1:] if argv is None else argv)
|
||||||
|
|||||||
@@ -33,12 +33,20 @@ class Printer:
|
|||||||
"""一台打印机的会话对象(无连接状态,可反复复用)。"""
|
"""一台打印机的会话对象(无连接状态,可反复复用)。"""
|
||||||
|
|
||||||
def __init__(self, target: str | None = None, *, timeout: float = 30.0,
|
def __init__(self, target: str | None = None, *, timeout: float = 30.0,
|
||||||
log=None, info: PrinterInfo | None = None):
|
log=None, info: PrinterInfo | None = None,
|
||||||
|
busy_retries: int = 4, busy_wait: float = 8.0,
|
||||||
|
page_wait: float = 120.0, page_interval: float = 2.0):
|
||||||
self.info = info or registry.resolve(target)
|
self.info = info or registry.resolve(target)
|
||||||
self.timeout = timeout
|
self.timeout = timeout
|
||||||
self.log = log
|
self.log = log
|
||||||
self._caps: dict | None = None
|
self._caps: dict | None = None
|
||||||
self._req_id = 0
|
self._req_id = 0
|
||||||
|
#: 设备回 0x0507/server-error-busy 时的重试次数与退避间隔
|
||||||
|
self.busy_retries = max(1, int(busy_retries))
|
||||||
|
self.busy_wait = float(busy_wait)
|
||||||
|
#: 等一页/一份真正出完纸的上限(秒)与轮询间隔
|
||||||
|
self.page_wait = float(page_wait)
|
||||||
|
self.page_interval = float(page_interval)
|
||||||
|
|
||||||
# --- 基础信息 ---------------------------------------------------------- #
|
# --- 基础信息 ---------------------------------------------------------- #
|
||||||
@property
|
@property
|
||||||
@@ -79,13 +87,17 @@ class Printer:
|
|||||||
ipp.OP_GET_PRINTER_ATTRIBUTES,
|
ipp.OP_GET_PRINTER_ATTRIBUTES,
|
||||||
[ipp.attr(ipp.T_KEYWORD, b"requested-attributes", b"all")])
|
[ipp.attr(ipp.T_KEYWORD, b"requested-attributes", b"all")])
|
||||||
if status not in ipp.SUCCESS_CODES:
|
if status not in ipp.SUCCESS_CODES:
|
||||||
raise IppError(status, ipp.STATUS_TEXT.get(status, "?"), "Get-Printer-Attributes")
|
raise IppError(status, ipp.status_text(status), "Get-Printer-Attributes")
|
||||||
self._caps = attrs
|
self._caps = attrs
|
||||||
return self._caps
|
return self._caps
|
||||||
|
|
||||||
def state(self) -> dict:
|
def state(self, refresh: bool = True) -> dict:
|
||||||
"""设备状态摘要。"""
|
"""设备状态摘要。
|
||||||
c = self.caps()
|
|
||||||
|
``refresh=True``(默认)每次现读一次 Get-Printer-Attributes:
|
||||||
|
排队数/状态必须是最新的,否则 :meth:`wait_idle` 会一直看着缓存里的旧值。
|
||||||
|
"""
|
||||||
|
c = self.caps(refresh=refresh)
|
||||||
s = (c.get("printer-state") or [0])[0]
|
s = (c.get("printer-state") or [0])[0]
|
||||||
return {
|
return {
|
||||||
"state": {3: "idle", 4: "processing", 5: "stopped"}.get(s, str(s)),
|
"state": {3: "idle", 4: "processing", 5: "stopped"}.get(s, str(s)),
|
||||||
@@ -129,14 +141,39 @@ class Printer:
|
|||||||
# --- 作业 -------------------------------------------------------------- #
|
# --- 作业 -------------------------------------------------------------- #
|
||||||
def print_job(self, document: bytes, doc_format: str = "image/jpeg",
|
def print_job(self, document: bytes, doc_format: str = "image/jpeg",
|
||||||
job_name: str = "printkit", **opts) -> dict:
|
job_name: str = "printkit", **opts) -> dict:
|
||||||
"""提交一个原始作业(字节流)。真正出纸。"""
|
"""提交一个原始作业(字节流)。真正出纸。
|
||||||
|
|
||||||
|
设备忙(``0x0507 server-error-busy`` 等)是**临时性拒绝**:上一份还在出纸,
|
||||||
|
这时提交会被直接打回。这里先等队列排空再退避重试,最多 ``busy_retries`` 次;
|
||||||
|
参数错、格式不支持这类硬错误立即抛,不浪费纸。
|
||||||
|
"""
|
||||||
self._check_format(doc_format)
|
self._check_format(doc_format)
|
||||||
opts = self._adjust(opts)
|
opts = self._adjust(opts)
|
||||||
job_attrs = [ipp.attr(ipp.T_NAME, b"job-name", job_name.encode("utf-8"))]
|
job_attrs = [ipp.attr(ipp.T_NAME, b"job-name", job_name.encode("utf-8"))]
|
||||||
job_attrs += _job_options(**opts)
|
job_attrs += _job_options(**opts)
|
||||||
status, attrs = self._request(ipp.OP_PRINT_JOB, [], job_attrs,
|
status, attrs = -1, {}
|
||||||
document=document, doc_format=doc_format)
|
for attempt in range(1, self.busy_retries + 1):
|
||||||
return _job_result(self, "Print-Job", status, attrs, len(document))
|
status, attrs = self._request(ipp.OP_PRINT_JOB, [], job_attrs,
|
||||||
|
document=document, doc_format=doc_format)
|
||||||
|
if status in ipp.SUCCESS_CODES or not ipp.is_retryable(status):
|
||||||
|
return _job_result(self, "Print-Job", status, attrs, len(document))
|
||||||
|
if attempt >= self.busy_retries:
|
||||||
|
break
|
||||||
|
self._say(f"[printkit] {self.info.id} 第 {attempt} 次提交被拒:"
|
||||||
|
f"{ipp.status_text(status)}(设备忙),等出完纸后重试")
|
||||||
|
self.wait_idle(timeout=self.page_wait, interval=self.page_interval)
|
||||||
|
time.sleep(self.busy_wait)
|
||||||
|
# 重试用尽仍被判忙:把设备自报状态一并带出(缺纸/开盖也表现为拒收作业)
|
||||||
|
hint = ""
|
||||||
|
try:
|
||||||
|
st = self.state()
|
||||||
|
hint = f"(设备 {st.get('state', '?')}"
|
||||||
|
if st.get("reasons"):
|
||||||
|
hint += ":" + "、".join(str(r) for r in st["reasons"][:3])
|
||||||
|
hint += ")"
|
||||||
|
except PrintKitError:
|
||||||
|
pass
|
||||||
|
raise IppError(status, f"{ipp.status_text(status)}{hint}", "Print-Job")
|
||||||
|
|
||||||
def validate_job(self, document: bytes, doc_format: str = "image/jpeg",
|
def validate_job(self, document: bytes, doc_format: str = "image/jpeg",
|
||||||
job_name: str = "printkit-validate", **opts) -> dict:
|
job_name: str = "printkit-validate", **opts) -> dict:
|
||||||
@@ -165,10 +202,21 @@ class Printer:
|
|||||||
results = []
|
results = []
|
||||||
for i, pg in enumerate(pages, 1):
|
for i, pg in enumerate(pages, 1):
|
||||||
name = f"{job_name}-p{i}"
|
name = f"{job_name}-p{i}"
|
||||||
if dry_run:
|
try:
|
||||||
results.append(self.validate_job(pg, "image/jpeg", name, **opts))
|
if dry_run:
|
||||||
else:
|
results.append(self.validate_job(pg, "image/jpeg", name, **opts))
|
||||||
results.append(self.print_job(pg, "image/jpeg", name, **opts))
|
else:
|
||||||
|
results.append(self.print_job(pg, "image/jpeg", name, **opts))
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
# 告诉调用方已经出过几页:外层据此决定能不能整份重打,
|
||||||
|
# 否则第 2 页失败后重打整份会把第 1 页再打一遍(废纸/重单)。
|
||||||
|
e.printed_pages = len(results)
|
||||||
|
e.total_pages = len(pages)
|
||||||
|
raise
|
||||||
|
# 一页一个作业:这台 EPSON 上一份没出完纸就收下一份会回 0x0507,
|
||||||
|
# 所以等本页真出完再提交下一页(单页文档无需等待)。
|
||||||
|
if not dry_run and i < len(pages):
|
||||||
|
self.wait_idle(timeout=self.page_wait, interval=self.page_interval)
|
||||||
return {"pages": results, "ok": all(r["ok"] for r in results)}
|
return {"pages": results, "ok": all(r["ok"] for r in results)}
|
||||||
|
|
||||||
def validate(self, src, *, dpi: int = 300, **opts) -> dict:
|
def validate(self, src, *, dpi: int = 300, **opts) -> dict:
|
||||||
@@ -195,7 +243,7 @@ class Printer:
|
|||||||
ipp.attr(ipp.T_INTEGER, b"limit", limit),
|
ipp.attr(ipp.T_INTEGER, b"limit", limit),
|
||||||
])
|
])
|
||||||
if status not in ipp.SUCCESS_CODES:
|
if status not in ipp.SUCCESS_CODES:
|
||||||
raise IppError(status, ipp.STATUS_TEXT.get(status, "?"), "Get-Jobs")
|
raise IppError(status, ipp.status_text(status), "Get-Jobs")
|
||||||
ids = attrs.get("job-id") or []
|
ids = attrs.get("job-id") or []
|
||||||
states = attrs.get("job-state") or []
|
states = attrs.get("job-state") or []
|
||||||
uris = attrs.get("job-uri") or []
|
uris = attrs.get("job-uri") or []
|
||||||
@@ -205,14 +253,28 @@ class Printer:
|
|||||||
for i in range(max(len(ids), len(states), len(uris)))]
|
for i in range(max(len(ids), len(states), len(uris)))]
|
||||||
|
|
||||||
def wait_idle(self, timeout: float = 120.0, interval: float = 2.0) -> bool:
|
def wait_idle(self, timeout: float = 120.0, interval: float = 2.0) -> bool:
|
||||||
"""等待队列清空(打印完成后返回 True,超时 False)。"""
|
"""等待当前作业出完纸(队列清空返回 True,超时 False)。
|
||||||
deadline = time.time() + timeout
|
|
||||||
while time.time() < deadline:
|
设备停在 ``stopped``(缺纸/卡纸/开盖)时不空等:直接返回 False,
|
||||||
st = self.state()
|
否则 :meth:`print_job` 的忙重试会把次数全耗在这上面。
|
||||||
if st["state"] == "idle" and st["queued"] == 0:
|
"""
|
||||||
|
deadline = time.time() + max(0.0, timeout)
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
st = self.state()
|
||||||
|
except PrintKitError as e: # noqa: BLE001
|
||||||
|
self._say(f"[printkit] {self.info.id} 读状态失败(继续等):{e}")
|
||||||
|
st = {}
|
||||||
|
if st.get("state") == "idle" and not st.get("queued"):
|
||||||
return True
|
return True
|
||||||
time.sleep(interval)
|
if st.get("state") == "stopped":
|
||||||
return False
|
self._say(f"[printkit] {self.info.id} 已停机"
|
||||||
|
f"({st.get('reasons') or '无原因上报'}),不再等待")
|
||||||
|
return False
|
||||||
|
left = deadline - time.time()
|
||||||
|
if left <= 0:
|
||||||
|
return False
|
||||||
|
time.sleep(max(0.2, min(interval, left)))
|
||||||
|
|
||||||
|
|
||||||
def _job_options(media=None, sides=None, color=None, copies=None,
|
def _job_options(media=None, sides=None, color=None, copies=None,
|
||||||
@@ -234,7 +296,7 @@ def _job_options(media=None, sides=None, color=None, copies=None,
|
|||||||
|
|
||||||
|
|
||||||
def _job_result(printer: Printer, op: str, status: int, attrs: dict, nbytes: int) -> dict:
|
def _job_result(printer: Printer, op: str, status: int, attrs: dict, nbytes: int) -> dict:
|
||||||
text = ipp.STATUS_TEXT.get(status, f"0x{status:04X}")
|
text = ipp.status_text(status)
|
||||||
ok = status in ipp.SUCCESS_CODES
|
ok = status in ipp.SUCCESS_CODES
|
||||||
if status not in ipp.SUCCESS_CODES:
|
if status not in ipp.SUCCESS_CODES:
|
||||||
raise IppError(status, text, op)
|
raise IppError(status, text, op)
|
||||||
|
|||||||
@@ -54,13 +54,38 @@ STATUS_TEXT = {
|
|||||||
0x0409: "client-error-document-format-not-supported",
|
0x0409: "client-error-document-format-not-supported",
|
||||||
0x040A: "client-error-attributes-or-values-not-supported",
|
0x040A: "client-error-attributes-or-values-not-supported",
|
||||||
0x040B: "client-error-uri-scheme-not-supported",
|
0x040B: "client-error-uri-scheme-not-supported",
|
||||||
|
0x040C: "client-error-charset-not-supported",
|
||||||
|
0x040D: "client-error-conflicting-attributes",
|
||||||
|
0x040E: "client-error-compression-not-supported",
|
||||||
|
0x040F: "client-error-compression-error",
|
||||||
0x0500: "server-error-internal-error",
|
0x0500: "server-error-internal-error",
|
||||||
0x0501: "server-error-operation-not-supported",
|
0x0501: "server-error-operation-not-supported",
|
||||||
0x0502: "server-error-service-unavailable",
|
0x0502: "server-error-service-unavailable",
|
||||||
|
0x0503: "server-error-version-not-supported",
|
||||||
|
0x0504: "server-error-device-error",
|
||||||
|
0x0505: "server-error-temporary-error",
|
||||||
|
0x0506: "server-error-not-accepting-jobs",
|
||||||
|
0x0507: "server-error-busy",
|
||||||
|
0x0508: "server-error-job-canceled",
|
||||||
|
0x0509: "server-error-multiple-document-jobs-not-supported",
|
||||||
}
|
}
|
||||||
|
|
||||||
SUCCESS_CODES = (0x0000, 0x0001, 0x0002)
|
SUCCESS_CODES = (0x0000, 0x0001, 0x0002)
|
||||||
|
|
||||||
|
#: 设备"临时性拒绝"状态码:等一下再提交就能过,属于可安全重试
|
||||||
|
#: (EPSON L6570/L565 上一份还在出纸时,新作业直接回 0x0507 server-error-busy)
|
||||||
|
RETRYABLE_CODES = (0x0502, 0x0505, 0x0506, 0x0507)
|
||||||
|
|
||||||
|
|
||||||
|
def status_text(status: int) -> str:
|
||||||
|
"""状态码 → 可读名;未知码回落 ``0xABCD``。"""
|
||||||
|
return STATUS_TEXT.get(status, f"0x{status:04X}")
|
||||||
|
|
||||||
|
|
||||||
|
def is_retryable(status: int) -> bool:
|
||||||
|
"""设备忙/暂不可用(可退避重试),区别于参数错、格式不支持这类硬错误。"""
|
||||||
|
return status in RETRYABLE_CODES
|
||||||
|
|
||||||
|
|
||||||
def attr(tag: int, name: bytes | str, value: bytes | str | int) -> bytes:
|
def attr(tag: int, name: bytes | str, value: bytes | str | int) -> bytes:
|
||||||
"""构造属性三元组:value-tag | name-len+name | value-len+value。"""
|
"""构造属性三元组:value-tag | name-len+name | value-len+value。"""
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "printkit"
|
name = "printkit"
|
||||||
version = "0.1.1"
|
version = "0.1.2"
|
||||||
description = "网络打印机直连打印 SDK:IPP over TLS,内置 EPSON L6570/L565,PDF/图片/Excel 表格打印"
|
description = "网络打印机直连打印 SDK:IPP over TLS,内置 EPSON L6570/L565,PDF/图片/Excel 表格打印"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.9"
|
requires-python = ">=3.9"
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"schema_version": 1,
|
"schema_version": 1,
|
||||||
"id": "printkit",
|
"id": "printkit",
|
||||||
"name": "网络打印 SDK",
|
"name": "网络打印 SDK",
|
||||||
"version": "0.1.1",
|
"version": "0.1.2",
|
||||||
"description": "网络打印机直连打印(IPP over TLS,无驱动无弹窗):内置 EPSON L6570/L565;PDF/图片栅格化、Excel·WPS 表格按列过滤排版成分页 PDF、Validate-Job 干跑校验、设备能力预检与参数降级",
|
"description": "网络打印机直连打印(IPP over TLS,无驱动无弹窗):内置 EPSON L6570/L565;PDF/图片栅格化、Excel·WPS 表格按列过滤排版成分页 PDF、Validate-Job 干跑校验、设备能力预检与参数降级",
|
||||||
"provides": [
|
"provides": [
|
||||||
"printkit"
|
"printkit"
|
||||||
|
|||||||
Reference in New Issue
Block a user