mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-26 04:27:21 +01:00
Compare commits
5 Commits
82fe807deb
...
ad3d70f197
| Author | SHA1 | Date | |
|---|---|---|---|
| ad3d70f197 | |||
| a438652aaa | |||
| 143dd9ff3d | |||
| cf44e54215 | |||
| 386ff25296 |
@ -0,0 +1,20 @@
|
||||
{
|
||||
"title": "Split brother_printer/cups_service.py under the 250-line cap",
|
||||
"objective": "Bring python_pkg/brother_printer/cups_service.py (406 lines) under the repo-wide 250-line cap by moving the IPP attribute queries, the CUPS status-code mapping and the CUPS-based USB fallback query into a new _cups_fallback.py, leaving cups_service holding only service control and raw USB port status.",
|
||||
"acceptance_criteria": [
|
||||
"cups_service.py and the new _cups_fallback.py are each at most 250 lines.",
|
||||
"The brother_printer suite still reports exactly 402 passing tests -- the same count as before the split, proving no test was dropped or silently skipped.",
|
||||
"The package keeps 100% branch coverage of the brother_printer source modules.",
|
||||
"test_cups_service.py, the largest of the four test modules, needs no edit at all: every name it imports and every collaborator it patches on MOD (fcntl, os, Path, shutil, subprocess, time) stays defined in cups_service.py.",
|
||||
"_get_cups_economode and find_cups_printer_name move together, because test_cups_service_part2.py imports both and patches shutil once on a single MOD; separating them would need two MOD constants in one test module.",
|
||||
"usb_query.py's late importlib.import_module call and the absolute patch target in test_usb_query.py both name the new module, so the CUPS fallback is still reached and still mocked.",
|
||||
"No assertion is changed and no test is deleted, skipped or weakened; the only test edits are the MOD constant, the import module path, and one absolute patch string.",
|
||||
"No suppression is added and no coverage exclusion is introduced."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Changing what any test asserts, or any status-code mapping behaviour.",
|
||||
"Splitting the brother_printer test files, which are separate commits -- part2 and part3 remain over the cap after this change.",
|
||||
"Adding a re-export shim in cups_service; importers point at the new module directly to keep the dependency direction one-way."
|
||||
],
|
||||
"verifier": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q (expects exactly 402 passed), plus pre-commit run --files on the touched files, plus bash ~/utils/scripts/check_file_length.sh --all for the cap."
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
{
|
||||
"title": "Split brother_printer/consumables.py under the 250-line cap",
|
||||
"objective": "Bring python_pkg/brother_printer/consumables.py (279 lines) under the repo-wide 250-line cap by moving the dropped-page detection into a new _page_delivery.py, while leaving every state-file primitive in consumables where two test modules patch it.",
|
||||
"acceptance_criteria": [
|
||||
"consumables.py and the new _page_delivery.py are each at most 250 lines.",
|
||||
"The brother_printer suite still reports exactly 402 passing tests -- the same count as before the split, proving no test was dropped or silently skipped.",
|
||||
"The package keeps 100% branch coverage of the brother_printer source modules.",
|
||||
"_load_consumable_state, _save_consumable_state, _get_cups_total_pages, CONSUMABLE_STATE_FILE and CUPS_PAGE_LOG stay defined in consumables.py, so test_consumables.py's patches still intercept every write that would otherwise reach ~/.config/brother_printer/state.json.",
|
||||
"~/.config/brother_printer/state.json is unmodified after a full suite run, checked by mtime rather than inferred from a green run.",
|
||||
"test_consumables.py needs no edit; test_consumables_part2.py gains a second MOD constant applied only to the two classes whose functions moved, never as a blanket substitution.",
|
||||
"No assertion is changed and no test is deleted, skipped or weakened.",
|
||||
"No suppression is added and no coverage exclusion is introduced."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Changing what any test asserts, or any counter-rebasing arithmetic.",
|
||||
"Moving the state-file primitives, which would risk a test writing to the live consumable state.",
|
||||
"Shrinking the module docstring, which records why the printer's counter is trusted over the CUPS page log.",
|
||||
"Splitting the brother_printer test files, which are separate commits."
|
||||
],
|
||||
"verifier": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q (expects exactly 402 passed), plus ls -la ~/.config/brother_printer/state.json to confirm the live state file was not written, plus pre-commit run --files on the touched files, plus bash ~/utils/scripts/check_file_length.sh --all for the cap."
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
{
|
||||
"title": "Split brother_printer/cups_queue.py under the 250-line cap",
|
||||
"objective": "Bring python_pkg/brother_printer/cups_queue.py (424 lines) under the repo-wide 250-line cap by moving the queue-status display and the interactive fix prompt into a new _queue_fix.py, chosen so the CUPS-mutating action primitives stay where their tests patch subprocess and time.",
|
||||
"acceptance_criteria": [
|
||||
"cups_queue.py and the new _queue_fix.py are each at most 250 lines.",
|
||||
"The brother_printer suite still reports exactly 402 passing tests -- the same count as before the split, proving no test was dropped or silently skipped.",
|
||||
"The package keeps 100% branch coverage of the brother_printer source modules.",
|
||||
"_cups_enable_printer, _cups_cancel_all_jobs, _cups_cancel_job and _cups_restart_service remain defined in cups_queue.py, so test_cups_queue.py's patches of subprocess, time, shutil and Path on that module still intercept every call that would otherwise reach the live CUPS daemon.",
|
||||
"No assertion is changed and no test is deleted, skipped or weakened; the only test edits are the MOD constant and the import module path following the moved code.",
|
||||
"No suppression is added and no coverage exclusion is introduced."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Changing what any test asserts, or what any display string contains.",
|
||||
"Splitting the brother_printer test files, which are separate commits.",
|
||||
"Moving the _cups_* primitives, which would let an unpatched subprocess.run restart the real CUPS service during the test run.",
|
||||
"Adding a re-export shim in cups_queue for display_cups_queue_status; importers point at the new module directly to keep the dependency direction one-way."
|
||||
],
|
||||
"verifier": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q (expects exactly 402 passed), plus pre-commit run --files on the touched files, plus bash ~/utils/scripts/check_file_length.sh --all for the cap."
|
||||
}
|
||||
@ -0,0 +1,48 @@
|
||||
{
|
||||
"intent": "Bring brother_printer/cups_service.py under the 250-line cap by moving the IPP queries, status-code mapping and CUPS-based USB fallback into their own module, with no behaviour change.",
|
||||
"scope": [
|
||||
"python_pkg/brother_printer/_cups_fallback.py (new)",
|
||||
"python_pkg/brother_printer/cups_service.py",
|
||||
"python_pkg/brother_printer/cups_queue.py, usb_query.py (import path only)",
|
||||
"python_pkg/brother_printer/tests/test_cups_service_part2.py, part3, part4 (MOD and import path only)",
|
||||
"python_pkg/brother_printer/tests/test_usb_query.py (one absolute patch target)",
|
||||
"Non-goal: no assertion changed, no test deleted, skipped or weakened"
|
||||
],
|
||||
"changes": [
|
||||
"Moved _parse_ipp_attributes, _get_cups_ipp_status, _get_cups_economode, _map_cups_to_status_code, _cups_reasons_to_error, _port_status_to_status_code, find_cups_printer_name and query_usb_via_cups verbatim into python_pkg/brother_printer/_cups_fallback.py.",
|
||||
"The seam is the whole IPP-onwards section rather than the section header at line 237: test_cups_service_part2.py imports both _get_cups_economode and find_cups_printer_name and patches shutil once, so those two had to travel together or that module would need two MOD constants.",
|
||||
"_cups_fallback imports _ensure_cups_running, _get_pyusb_device_info and _query_usb_port_status_raw from cups_service, so test_cups_service_part3.py can patch all five of its targets on one module.",
|
||||
"cups_service.py dropped the imports only the moved code used (re, printer_info_from_cups, run_command_text, estimate_consumable_life, USBResult, the three CUPS mapping tables and the three DERIVED_* codes) and its docstring now names the new module; 406 -> 234 lines.",
|
||||
"cups_queue.py imports find_cups_printer_name from _cups_fallback, and usb_query.py's late importlib.import_module now names _cups_fallback. test_usb_query.py patches that path absolutely, so its one patch string moved with it."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q",
|
||||
"result": "pass",
|
||||
"evidence": "402 passed before the split and 402 passed after it - identical pass count, not merely a green run."
|
||||
},
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -c \"from python_pkg.brother_printer import _cups_fallback as q, cups_service as c, cups_queue as cq; q._ensure_cups_running; q._query_usb_port_status_raw; q.find_cups_printer_name; q.shutil; q.subprocess; c.fcntl; c.os; c.Path; c.time; cq.find_cups_printer_name\"",
|
||||
"result": "pass",
|
||||
"evidence": "runtime probe OK - every name the four test modules patch is still a real attribute of the module they name, so ruff's TC001 rewrite trap did not fire."
|
||||
},
|
||||
{
|
||||
"command": "wc -l python_pkg/brother_printer/cups_service.py python_pkg/brother_printer/_cups_fallback.py",
|
||||
"result": "pass",
|
||||
"evidence": "234 and 209 lines, both under the 250-line cap in a single cut."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <the nine touched files>",
|
||||
"result": "pass",
|
||||
"evidence": "ruff, ruff format, mypy, pylint, bandit and pytest-with-coverage all pass on the touched files."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"usb_query.py reaches the fallback through a late importlib.import_module with the module path as a string, which no import checker validates. Covered by test_usb_query.py exercising that path, and by the pass count staying at 402 - a stale string would have raised ModuleNotFoundError there.",
|
||||
"cups_queue -> _cups_fallback -> cups_service is now a three-module chain; moving anything else out of cups_service must keep that direction to avoid a cycle."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; cups_service.py returns to 406 lines and _cups_fallback.py disappears.",
|
||||
"After rollback, re-run the package suite and confirm it still reports 402 passed."
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,44 @@
|
||||
{
|
||||
"intent": "Bring brother_printer/display.py under the 250-line cap by moving the page-count estimate and dropped-page warning into their own module, with no behaviour change.",
|
||||
"scope": [
|
||||
"python_pkg/brother_printer/_page_count.py (new)",
|
||||
"python_pkg/brother_printer/display.py",
|
||||
"python_pkg/brother_printer/tests/test_display_part3.py -> tests/test_page_count.py",
|
||||
"Non-goal: no assertion changed, no test deleted, skipped or weakened"
|
||||
],
|
||||
"changes": [
|
||||
"Moved _display_page_delivery_warning, _display_page_count_estimate and _display_consumables_reference verbatim into python_pkg/brother_printer/_page_count.py, which imports the patched collaborators check_page_delivery and estimate_consumable_life directly.",
|
||||
"display.py now imports the three functions from _page_count so display_usb_results still resolves them, and dropped the now-unused render_life_bar, TONER_RATED_PAGES and DRUM_RATED_PAGES imports; 342 -> 248 lines.",
|
||||
"Renamed tests/test_display_part3.py to tests/test_page_count.py and repointed its MOD and import block to the new module (per docs/python-split-recipes.md, the module a test patches must be the one the function actually lives in)."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q",
|
||||
"result": "pass",
|
||||
"evidence": "402 passed before the split and 402 passed after it - identical pass count, not merely a green run."
|
||||
},
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -c \"from python_pkg.brother_printer import display; display._display_page_count_estimate; display._display_consumables_reference; display._display_report_header; display._display_page_delivery_warning\"",
|
||||
"result": "pass",
|
||||
"evidence": "runtime probe OK - the names test_display.py patches on display are still attributes of display at import time, so ruff's TC001 rewrite trap did not fire."
|
||||
},
|
||||
{
|
||||
"command": "wc -l python_pkg/brother_printer/display.py",
|
||||
"result": "pass",
|
||||
"evidence": "248 lines, under the 250-line cap; _page_count.py is 114 lines."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files python_pkg/brother_printer/_page_count.py python_pkg/brother_printer/display.py python_pkg/brother_printer/tests/test_page_count.py",
|
||||
"result": "pass",
|
||||
"evidence": "ruff auto-sorted the new import block in test_page_count.py on the first run; clean on re-run."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"mock.patch pins names to a module: a test still patching estimate_consumable_life on display would now miss. Checked - test_page_count.py is the only module that patched it, and its MOD moved with the code.",
|
||||
"display.py keeps _display_report_header, which both test_display.py and test_display_part2.py patch, so it was deliberately left in place."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; display.py returns to 342 lines and test_page_count.py back to test_display_part3.py.",
|
||||
"After rollback, re-run the package suite and confirm it still reports 402 passed."
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,52 @@
|
||||
{
|
||||
"intent": "Bring brother_printer/consumables.py under the 250-line cap by moving the dropped-page detection into its own module, with no behaviour change.",
|
||||
"scope": [
|
||||
"python_pkg/brother_printer/_page_delivery.py (new)",
|
||||
"python_pkg/brother_printer/consumables.py",
|
||||
"python_pkg/brother_printer/_page_count.py (import path only)",
|
||||
"python_pkg/brother_printer/tests/test_consumables_part2.py (second MOD constant, applied per class)",
|
||||
"Non-goal: no assertion changed, no test deleted, skipped or weakened"
|
||||
],
|
||||
"changes": [
|
||||
"Moved check_page_delivery and _snapshot_counters verbatim into python_pkg/brother_printer/_page_delivery.py, which imports the three state-file primitives from consumables.",
|
||||
"The primitives themselves stay in consumables.py: test_consumables.py patches _load_consumable_state, _save_consumable_state, _get_cups_total_pages, CONSUMABLE_STATE_FILE and CUPS_PAGE_LOG on that module, and moving any of them would have let a test write to the real state file at ~/.config/brother_printer/state.json.",
|
||||
"consumables.py dropped the now-unused PAGE_DROP_WARN_THRESHOLD and PageDeliveryCheck imports; 279 -> 217 lines.",
|
||||
"test_consumables_part2.py gained a second constant MOD_PD alongside MOD, applied only to TestCheckPageDelivery and TestSnapshotCounters. Its other two classes test functions that did not move and keep MOD. This is the per-name discipline docs/python-split-recipes.md requires, not a blanket swap: the same three primitives are patched from both modules, so which MOD is correct depends on which caller the test exercises.",
|
||||
"_page_count.py imports check_page_delivery from _page_delivery now; test_page_count.py patches that name on _page_count, so it needed no edit."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q",
|
||||
"result": "pass",
|
||||
"evidence": "402 passed before the split and 402 passed after it - identical pass count, not merely a green run."
|
||||
},
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -c \"from python_pkg.brother_printer import _page_delivery as pd, consumables as c, _page_count as pc; pd._load_consumable_state; pd._save_consumable_state; pd._get_cups_total_pages; c.CONSUMABLE_STATE_FILE; c.CUPS_PAGE_LOG; c._migrate_state_to_printer_scale; pc.check_page_delivery\"",
|
||||
"result": "pass",
|
||||
"evidence": "runtime probe OK - both MOD and MOD_PD resolve every name their classes patch."
|
||||
},
|
||||
{
|
||||
"command": "ls -la ~/.config/brother_printer/state.json",
|
||||
"result": "pass",
|
||||
"evidence": "mtime still Jul 17 14:42 after the full suite run, so no test escaped its mock and wrote to the live consumable state. A green pass count alone would not have caught that."
|
||||
},
|
||||
{
|
||||
"command": "wc -l python_pkg/brother_printer/consumables.py python_pkg/brother_printer/_page_delivery.py",
|
||||
"result": "pass",
|
||||
"evidence": "217 and 76 lines, both under the 250-line cap."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <the five touched files>",
|
||||
"result": "pass",
|
||||
"evidence": "ruff, ruff format, mypy, pylint, bandit and pytest-with-coverage all pass on the touched files."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"test_consumables_part2.py now carries two module constants; a future edit that patches a state primitive in the wrong one fails loudly with an AttributeError rather than silently, because each name exists in only one of the two modules under its own MOD.",
|
||||
"consumables <- _page_delivery <- _page_count is a three-module chain; consumables must never import from _page_delivery or it becomes a cycle."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; consumables.py returns to 279 lines and _page_delivery.py disappears.",
|
||||
"After rollback, re-run the package suite and confirm it still reports 402 passed."
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,51 @@
|
||||
{
|
||||
"intent": "Bring brother_printer/usb_query.py under the 250-line cap by moving the non-blocking PJL transport into its own module, with no behaviour change.",
|
||||
"scope": [
|
||||
"python_pkg/brother_printer/_pjl_io.py (new)",
|
||||
"python_pkg/brother_printer/usb_query.py",
|
||||
"python_pkg/brother_printer/tests/test_usb_query_part2.py (MOD and import path only)",
|
||||
"Non-goal: no assertion changed, no test deleted, skipped or weakened"
|
||||
],
|
||||
"changes": [
|
||||
"Moved _drain_buffer, _write_with_deadline, _read_nonblocking, _wait_for_pjl_response and pjl_query verbatim into python_pkg/brother_printer/_pjl_io.py, together with the comment explaining why the fd is kept non-blocking; 267 -> 180 lines.",
|
||||
"usb_query.py imports _drain_buffer, _write_with_deadline and pjl_query back, because test_usb_query.py patches all three on that module. Checked first that each is genuinely called by the code that stayed (_retry_pjl_query and _run_pjl_queries call all three), so ruff cannot strip them under F401 and no __all__ shim is needed.",
|
||||
"Dropped contextlib and select from usb_query, which the moved block was their only user. Kept os and time despite the move: test_usb_query.py patches MOD.os.access/open/close and MOD.time.sleep, and _retry_pjl_query / query_usb_pjl still use both.",
|
||||
"_pjl_io imports os, select, time and contextlib by name because test_usb_query_part2.py patches MOD.os.read, MOD.os.write, MOD.select.select and MOD.time.time on it.",
|
||||
"test_usb_query_part2.py had its MOD constant and import module repointed at _pjl_io. test_usb_query.py needed no change, which is the signal the seam matched the existing test boundary."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q",
|
||||
"result": "pass",
|
||||
"evidence": "402 passed before the split and 402 passed after it - identical pass count, not merely a green run."
|
||||
},
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -c \"from python_pkg.brother_printer import usb_query as u, _pjl_io as p; u._drain_buffer; u.pjl_query; u._write_with_deadline; u.time; u.os; u.Path; u.shutil; p.os; p.select; p.time; p.contextlib; p._read_nonblocking\"",
|
||||
"result": "pass",
|
||||
"evidence": "runtime probe OK - the three re-imported names are real attributes of usb_query, so test_usb_query.py's patches still reach them."
|
||||
},
|
||||
{
|
||||
"command": "grep -cw '_drain_buffer|pjl_query|_write_with_deadline' over the kept region of usb_query.py",
|
||||
"result": "pass",
|
||||
"evidence": "5, 1 and 1 real call sites respectively - all three imports are used, so ruff's F401 sweep leaves them alone. Had any been import-only it would have needed an __all__ entry per docs/python-split-recipes.md."
|
||||
},
|
||||
{
|
||||
"command": "wc -l python_pkg/brother_printer/usb_query.py python_pkg/brother_printer/_pjl_io.py",
|
||||
"result": "pass",
|
||||
"evidence": "180 and 109 lines, both well under the 250-line cap."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <the four touched files>",
|
||||
"result": "pass",
|
||||
"evidence": "ruff, ruff format, mypy, pylint, bandit and pytest-with-coverage all pass on the touched files."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"The three re-imported names are load-bearing for mock.patch, not just for calls. If a future edit removes the last call site of one, ruff will strip the import and test_usb_query.py will fail with 'does not have the attribute' - the fix is an __all__ entry, not deleting the patch.",
|
||||
"usb_query <- _pjl_io is one-way; _pjl_io must never import from usb_query."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; usb_query.py returns to 267 lines and _pjl_io.py disappears.",
|
||||
"After rollback, re-run the package suite and confirm it still reports 402 passed."
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,47 @@
|
||||
{
|
||||
"intent": "Bring brother_printer/cups_queue.py under the 250-line cap by moving the queue-status display and the interactive fix prompt into their own module, with no behaviour change.",
|
||||
"scope": [
|
||||
"python_pkg/brother_printer/_queue_fix.py (new)",
|
||||
"python_pkg/brother_printer/cups_queue.py",
|
||||
"python_pkg/brother_printer/display.py (import path only)",
|
||||
"python_pkg/brother_printer/tests/test_cups_queue_part2.py, test_cups_queue_part3.py (MOD and import path only)",
|
||||
"Non-goal: no assertion changed, no test deleted, skipped or weakened"
|
||||
],
|
||||
"changes": [
|
||||
"Moved display_cups_queue_status, _offer_queue_fix, the five _dwj_* choice handlers, the _DWJ_ACTIONS table and the four _handle_* dispatchers verbatim into python_pkg/brother_printer/_queue_fix.py.",
|
||||
"The _cups_* action primitives stay in cups_queue.py on purpose and _queue_fix imports the three it needs. test_cups_queue.py patches subprocess and time on cups_queue, and those primitives are their only consumers, so moving them would have left subprocess.run unpatched and able to restart the real CUPS service during the suite.",
|
||||
"cups_queue.py dropped the imports that only the moved code used (BOLD, CYAN, GREEN, YELLOW, _prompt and the whole TYPE_CHECKING/Callable block); 424 -> 245 lines.",
|
||||
"display.py now imports display_cups_queue_status from _queue_fix and get_cups_queue_status from cups_queue, keeping the dependency direction cups_queue <- _queue_fix <- display with no re-export shim and no cycle.",
|
||||
"test_cups_queue_part2.py and test_cups_queue_part3.py had their MOD constant and import module repointed at _queue_fix. test_cups_queue.py needed no change at all, which is the signal the seam matched the existing test boundary."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -m pytest python_pkg/brother_printer/tests -q",
|
||||
"result": "pass",
|
||||
"evidence": "402 passed before the split and 402 passed after it - identical pass count, not merely a green run."
|
||||
},
|
||||
{
|
||||
"command": "PYTHONPATH=. python3 -c \"from python_pkg.brother_printer import _queue_fix as q, cups_queue as c, display as d; q._cups_enable_printer; q._cups_restart_service; q._prompt; q._handle_disabled_with_jobs; c.subprocess; c.time; c.shutil; c.Path; d.display_cups_queue_status\"",
|
||||
"result": "pass",
|
||||
"evidence": "runtime probe OK - every name the three test modules patch is still a real attribute of the module they name, so ruff's TC001 rewrite trap did not fire."
|
||||
},
|
||||
{
|
||||
"command": "wc -l python_pkg/brother_printer/cups_queue.py python_pkg/brother_printer/_queue_fix.py",
|
||||
"result": "pass",
|
||||
"evidence": "245 and 203 lines, both under the 250-line cap."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files <the six touched files>",
|
||||
"result": "pass",
|
||||
"evidence": "ruff, ruff format, mypy, pylint, bandit and pytest-with-coverage all pass on the touched files."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"mock.patch pins names to a module. The dangerous direction here was silent rather than red: an unpatched _cups_restart_service would have run systemctl restart cups for real. Mitigated by leaving all four _cups_* primitives in cups_queue.py, which the runtime probe and the unchanged test_cups_queue.py both confirm.",
|
||||
"display.py imports from both modules now; a future move of get_cups_queue_status into _queue_fix would create a cycle."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; cups_queue.py returns to 424 lines and _queue_fix.py disappears.",
|
||||
"After rollback, re-run the package suite and confirm it still reports 402 passed."
|
||||
]
|
||||
}
|
||||
208
python_pkg/brother_printer/_cups_fallback.py
Normal file
208
python_pkg/brother_printer/_cups_fallback.py
Normal file
@ -0,0 +1,208 @@
|
||||
"""IPP attribute queries, CUPS status mapping, and the CUPS-based USB fallback.
|
||||
|
||||
Split out of :mod:`python_pkg.brother_printer.cups_service` to keep it under
|
||||
the 250-line cap. The service-control and raw USB port-status helpers stay in
|
||||
``cups_service``, which patches ``fcntl``, ``os``, ``Path`` and ``time`` on
|
||||
that module; they are imported here so ``tests/test_cups_service_part3.py``
|
||||
can patch them on this one.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
from python_pkg.brother_printer._query import (
|
||||
printer_info_from_cups,
|
||||
run_command_text,
|
||||
)
|
||||
from python_pkg.brother_printer.constants import (
|
||||
_CUPS_REASONS_TO_STATUS,
|
||||
_CUPS_STATE_TO_STATUS,
|
||||
_ERROR_REASON_MAP,
|
||||
DERIVED_CUPS_ERROR,
|
||||
DERIVED_TONER_END,
|
||||
DERIVED_TONER_LOW,
|
||||
)
|
||||
from python_pkg.brother_printer.consumables import estimate_consumable_life
|
||||
from python_pkg.brother_printer.cups_service import (
|
||||
_ensure_cups_running,
|
||||
_get_pyusb_device_info,
|
||||
_query_usb_port_status_raw,
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import (
|
||||
USBPortStatus,
|
||||
USBResult,
|
||||
)
|
||||
|
||||
# ── IPP / CUPS attribute queries ────────────────────────────────────
|
||||
|
||||
|
||||
def _parse_ipp_attributes(output: str) -> dict[str, str]:
|
||||
"""Parse ipptool verbose output into an attribute dict."""
|
||||
attrs: dict[str, str] = {}
|
||||
for line in output.splitlines():
|
||||
match = re.match(r"\s+(\S+)\s+\([^)]+\)\s+=\s+(.*)", line)
|
||||
if match:
|
||||
attrs[match.group(1)] = match.group(2).strip()
|
||||
return attrs
|
||||
|
||||
|
||||
def _get_cups_ipp_status(printer_name: str) -> dict[str, str]:
|
||||
"""Query printer attributes via CUPS IPP using ipptool."""
|
||||
ipptool_path = shutil.which("ipptool")
|
||||
if not ipptool_path:
|
||||
return {}
|
||||
uri = f"ipp://localhost/printers/{printer_name}"
|
||||
try:
|
||||
r = subprocess.run(
|
||||
[ipptool_path, "-tv", uri, "get-printer-attributes.test"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
check=False,
|
||||
)
|
||||
return _parse_ipp_attributes(r.stdout)
|
||||
except (subprocess.TimeoutExpired, subprocess.SubprocessError, OSError):
|
||||
return {}
|
||||
|
||||
|
||||
def _get_cups_economode(printer_name: str) -> str:
|
||||
"""Query toner save mode setting via lpoptions."""
|
||||
lpoptions_path = shutil.which("lpoptions")
|
||||
if not lpoptions_path:
|
||||
return ""
|
||||
command = [lpoptions_path, "-p", printer_name, "-l"]
|
||||
for line in run_command_text(command).splitlines():
|
||||
if "conomode" in line.lower():
|
||||
match = re.search(r"\*(\w+)", line)
|
||||
if match:
|
||||
return "ON" if match.group(1).lower() == "true" else "OFF"
|
||||
return ""
|
||||
|
||||
|
||||
# ── Status code mapping ──────────────────────────────────────────────
|
||||
|
||||
|
||||
def _map_cups_to_status_code(state: str, reasons: str) -> str:
|
||||
"""Map CUPS state + reasons to a Brother PJL status code string."""
|
||||
for keyword, code in _CUPS_REASONS_TO_STATUS.items():
|
||||
if keyword in reasons.lower():
|
||||
return str(code)
|
||||
clean_state = re.sub(r"\(.*\)", "", state).strip().lower()
|
||||
return str(_CUPS_STATE_TO_STATUS.get(clean_state, 10001))
|
||||
|
||||
|
||||
def _cups_reasons_to_error(cups_reasons: str) -> tuple[str, str]:
|
||||
"""Map CUPS reason keywords to a (status_code, display) pair."""
|
||||
reasons_lower = cups_reasons.lower()
|
||||
for keywords, code, display in _ERROR_REASON_MAP:
|
||||
if any(kw in reasons_lower for kw in keywords):
|
||||
return code, display
|
||||
# Nothing recognised. Show what CUPS actually said rather than a bare
|
||||
# "Printer Error", which tells the reader nothing they can act on.
|
||||
detail = cups_reasons.strip()
|
||||
if detail and detail.lower() not in {"none", ""}:
|
||||
return DERIVED_CUPS_ERROR, f"Printer Error (CUPS reports: {detail})"
|
||||
return DERIVED_CUPS_ERROR, "Printer Error (CUPS gave no reason)"
|
||||
|
||||
|
||||
def _port_status_to_status_code(
|
||||
ps: USBPortStatus,
|
||||
cups_reasons: str,
|
||||
) -> tuple[str, str]:
|
||||
"""Map USB port status + CUPS reasons to (status_code, display)."""
|
||||
# The port status exposes only paper_empty/error/online bits, so anything
|
||||
# more specific than "out of paper" has to come from the CUPS reasons -
|
||||
# an error bit alone does not tell us the cover is open.
|
||||
if ps.paper_empty:
|
||||
return "41000", "No Paper"
|
||||
if ps.error:
|
||||
return _cups_reasons_to_error(cups_reasons)
|
||||
if not ps.online:
|
||||
return "10002", "Offline / Sleep"
|
||||
return "", ""
|
||||
|
||||
|
||||
# ── CUPS printer name discovery ──────────────────────────────────────
|
||||
|
||||
|
||||
def find_cups_printer_name() -> str:
|
||||
"""Find the CUPS queue name for a Brother printer."""
|
||||
lpstat_path = shutil.which("lpstat")
|
||||
if not lpstat_path:
|
||||
return ""
|
||||
for line in run_command_text([lpstat_path, "-v"]).splitlines():
|
||||
if "brother" in line.lower():
|
||||
match = re.match(r"device for (\S+):", line)
|
||||
if match:
|
||||
return match.group(1)
|
||||
return ""
|
||||
|
||||
|
||||
# ── CUPS-based USB fallback query ────────────────────────────────────
|
||||
|
||||
|
||||
def query_usb_via_cups() -> USBResult:
|
||||
"""Query USB printer status through CUPS when /dev/usb/lp* is unavailable."""
|
||||
_ensure_cups_running()
|
||||
printer_name = find_cups_printer_name()
|
||||
if not printer_name:
|
||||
return USBResult(
|
||||
error="No USB printer device at /dev/usb/lp*"
|
||||
" (usblp module not available)"
|
||||
" and no Brother printer found in CUPS.",
|
||||
)
|
||||
|
||||
pyusb_info = _get_pyusb_device_info()
|
||||
cups_info = printer_info_from_cups()
|
||||
|
||||
result = USBResult(
|
||||
device="cups",
|
||||
product=(
|
||||
pyusb_info.get("product")
|
||||
or cups_info.get("product")
|
||||
or "Brother Laser Printer"
|
||||
),
|
||||
serial=pyusb_info.get("serial") or cups_info.get("serial", ""),
|
||||
)
|
||||
|
||||
ipp = _get_cups_ipp_status(printer_name)
|
||||
state = ipp.get("printer-state", "")
|
||||
reasons = ipp.get("printer-state-reasons", "none")
|
||||
result.economode = _get_cups_economode(printer_name)
|
||||
|
||||
port_status = _query_usb_port_status_raw(state)
|
||||
if port_status is not None:
|
||||
result.port_status = port_status
|
||||
hw_code, hw_display = _port_status_to_status_code(
|
||||
port_status,
|
||||
reasons,
|
||||
)
|
||||
if hw_code:
|
||||
result.status_code = hw_code
|
||||
result.display = hw_display
|
||||
result.online = "TRUE" if port_status.online else "FALSE"
|
||||
return result
|
||||
estimate = estimate_consumable_life()
|
||||
if estimate.toner_exhausted:
|
||||
result.status_code = DERIVED_TONER_END
|
||||
result.display = "Toner End (estimated from page count)"
|
||||
result.online = "TRUE"
|
||||
return result
|
||||
if estimate.toner_low:
|
||||
result.status_code = DERIVED_TONER_LOW
|
||||
result.display = "Toner Low (estimated from page count)"
|
||||
result.online = "TRUE"
|
||||
return result
|
||||
result.status_code = _map_cups_to_status_code(state, reasons)
|
||||
result.display = ipp.get("printer-state-message", "")
|
||||
result.online = "TRUE"
|
||||
return result
|
||||
|
||||
result.status_code = _map_cups_to_status_code(state, reasons)
|
||||
result.display = ipp.get("printer-state-message", "")
|
||||
result.online = "TRUE" if state.lower() in {"idle", "processing"} else "FALSE"
|
||||
|
||||
return result
|
||||
115
python_pkg/brother_printer/_page_count.py
Normal file
115
python_pkg/brother_printer/_page_count.py
Normal file
@ -0,0 +1,115 @@
|
||||
"""Page-count estimates and the dropped-page warning.
|
||||
|
||||
Split out of :mod:`python_pkg.brother_printer.display` to keep it under the
|
||||
250-line cap. ``estimate_consumable_life`` and ``check_page_delivery`` are
|
||||
patched by ``tests/test_display_part3.py``, so they are imported here rather
|
||||
than through ``display``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from python_pkg.brother_printer._page_delivery import check_page_delivery
|
||||
from python_pkg.brother_printer._supply import render_life_bar
|
||||
from python_pkg.brother_printer.constants import (
|
||||
BOLD,
|
||||
DIM,
|
||||
DRUM_RATED_PAGES,
|
||||
RED,
|
||||
RESET,
|
||||
TONER_RATED_PAGES,
|
||||
YELLOW,
|
||||
_out,
|
||||
)
|
||||
from python_pkg.brother_printer.consumables import estimate_consumable_life
|
||||
|
||||
|
||||
def _display_page_delivery_warning(printer_total: int, *, queue_idle: bool) -> None:
|
||||
"""Warn when CUPS claims more pages than the printer actually counted.
|
||||
|
||||
Args:
|
||||
printer_total: Lifetime count from the printer's own counter.
|
||||
queue_idle: False while a job is queued or printing, when the two
|
||||
counters legitimately disagree.
|
||||
"""
|
||||
check = check_page_delivery(printer_total, queue_idle=queue_idle)
|
||||
if not check.suspected:
|
||||
return
|
||||
_out(f"{BOLD}── Dropped Pages ──{RESET}")
|
||||
_out()
|
||||
_out(
|
||||
f" {RED}{BOLD}⚠ {check.dropped} pages did not print.{RESET}"
|
||||
f" {RED}CUPS sent {check.cups_pages} pages since the last check;"
|
||||
f" the printer's own counter advanced by"
|
||||
f" {check.printer_pages}.{RESET}"
|
||||
)
|
||||
_out()
|
||||
_out(
|
||||
f" {DIM}The printer discards pages whose 600 dpi raster does not fit"
|
||||
f" its memory, stays READY, and reports no error - and CUPS still calls"
|
||||
f" the job successful. Reprint at a lower resolution:{RESET}"
|
||||
)
|
||||
_out(f" {DIM} lp -o Resolution=300dpi <file>{RESET}")
|
||||
_out()
|
||||
|
||||
|
||||
def _display_page_count_estimate(printer_total: int = 0) -> None:
|
||||
"""Show estimated consumable life based on the printer's page count.
|
||||
|
||||
Args:
|
||||
printer_total: Lifetime count from the printer's own counter, or zero
|
||||
when it could not be read and the CUPS page log has to stand in.
|
||||
"""
|
||||
estimate = estimate_consumable_life(printer_total)
|
||||
if estimate.total_pages <= 0:
|
||||
return
|
||||
_out(f"{BOLD}── Page Count Estimate ──{RESET}")
|
||||
_out()
|
||||
_out(
|
||||
f" {BOLD}Total pages printed:{RESET} {estimate.total_pages}"
|
||||
f" (toner: {estimate.toner_pages} since replacement,"
|
||||
f" drum: {estimate.drum_pages} since replacement)"
|
||||
)
|
||||
if estimate.approximate:
|
||||
_out(
|
||||
f" {YELLOW}Approximate: counted from the CUPS log, not the"
|
||||
f" printer's own counter, so it misses pages CUPS never saw"
|
||||
f" and reads high.{RESET}"
|
||||
)
|
||||
_out()
|
||||
render_life_bar(
|
||||
"Toner:",
|
||||
estimate.toner_pct_remaining,
|
||||
exhausted=estimate.toner_exhausted,
|
||||
low=estimate.toner_low,
|
||||
exhausted_note=" ← REPLACE NOW",
|
||||
low_note=" ← order soon",
|
||||
)
|
||||
render_life_bar(
|
||||
"Drum: ",
|
||||
estimate.drum_pct_remaining,
|
||||
low=estimate.drum_near_end,
|
||||
low_note=" ← nearing end",
|
||||
)
|
||||
_out(
|
||||
f" {DIM}Based on pages since last replacement"
|
||||
f" vs rated capacity (toner ~{TONER_RATED_PAGES},"
|
||||
f" drum ~{DRUM_RATED_PAGES}).{RESET}"
|
||||
)
|
||||
_out(f" {DIM}Reset after replacing: --reset-toner or --reset-drum{RESET}")
|
||||
if estimate.toner_exhausted:
|
||||
_out()
|
||||
_out(
|
||||
f" {RED}{BOLD}⚠ Toner is likely exhausted."
|
||||
f" This is probably why the orange light is flashing.{RESET}"
|
||||
)
|
||||
_out()
|
||||
|
||||
|
||||
def _display_consumables_reference() -> None:
|
||||
"""Print compatible consumables reference."""
|
||||
_out(f"{BOLD}── Compatible Consumables ──{RESET}")
|
||||
_out()
|
||||
_out(f" {BOLD}Toner:{RESET} TN-1050 / TN-1030 (or compatible third-party)")
|
||||
_out(f" {BOLD}Drum:{RESET} DR-1050 / DR-1030 (or compatible third-party)")
|
||||
_out(f" {DIM} Toner rated ~1000 pages; Drum rated ~10000 pages.{RESET}")
|
||||
_out()
|
||||
76
python_pkg/brother_printer/_page_delivery.py
Normal file
76
python_pkg/brother_printer/_page_delivery.py
Normal file
@ -0,0 +1,76 @@
|
||||
"""Dropped-page detection: CUPS's page log versus the printer's own counter.
|
||||
|
||||
Split out of :mod:`python_pkg.brother_printer.consumables` to keep it under
|
||||
the 250-line cap. The state-file I/O stays in ``consumables`` because
|
||||
``tests/test_consumables.py`` patches it there; it is imported here so
|
||||
``tests/test_consumables_part2.py`` can patch it on this module for the two
|
||||
functions that moved.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from python_pkg.brother_printer.constants import PAGE_DROP_WARN_THRESHOLD
|
||||
from python_pkg.brother_printer.consumables import (
|
||||
_get_cups_total_pages,
|
||||
_load_consumable_state,
|
||||
_save_consumable_state,
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import PageDeliveryCheck
|
||||
|
||||
|
||||
def check_page_delivery(printer_total: int, *, queue_idle: bool) -> PageDeliveryCheck:
|
||||
"""Compare pages CUPS logged against pages the printer actually counted.
|
||||
|
||||
Only meaningful between jobs: mid-job, CUPS has logged pages the printer has
|
||||
not yet pulled off the wire, which would look identical to dropping them.
|
||||
Records a fresh snapshot of both counters whenever it runs cleanly.
|
||||
|
||||
Args:
|
||||
printer_total: Lifetime count from the printer's own counter.
|
||||
queue_idle: False when a job is queued or printing, which makes any
|
||||
comparison meaningless.
|
||||
|
||||
Returns:
|
||||
The comparison. suspected is True only when CUPS claims materially more
|
||||
pages than the printer recorded.
|
||||
"""
|
||||
check = PageDeliveryCheck()
|
||||
if printer_total <= 0 or not queue_idle:
|
||||
return check
|
||||
state = _load_consumable_state()
|
||||
cups_total = _get_cups_total_pages()
|
||||
last_printer = state["last_printer_count"]
|
||||
last_cups = state["last_cups_total"]
|
||||
|
||||
_snapshot_counters(state, printer_total, cups_total)
|
||||
|
||||
if last_printer <= 0 or last_cups <= 0:
|
||||
# No baseline yet: this run establishes one.
|
||||
return check
|
||||
printer_delta = printer_total - last_printer
|
||||
cups_delta = cups_total - last_cups
|
||||
if printer_delta < 0 or cups_delta < 0:
|
||||
# Counter reset or the page log rotated; nothing to conclude.
|
||||
return check
|
||||
check.cups_pages = cups_delta
|
||||
check.printer_pages = printer_delta
|
||||
check.dropped = cups_delta - printer_delta
|
||||
check.suspected = check.dropped >= PAGE_DROP_WARN_THRESHOLD
|
||||
return check
|
||||
|
||||
|
||||
def _snapshot_counters(
|
||||
state: dict[str, int],
|
||||
printer_total: int,
|
||||
cups_total: int,
|
||||
) -> None:
|
||||
"""Persist where both counters stood, for the next run to compare against."""
|
||||
if (
|
||||
state["last_printer_count"] == printer_total
|
||||
and state["last_cups_total"] == cups_total
|
||||
):
|
||||
return
|
||||
updated = dict(state)
|
||||
updated["last_printer_count"] = printer_total
|
||||
updated["last_cups_total"] = cups_total
|
||||
_save_consumable_state(updated)
|
||||
108
python_pkg/brother_printer/_pjl_io.py
Normal file
108
python_pkg/brother_printer/_pjl_io.py
Normal file
@ -0,0 +1,108 @@
|
||||
"""Non-blocking PJL transport over the raw /dev/usb/lp* file descriptor.
|
||||
|
||||
Split out of :mod:`python_pkg.brother_printer.usb_query` to keep it under the
|
||||
250-line cap. ``tests/test_usb_query_part2.py`` patches ``os``, ``select`` and
|
||||
``time`` on this module, so those imports are load-bearing; the query callers
|
||||
that stay in ``usb_query`` import these functions back, which is what keeps
|
||||
``tests/test_usb_query.py`` patching them there.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import select
|
||||
import time
|
||||
|
||||
# ── PJL over USB ─────────────────────────────────────────────────────
|
||||
|
||||
|
||||
# The printer's fd is opened and kept non-blocking. usblp blocks indefinitely
|
||||
# on a plain open() and on writes whenever the printer is not ready to talk -
|
||||
# stuck mid-job, wedged, or simply asleep - so a blocking fd turns "the printer
|
||||
# is unwell" into "this tool hangs forever", which is the worst possible answer
|
||||
# when a status report is exactly what you wanted.
|
||||
|
||||
|
||||
def _drain_buffer(fd: int) -> None:
|
||||
"""Read and discard any stale data from the USB buffer."""
|
||||
with contextlib.suppress(OSError):
|
||||
while os.read(fd, 4096):
|
||||
pass
|
||||
|
||||
|
||||
def _write_with_deadline(fd: int, data: bytes, deadline: float) -> bool:
|
||||
"""Write all of data to a non-blocking fd. Returns False if the deadline passes.
|
||||
|
||||
Args:
|
||||
fd: Non-blocking file descriptor for the printer.
|
||||
data: Bytes to send.
|
||||
deadline: Absolute monotonic-ish time (time.time()) to give up at.
|
||||
|
||||
Returns:
|
||||
True when everything was written, False on timeout or write error.
|
||||
"""
|
||||
sent = 0
|
||||
while sent < len(data):
|
||||
remaining = deadline - time.time()
|
||||
if remaining <= 0:
|
||||
return False
|
||||
try:
|
||||
sent += os.write(fd, data[sent:])
|
||||
except BlockingIOError:
|
||||
# Printer's buffer is full or it is not accepting data: wait for it
|
||||
# to become writable rather than spinning or blocking forever.
|
||||
_, writable, _ = select.select([], [fd], [], min(remaining, 0.5))
|
||||
if not writable:
|
||||
continue
|
||||
except OSError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _read_nonblocking(fd: int) -> bytes:
|
||||
"""Read all currently available data from a non-blocking fd."""
|
||||
data = b""
|
||||
with contextlib.suppress(OSError):
|
||||
while True:
|
||||
chunk = os.read(fd, 4096)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
return data
|
||||
|
||||
|
||||
def _wait_for_pjl_response(fd: int, deadline: float) -> bytes:
|
||||
"""Poll fd until PJL data arrives or deadline expires."""
|
||||
response = b""
|
||||
while time.time() < deadline:
|
||||
remaining = deadline - time.time()
|
||||
if remaining <= 0:
|
||||
break
|
||||
readable, _, _ = select.select([fd], [], [], min(remaining, 1.0))
|
||||
if readable:
|
||||
response += _read_nonblocking(fd)
|
||||
if response and (b"=" in response or b"@PJL" in response):
|
||||
break
|
||||
return response
|
||||
|
||||
|
||||
def pjl_query(fd: int, cmd: str, timeout_sec: float = 5.0) -> str:
|
||||
"""Send a PJL command via raw fd and read the response.
|
||||
|
||||
Args:
|
||||
fd: Non-blocking file descriptor for the printer.
|
||||
cmd: PJL command, e.g. "@PJL INFO STATUS".
|
||||
timeout_sec: Total budget for sending the command and reading the reply.
|
||||
|
||||
Returns:
|
||||
The printer's reply, or "" if it did not answer in time. A silent
|
||||
printer is a normal outcome here, not an error: it happens whenever the
|
||||
printer is busy digesting a job.
|
||||
"""
|
||||
deadline = time.time() + timeout_sec
|
||||
pjl_cmd = f"\x1b%-12345X@PJL\r\n{cmd}\r\n\x1b%-12345X"
|
||||
if not _write_with_deadline(fd, pjl_cmd.encode(), deadline):
|
||||
return ""
|
||||
response = _wait_for_pjl_response(fd, deadline)
|
||||
return response.decode("ascii", errors="replace")
|
||||
203
python_pkg/brother_printer/_queue_fix.py
Normal file
203
python_pkg/brother_printer/_queue_fix.py
Normal file
@ -0,0 +1,203 @@
|
||||
"""CUPS queue status display and the interactive queue-fix prompt.
|
||||
|
||||
Split out of :mod:`python_pkg.brother_printer.cups_queue` to keep it under the
|
||||
250-line cap. The ``_cups_*`` action primitives deliberately stay in
|
||||
``cups_queue``: ``tests/test_cups_queue.py`` patches ``subprocess`` and
|
||||
``time`` on that module, and moving them would let a real ``subprocess.run``
|
||||
reach the live CUPS daemon.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from python_pkg.brother_printer.constants import (
|
||||
BOLD,
|
||||
CYAN,
|
||||
DIM,
|
||||
GREEN,
|
||||
RED,
|
||||
RESET,
|
||||
YELLOW,
|
||||
_out,
|
||||
_prompt,
|
||||
)
|
||||
from python_pkg.brother_printer.cups_queue import (
|
||||
_cups_cancel_all_jobs,
|
||||
_cups_enable_printer,
|
||||
_cups_restart_service,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
from python_pkg.brother_printer.data_classes import CUPSQueueStatus
|
||||
|
||||
|
||||
# ── Queue status display ────────────────────────────────────────────
|
||||
|
||||
|
||||
def display_cups_queue_status(queue: CUPSQueueStatus) -> None:
|
||||
"""Display CUPS queue status and offer interactive fixes."""
|
||||
if not queue.printer_name:
|
||||
return
|
||||
if queue.enabled and not queue.jobs and not queue.has_backend_errors:
|
||||
return
|
||||
|
||||
_out()
|
||||
_out(f"{BOLD}── Print Queue ──{RESET}")
|
||||
_out()
|
||||
|
||||
if queue.has_backend_errors and queue.enabled and not queue.jobs:
|
||||
_out(f" {YELLOW}{BOLD}⚡ CUPS backend has stale errors{RESET}")
|
||||
_out(
|
||||
f" {DIM}New print jobs may silently fail."
|
||||
f" A CUPS restart usually fixes this.{RESET}"
|
||||
)
|
||||
_out()
|
||||
|
||||
if not queue.enabled:
|
||||
_out(f" {RED}{BOLD}⚠ Printer queue is DISABLED{RESET}")
|
||||
if queue.reason:
|
||||
_out(f" {DIM}Reason: {queue.reason}{RESET}")
|
||||
_out()
|
||||
|
||||
if queue.jobs:
|
||||
_out(f" {BOLD}Pending jobs ({len(queue.jobs)}):{RESET}")
|
||||
for job in queue.jobs:
|
||||
_out(f" {job.job_id} {DIM}{job.user} {job.size}B {job.date}{RESET}")
|
||||
_out()
|
||||
|
||||
_offer_queue_fix(queue)
|
||||
|
||||
|
||||
# ── Interactive queue fix ────────────────────────────────────────────
|
||||
|
||||
|
||||
def _offer_queue_fix(queue: CUPSQueueStatus) -> None:
|
||||
"""Prompt the user to fix a disabled queue / pending jobs."""
|
||||
_out(f" {BOLD}Available actions:{RESET}")
|
||||
|
||||
options: list[str] = []
|
||||
if not queue.enabled and queue.jobs:
|
||||
_out(f" {CYAN}1){RESET} Re-enable printer and retry all jobs")
|
||||
_out(f" {CYAN}2){RESET} Re-enable printer and cancel all jobs")
|
||||
_out(f" {CYAN}3){RESET} Cancel all jobs (keep printer disabled)")
|
||||
_out(f" {CYAN}4){RESET} Restart CUPS service (fixes stale backend)")
|
||||
_out(f" {CYAN}5){RESET} Restart CUPS + re-enable + retry all jobs")
|
||||
_out(f" {CYAN}6){RESET} Do nothing")
|
||||
options = ["1", "2", "3", "4", "5", "6"]
|
||||
elif not queue.enabled:
|
||||
_out(f" {CYAN}1){RESET} Re-enable printer")
|
||||
_out(f" {CYAN}2){RESET} Restart CUPS service (fixes stale backend)")
|
||||
_out(f" {CYAN}3){RESET} Do nothing")
|
||||
options = ["1", "2", "3"]
|
||||
elif queue.jobs:
|
||||
_out(f" {CYAN}1){RESET} Cancel all pending jobs")
|
||||
_out(f" {CYAN}2){RESET} Restart CUPS service (fixes stale backend)")
|
||||
_out(f" {CYAN}3){RESET} Do nothing")
|
||||
options = ["1", "2", "3"]
|
||||
else:
|
||||
_out(f" {CYAN}1){RESET} Restart CUPS service (fixes stale backend)")
|
||||
_out(f" {CYAN}2){RESET} Do nothing")
|
||||
options = ["1", "2"]
|
||||
|
||||
_out()
|
||||
choice = _prompt(f" Choose [{'/'.join(options)}]: ")
|
||||
_out()
|
||||
|
||||
if not queue.enabled and queue.jobs:
|
||||
_handle_disabled_with_jobs(queue, choice)
|
||||
elif not queue.enabled:
|
||||
_handle_disabled_no_jobs(queue, choice)
|
||||
elif queue.jobs:
|
||||
_handle_enabled_with_jobs(queue, choice)
|
||||
else:
|
||||
_handle_backend_errors_only(choice)
|
||||
|
||||
|
||||
def _dwj_enable_only(printer_name: str) -> None:
|
||||
"""Choice 1: re-enable printer so queued jobs are retried."""
|
||||
if _cups_enable_printer(printer_name):
|
||||
_out(f" {GREEN}✓ Printer re-enabled. Jobs will be retried.{RESET}")
|
||||
|
||||
|
||||
def _dwj_cancel_and_enable(printer_name: str) -> None:
|
||||
"""Choice 2: cancel all jobs then re-enable."""
|
||||
_cups_cancel_all_jobs(printer_name)
|
||||
if _cups_enable_printer(printer_name):
|
||||
_out(f" {GREEN}✓ All jobs cancelled and printer re-enabled.{RESET}")
|
||||
|
||||
|
||||
def _dwj_cancel_only(printer_name: str) -> None:
|
||||
"""Choice 3: cancel all jobs."""
|
||||
if _cups_cancel_all_jobs(printer_name):
|
||||
_out(f" {GREEN}✓ All jobs cancelled.{RESET}")
|
||||
|
||||
|
||||
def _dwj_restart_only(_printer_name: str) -> None:
|
||||
"""Choice 4: restart CUPS."""
|
||||
if _cups_restart_service():
|
||||
_out(f" {GREEN}✓ CUPS restarted.{RESET}")
|
||||
|
||||
|
||||
def _dwj_restart_and_enable(printer_name: str) -> None:
|
||||
"""Choice 5: restart CUPS and re-enable printer."""
|
||||
if _cups_restart_service():
|
||||
_cups_enable_printer(printer_name)
|
||||
_out(
|
||||
f" {GREEN}✓ CUPS restarted, printer re-enabled."
|
||||
f" Jobs will be retried.{RESET}"
|
||||
)
|
||||
|
||||
|
||||
_DWJ_ACTIONS: dict[str, Callable[[str], None]] = {
|
||||
"1": _dwj_enable_only,
|
||||
"2": _dwj_cancel_and_enable,
|
||||
"3": _dwj_cancel_only,
|
||||
"4": _dwj_restart_only,
|
||||
"5": _dwj_restart_and_enable,
|
||||
}
|
||||
|
||||
|
||||
def _handle_disabled_with_jobs(queue: CUPSQueueStatus, choice: str) -> None:
|
||||
"""Handle fix for disabled printer with pending jobs."""
|
||||
action = _DWJ_ACTIONS.get(choice)
|
||||
if action is not None:
|
||||
action(queue.printer_name)
|
||||
else:
|
||||
_out(f" {DIM}No changes made.{RESET}")
|
||||
|
||||
|
||||
def _handle_disabled_no_jobs(queue: CUPSQueueStatus, choice: str) -> None:
|
||||
"""Handle fix for disabled printer with no pending jobs."""
|
||||
if choice == "1":
|
||||
if _cups_enable_printer(queue.printer_name):
|
||||
_out(f" {GREEN}✓ Printer re-enabled.{RESET}")
|
||||
elif choice == "2":
|
||||
if _cups_restart_service():
|
||||
_cups_enable_printer(queue.printer_name)
|
||||
_out(f" {GREEN}✓ CUPS restarted and printer re-enabled.{RESET}")
|
||||
else:
|
||||
_out(f" {DIM}No changes made.{RESET}")
|
||||
|
||||
|
||||
def _handle_enabled_with_jobs(queue: CUPSQueueStatus, choice: str) -> None:
|
||||
"""Handle fix for enabled printer with stuck jobs."""
|
||||
if choice == "1":
|
||||
if _cups_cancel_all_jobs(queue.printer_name):
|
||||
_out(f" {GREEN}✓ All jobs cancelled.{RESET}")
|
||||
elif choice == "2":
|
||||
if _cups_restart_service():
|
||||
_out(f" {GREEN}✓ CUPS restarted.{RESET}")
|
||||
else:
|
||||
_out(f" {DIM}No changes made.{RESET}")
|
||||
|
||||
|
||||
def _handle_backend_errors_only(choice: str) -> None:
|
||||
"""Handle fix when only stale backend errors are detected."""
|
||||
if choice == "1":
|
||||
if _cups_restart_service():
|
||||
_out(f" {GREEN}✓ CUPS restarted. Stale backend errors cleared.{RESET}")
|
||||
else:
|
||||
_out(f" {DIM}No changes made.{RESET}")
|
||||
@ -20,15 +20,11 @@ from python_pkg.brother_printer.constants import (
|
||||
CUPS_PAGE_LOG_PATH,
|
||||
DRUM_RATED_PAGES,
|
||||
GREEN,
|
||||
PAGE_DROP_WARN_THRESHOLD,
|
||||
RESET,
|
||||
TONER_RATED_PAGES,
|
||||
_out,
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import (
|
||||
PageCountEstimate,
|
||||
PageDeliveryCheck,
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import PageCountEstimate
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@ -186,64 +182,6 @@ def _cups_total_on_printer_scale(state: dict[str, int]) -> int:
|
||||
return cups_total + offset
|
||||
|
||||
|
||||
def check_page_delivery(printer_total: int, *, queue_idle: bool) -> PageDeliveryCheck:
|
||||
"""Compare pages CUPS logged against pages the printer actually counted.
|
||||
|
||||
Only meaningful between jobs: mid-job, CUPS has logged pages the printer has
|
||||
not yet pulled off the wire, which would look identical to dropping them.
|
||||
Records a fresh snapshot of both counters whenever it runs cleanly.
|
||||
|
||||
Args:
|
||||
printer_total: Lifetime count from the printer's own counter.
|
||||
queue_idle: False when a job is queued or printing, which makes any
|
||||
comparison meaningless.
|
||||
|
||||
Returns:
|
||||
The comparison. suspected is True only when CUPS claims materially more
|
||||
pages than the printer recorded.
|
||||
"""
|
||||
check = PageDeliveryCheck()
|
||||
if printer_total <= 0 or not queue_idle:
|
||||
return check
|
||||
state = _load_consumable_state()
|
||||
cups_total = _get_cups_total_pages()
|
||||
last_printer = state["last_printer_count"]
|
||||
last_cups = state["last_cups_total"]
|
||||
|
||||
_snapshot_counters(state, printer_total, cups_total)
|
||||
|
||||
if last_printer <= 0 or last_cups <= 0:
|
||||
# No baseline yet: this run establishes one.
|
||||
return check
|
||||
printer_delta = printer_total - last_printer
|
||||
cups_delta = cups_total - last_cups
|
||||
if printer_delta < 0 or cups_delta < 0:
|
||||
# Counter reset or the page log rotated; nothing to conclude.
|
||||
return check
|
||||
check.cups_pages = cups_delta
|
||||
check.printer_pages = printer_delta
|
||||
check.dropped = cups_delta - printer_delta
|
||||
check.suspected = check.dropped >= PAGE_DROP_WARN_THRESHOLD
|
||||
return check
|
||||
|
||||
|
||||
def _snapshot_counters(
|
||||
state: dict[str, int],
|
||||
printer_total: int,
|
||||
cups_total: int,
|
||||
) -> None:
|
||||
"""Persist where both counters stood, for the next run to compare against."""
|
||||
if (
|
||||
state["last_printer_count"] == printer_total
|
||||
and state["last_cups_total"] == cups_total
|
||||
):
|
||||
return
|
||||
updated = dict(state)
|
||||
updated["last_printer_count"] = printer_total
|
||||
updated["last_cups_total"] = cups_total
|
||||
_save_consumable_state(updated)
|
||||
|
||||
|
||||
def estimate_consumable_life(printer_total: int = 0) -> PageCountEstimate:
|
||||
"""Estimate toner/drum life from pages printed since the last replacement.
|
||||
|
||||
|
||||
@ -8,28 +8,18 @@ import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from python_pkg.brother_printer._cups_fallback import find_cups_printer_name
|
||||
from python_pkg.brother_printer._query import run_command_text
|
||||
from python_pkg.brother_printer.constants import (
|
||||
BOLD,
|
||||
CYAN,
|
||||
DIM,
|
||||
GREEN,
|
||||
MIN_LPSTAT_JOB_PARTS,
|
||||
RED,
|
||||
RESET,
|
||||
YELLOW,
|
||||
_out,
|
||||
_prompt,
|
||||
)
|
||||
from python_pkg.brother_printer.cups_service import find_cups_printer_name
|
||||
from python_pkg.brother_printer.data_classes import CUPSJob, CUPSQueueStatus
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
|
||||
# ── Queue inspection ─────────────────────────────────────────────────
|
||||
|
||||
|
||||
@ -253,172 +243,3 @@ def _check_cups_backend_errors(
|
||||
return False, ""
|
||||
|
||||
return True, backend_error
|
||||
|
||||
|
||||
# ── Queue status display ────────────────────────────────────────────
|
||||
|
||||
|
||||
def display_cups_queue_status(queue: CUPSQueueStatus) -> None:
|
||||
"""Display CUPS queue status and offer interactive fixes."""
|
||||
if not queue.printer_name:
|
||||
return
|
||||
if queue.enabled and not queue.jobs and not queue.has_backend_errors:
|
||||
return
|
||||
|
||||
_out()
|
||||
_out(f"{BOLD}── Print Queue ──{RESET}")
|
||||
_out()
|
||||
|
||||
if queue.has_backend_errors and queue.enabled and not queue.jobs:
|
||||
_out(f" {YELLOW}{BOLD}⚡ CUPS backend has stale errors{RESET}")
|
||||
_out(
|
||||
f" {DIM}New print jobs may silently fail."
|
||||
f" A CUPS restart usually fixes this.{RESET}"
|
||||
)
|
||||
_out()
|
||||
|
||||
if not queue.enabled:
|
||||
_out(f" {RED}{BOLD}⚠ Printer queue is DISABLED{RESET}")
|
||||
if queue.reason:
|
||||
_out(f" {DIM}Reason: {queue.reason}{RESET}")
|
||||
_out()
|
||||
|
||||
if queue.jobs:
|
||||
_out(f" {BOLD}Pending jobs ({len(queue.jobs)}):{RESET}")
|
||||
for job in queue.jobs:
|
||||
_out(f" {job.job_id} {DIM}{job.user} {job.size}B {job.date}{RESET}")
|
||||
_out()
|
||||
|
||||
_offer_queue_fix(queue)
|
||||
|
||||
|
||||
# ── Interactive queue fix ────────────────────────────────────────────
|
||||
|
||||
|
||||
def _offer_queue_fix(queue: CUPSQueueStatus) -> None:
|
||||
"""Prompt the user to fix a disabled queue / pending jobs."""
|
||||
_out(f" {BOLD}Available actions:{RESET}")
|
||||
|
||||
options: list[str] = []
|
||||
if not queue.enabled and queue.jobs:
|
||||
_out(f" {CYAN}1){RESET} Re-enable printer and retry all jobs")
|
||||
_out(f" {CYAN}2){RESET} Re-enable printer and cancel all jobs")
|
||||
_out(f" {CYAN}3){RESET} Cancel all jobs (keep printer disabled)")
|
||||
_out(f" {CYAN}4){RESET} Restart CUPS service (fixes stale backend)")
|
||||
_out(f" {CYAN}5){RESET} Restart CUPS + re-enable + retry all jobs")
|
||||
_out(f" {CYAN}6){RESET} Do nothing")
|
||||
options = ["1", "2", "3", "4", "5", "6"]
|
||||
elif not queue.enabled:
|
||||
_out(f" {CYAN}1){RESET} Re-enable printer")
|
||||
_out(f" {CYAN}2){RESET} Restart CUPS service (fixes stale backend)")
|
||||
_out(f" {CYAN}3){RESET} Do nothing")
|
||||
options = ["1", "2", "3"]
|
||||
elif queue.jobs:
|
||||
_out(f" {CYAN}1){RESET} Cancel all pending jobs")
|
||||
_out(f" {CYAN}2){RESET} Restart CUPS service (fixes stale backend)")
|
||||
_out(f" {CYAN}3){RESET} Do nothing")
|
||||
options = ["1", "2", "3"]
|
||||
else:
|
||||
_out(f" {CYAN}1){RESET} Restart CUPS service (fixes stale backend)")
|
||||
_out(f" {CYAN}2){RESET} Do nothing")
|
||||
options = ["1", "2"]
|
||||
|
||||
_out()
|
||||
choice = _prompt(f" Choose [{'/'.join(options)}]: ")
|
||||
_out()
|
||||
|
||||
if not queue.enabled and queue.jobs:
|
||||
_handle_disabled_with_jobs(queue, choice)
|
||||
elif not queue.enabled:
|
||||
_handle_disabled_no_jobs(queue, choice)
|
||||
elif queue.jobs:
|
||||
_handle_enabled_with_jobs(queue, choice)
|
||||
else:
|
||||
_handle_backend_errors_only(choice)
|
||||
|
||||
|
||||
def _dwj_enable_only(printer_name: str) -> None:
|
||||
"""Choice 1: re-enable printer so queued jobs are retried."""
|
||||
if _cups_enable_printer(printer_name):
|
||||
_out(f" {GREEN}✓ Printer re-enabled. Jobs will be retried.{RESET}")
|
||||
|
||||
|
||||
def _dwj_cancel_and_enable(printer_name: str) -> None:
|
||||
"""Choice 2: cancel all jobs then re-enable."""
|
||||
_cups_cancel_all_jobs(printer_name)
|
||||
if _cups_enable_printer(printer_name):
|
||||
_out(f" {GREEN}✓ All jobs cancelled and printer re-enabled.{RESET}")
|
||||
|
||||
|
||||
def _dwj_cancel_only(printer_name: str) -> None:
|
||||
"""Choice 3: cancel all jobs."""
|
||||
if _cups_cancel_all_jobs(printer_name):
|
||||
_out(f" {GREEN}✓ All jobs cancelled.{RESET}")
|
||||
|
||||
|
||||
def _dwj_restart_only(_printer_name: str) -> None:
|
||||
"""Choice 4: restart CUPS."""
|
||||
if _cups_restart_service():
|
||||
_out(f" {GREEN}✓ CUPS restarted.{RESET}")
|
||||
|
||||
|
||||
def _dwj_restart_and_enable(printer_name: str) -> None:
|
||||
"""Choice 5: restart CUPS and re-enable printer."""
|
||||
if _cups_restart_service():
|
||||
_cups_enable_printer(printer_name)
|
||||
_out(
|
||||
f" {GREEN}✓ CUPS restarted, printer re-enabled."
|
||||
f" Jobs will be retried.{RESET}"
|
||||
)
|
||||
|
||||
|
||||
_DWJ_ACTIONS: dict[str, Callable[[str], None]] = {
|
||||
"1": _dwj_enable_only,
|
||||
"2": _dwj_cancel_and_enable,
|
||||
"3": _dwj_cancel_only,
|
||||
"4": _dwj_restart_only,
|
||||
"5": _dwj_restart_and_enable,
|
||||
}
|
||||
|
||||
|
||||
def _handle_disabled_with_jobs(queue: CUPSQueueStatus, choice: str) -> None:
|
||||
"""Handle fix for disabled printer with pending jobs."""
|
||||
action = _DWJ_ACTIONS.get(choice)
|
||||
if action is not None:
|
||||
action(queue.printer_name)
|
||||
else:
|
||||
_out(f" {DIM}No changes made.{RESET}")
|
||||
|
||||
|
||||
def _handle_disabled_no_jobs(queue: CUPSQueueStatus, choice: str) -> None:
|
||||
"""Handle fix for disabled printer with no pending jobs."""
|
||||
if choice == "1":
|
||||
if _cups_enable_printer(queue.printer_name):
|
||||
_out(f" {GREEN}✓ Printer re-enabled.{RESET}")
|
||||
elif choice == "2":
|
||||
if _cups_restart_service():
|
||||
_cups_enable_printer(queue.printer_name)
|
||||
_out(f" {GREEN}✓ CUPS restarted and printer re-enabled.{RESET}")
|
||||
else:
|
||||
_out(f" {DIM}No changes made.{RESET}")
|
||||
|
||||
|
||||
def _handle_enabled_with_jobs(queue: CUPSQueueStatus, choice: str) -> None:
|
||||
"""Handle fix for enabled printer with stuck jobs."""
|
||||
if choice == "1":
|
||||
if _cups_cancel_all_jobs(queue.printer_name):
|
||||
_out(f" {GREEN}✓ All jobs cancelled.{RESET}")
|
||||
elif choice == "2":
|
||||
if _cups_restart_service():
|
||||
_out(f" {GREEN}✓ CUPS restarted.{RESET}")
|
||||
else:
|
||||
_out(f" {DIM}No changes made.{RESET}")
|
||||
|
||||
|
||||
def _handle_backend_errors_only(choice: str) -> None:
|
||||
"""Handle fix when only stale backend errors are detected."""
|
||||
if choice == "1":
|
||||
if _cups_restart_service():
|
||||
_out(f" {GREEN}✓ CUPS restarted. Stale backend errors cleared.{RESET}")
|
||||
else:
|
||||
_out(f" {DIM}No changes made.{RESET}")
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
"""CUPS service management, USB port status, and the CUPS-based fallback query.
|
||||
"""CUPS service management and raw USB port status.
|
||||
|
||||
Consumable life tracking lives in consumables.py.
|
||||
The CUPS-based fallback query lives in _cups_fallback.py, and consumable life
|
||||
tracking in consumables.py.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@ -11,30 +12,13 @@ import importlib
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from python_pkg.brother_printer._query import (
|
||||
printer_info_from_cups,
|
||||
run_command_text,
|
||||
)
|
||||
from python_pkg.brother_printer.constants import (
|
||||
_CUPS_REASONS_TO_STATUS,
|
||||
_CUPS_STATE_TO_STATUS,
|
||||
_ERROR_REASON_MAP,
|
||||
BROTHER_USB_VENDOR_ID,
|
||||
DERIVED_CUPS_ERROR,
|
||||
DERIVED_TONER_END,
|
||||
DERIVED_TONER_LOW,
|
||||
)
|
||||
from python_pkg.brother_printer.consumables import estimate_consumable_life
|
||||
from python_pkg.brother_printer.data_classes import (
|
||||
USBPortStatus,
|
||||
USBResult,
|
||||
)
|
||||
from python_pkg.brother_printer.constants import BROTHER_USB_VENDOR_ID
|
||||
from python_pkg.brother_printer.data_classes import USBPortStatus
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import types
|
||||
@ -232,175 +216,3 @@ def _query_usb_port_status_raw(cups_state: str = "") -> USBPortStatus | None:
|
||||
except (OSError, ValueError):
|
||||
logger.debug("USB port status query failed", exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
# ── IPP / CUPS attribute queries ────────────────────────────────────
|
||||
|
||||
|
||||
def _parse_ipp_attributes(output: str) -> dict[str, str]:
|
||||
"""Parse ipptool verbose output into an attribute dict."""
|
||||
attrs: dict[str, str] = {}
|
||||
for line in output.splitlines():
|
||||
match = re.match(r"\s+(\S+)\s+\([^)]+\)\s+=\s+(.*)", line)
|
||||
if match:
|
||||
attrs[match.group(1)] = match.group(2).strip()
|
||||
return attrs
|
||||
|
||||
|
||||
def _get_cups_ipp_status(printer_name: str) -> dict[str, str]:
|
||||
"""Query printer attributes via CUPS IPP using ipptool."""
|
||||
ipptool_path = shutil.which("ipptool")
|
||||
if not ipptool_path:
|
||||
return {}
|
||||
uri = f"ipp://localhost/printers/{printer_name}"
|
||||
try:
|
||||
r = subprocess.run(
|
||||
[ipptool_path, "-tv", uri, "get-printer-attributes.test"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
check=False,
|
||||
)
|
||||
return _parse_ipp_attributes(r.stdout)
|
||||
except (subprocess.TimeoutExpired, subprocess.SubprocessError, OSError):
|
||||
return {}
|
||||
|
||||
|
||||
def _get_cups_economode(printer_name: str) -> str:
|
||||
"""Query toner save mode setting via lpoptions."""
|
||||
lpoptions_path = shutil.which("lpoptions")
|
||||
if not lpoptions_path:
|
||||
return ""
|
||||
command = [lpoptions_path, "-p", printer_name, "-l"]
|
||||
for line in run_command_text(command).splitlines():
|
||||
if "conomode" in line.lower():
|
||||
match = re.search(r"\*(\w+)", line)
|
||||
if match:
|
||||
return "ON" if match.group(1).lower() == "true" else "OFF"
|
||||
return ""
|
||||
|
||||
|
||||
# ── Status code mapping ──────────────────────────────────────────────
|
||||
|
||||
|
||||
def _map_cups_to_status_code(state: str, reasons: str) -> str:
|
||||
"""Map CUPS state + reasons to a Brother PJL status code string."""
|
||||
for keyword, code in _CUPS_REASONS_TO_STATUS.items():
|
||||
if keyword in reasons.lower():
|
||||
return str(code)
|
||||
clean_state = re.sub(r"\(.*\)", "", state).strip().lower()
|
||||
return str(_CUPS_STATE_TO_STATUS.get(clean_state, 10001))
|
||||
|
||||
|
||||
def _cups_reasons_to_error(cups_reasons: str) -> tuple[str, str]:
|
||||
"""Map CUPS reason keywords to a (status_code, display) pair."""
|
||||
reasons_lower = cups_reasons.lower()
|
||||
for keywords, code, display in _ERROR_REASON_MAP:
|
||||
if any(kw in reasons_lower for kw in keywords):
|
||||
return code, display
|
||||
# Nothing recognised. Show what CUPS actually said rather than a bare
|
||||
# "Printer Error", which tells the reader nothing they can act on.
|
||||
detail = cups_reasons.strip()
|
||||
if detail and detail.lower() not in {"none", ""}:
|
||||
return DERIVED_CUPS_ERROR, f"Printer Error (CUPS reports: {detail})"
|
||||
return DERIVED_CUPS_ERROR, "Printer Error (CUPS gave no reason)"
|
||||
|
||||
|
||||
def _port_status_to_status_code(
|
||||
ps: USBPortStatus,
|
||||
cups_reasons: str,
|
||||
) -> tuple[str, str]:
|
||||
"""Map USB port status + CUPS reasons to (status_code, display)."""
|
||||
# The port status exposes only paper_empty/error/online bits, so anything
|
||||
# more specific than "out of paper" has to come from the CUPS reasons -
|
||||
# an error bit alone does not tell us the cover is open.
|
||||
if ps.paper_empty:
|
||||
return "41000", "No Paper"
|
||||
if ps.error:
|
||||
return _cups_reasons_to_error(cups_reasons)
|
||||
if not ps.online:
|
||||
return "10002", "Offline / Sleep"
|
||||
return "", ""
|
||||
|
||||
|
||||
# ── CUPS printer name discovery ──────────────────────────────────────
|
||||
|
||||
|
||||
def find_cups_printer_name() -> str:
|
||||
"""Find the CUPS queue name for a Brother printer."""
|
||||
lpstat_path = shutil.which("lpstat")
|
||||
if not lpstat_path:
|
||||
return ""
|
||||
for line in run_command_text([lpstat_path, "-v"]).splitlines():
|
||||
if "brother" in line.lower():
|
||||
match = re.match(r"device for (\S+):", line)
|
||||
if match:
|
||||
return match.group(1)
|
||||
return ""
|
||||
|
||||
|
||||
# ── CUPS-based USB fallback query ────────────────────────────────────
|
||||
|
||||
|
||||
def query_usb_via_cups() -> USBResult:
|
||||
"""Query USB printer status through CUPS when /dev/usb/lp* is unavailable."""
|
||||
_ensure_cups_running()
|
||||
printer_name = find_cups_printer_name()
|
||||
if not printer_name:
|
||||
return USBResult(
|
||||
error="No USB printer device at /dev/usb/lp*"
|
||||
" (usblp module not available)"
|
||||
" and no Brother printer found in CUPS.",
|
||||
)
|
||||
|
||||
pyusb_info = _get_pyusb_device_info()
|
||||
cups_info = printer_info_from_cups()
|
||||
|
||||
result = USBResult(
|
||||
device="cups",
|
||||
product=(
|
||||
pyusb_info.get("product")
|
||||
or cups_info.get("product")
|
||||
or "Brother Laser Printer"
|
||||
),
|
||||
serial=pyusb_info.get("serial") or cups_info.get("serial", ""),
|
||||
)
|
||||
|
||||
ipp = _get_cups_ipp_status(printer_name)
|
||||
state = ipp.get("printer-state", "")
|
||||
reasons = ipp.get("printer-state-reasons", "none")
|
||||
result.economode = _get_cups_economode(printer_name)
|
||||
|
||||
port_status = _query_usb_port_status_raw(state)
|
||||
if port_status is not None:
|
||||
result.port_status = port_status
|
||||
hw_code, hw_display = _port_status_to_status_code(
|
||||
port_status,
|
||||
reasons,
|
||||
)
|
||||
if hw_code:
|
||||
result.status_code = hw_code
|
||||
result.display = hw_display
|
||||
result.online = "TRUE" if port_status.online else "FALSE"
|
||||
return result
|
||||
estimate = estimate_consumable_life()
|
||||
if estimate.toner_exhausted:
|
||||
result.status_code = DERIVED_TONER_END
|
||||
result.display = "Toner End (estimated from page count)"
|
||||
result.online = "TRUE"
|
||||
return result
|
||||
if estimate.toner_low:
|
||||
result.status_code = DERIVED_TONER_LOW
|
||||
result.display = "Toner Low (estimated from page count)"
|
||||
result.online = "TRUE"
|
||||
return result
|
||||
result.status_code = _map_cups_to_status_code(state, reasons)
|
||||
result.display = ipp.get("printer-state-message", "")
|
||||
result.online = "TRUE"
|
||||
return result
|
||||
|
||||
result.status_code = _map_cups_to_status_code(state, reasons)
|
||||
result.display = ipp.get("printer-state-message", "")
|
||||
result.online = "TRUE" if state.lower() in {"idle", "processing"} else "FALSE"
|
||||
|
||||
return result
|
||||
|
||||
@ -9,6 +9,12 @@ from typing import TYPE_CHECKING
|
||||
# Re-exported through __all__: tests/test_display.py imports these names from
|
||||
# this module. Only the un-patched supply *maths* moved to _supply -- everything
|
||||
# the tests reach with mock.patch has to stay resolvable here.
|
||||
from python_pkg.brother_printer._page_count import (
|
||||
_display_consumables_reference,
|
||||
_display_page_count_estimate,
|
||||
_display_page_delivery_warning,
|
||||
)
|
||||
from python_pkg.brother_printer._queue_fix import display_cups_queue_status
|
||||
from python_pkg.brother_printer._severity import (
|
||||
_SEVERITY_COLORS,
|
||||
_SEVERITY_ICONS,
|
||||
@ -21,29 +27,19 @@ from python_pkg.brother_printer._supply import (
|
||||
_format_supply_bar,
|
||||
_parse_supply_value,
|
||||
_process_supply_item,
|
||||
render_life_bar,
|
||||
)
|
||||
from python_pkg.brother_printer.constants import (
|
||||
BOLD,
|
||||
CYAN,
|
||||
DIM,
|
||||
DRUM_RATED_PAGES,
|
||||
GREEN,
|
||||
RED,
|
||||
RESET,
|
||||
TONER_RATED_PAGES,
|
||||
YELLOW,
|
||||
_out,
|
||||
get_status_info,
|
||||
)
|
||||
from python_pkg.brother_printer.consumables import (
|
||||
check_page_delivery,
|
||||
estimate_consumable_life,
|
||||
)
|
||||
from python_pkg.brother_printer.cups_queue import (
|
||||
display_cups_queue_status,
|
||||
get_cups_queue_status,
|
||||
)
|
||||
from python_pkg.brother_printer.cups_queue import get_cups_queue_status
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from python_pkg.brother_printer.data_classes import (
|
||||
@ -72,98 +68,6 @@ def _display_report_header() -> None:
|
||||
_out()
|
||||
|
||||
|
||||
def _display_page_delivery_warning(printer_total: int, *, queue_idle: bool) -> None:
|
||||
"""Warn when CUPS claims more pages than the printer actually counted.
|
||||
|
||||
Args:
|
||||
printer_total: Lifetime count from the printer's own counter.
|
||||
queue_idle: False while a job is queued or printing, when the two
|
||||
counters legitimately disagree.
|
||||
"""
|
||||
check = check_page_delivery(printer_total, queue_idle=queue_idle)
|
||||
if not check.suspected:
|
||||
return
|
||||
_out(f"{BOLD}── Dropped Pages ──{RESET}")
|
||||
_out()
|
||||
_out(
|
||||
f" {RED}{BOLD}⚠ {check.dropped} pages did not print.{RESET}"
|
||||
f" {RED}CUPS sent {check.cups_pages} pages since the last check;"
|
||||
f" the printer's own counter advanced by"
|
||||
f" {check.printer_pages}.{RESET}"
|
||||
)
|
||||
_out()
|
||||
_out(
|
||||
f" {DIM}The printer discards pages whose 600 dpi raster does not fit"
|
||||
f" its memory, stays READY, and reports no error - and CUPS still calls"
|
||||
f" the job successful. Reprint at a lower resolution:{RESET}"
|
||||
)
|
||||
_out(f" {DIM} lp -o Resolution=300dpi <file>{RESET}")
|
||||
_out()
|
||||
|
||||
|
||||
def _display_page_count_estimate(printer_total: int = 0) -> None:
|
||||
"""Show estimated consumable life based on the printer's page count.
|
||||
|
||||
Args:
|
||||
printer_total: Lifetime count from the printer's own counter, or zero
|
||||
when it could not be read and the CUPS page log has to stand in.
|
||||
"""
|
||||
estimate = estimate_consumable_life(printer_total)
|
||||
if estimate.total_pages <= 0:
|
||||
return
|
||||
_out(f"{BOLD}── Page Count Estimate ──{RESET}")
|
||||
_out()
|
||||
_out(
|
||||
f" {BOLD}Total pages printed:{RESET} {estimate.total_pages}"
|
||||
f" (toner: {estimate.toner_pages} since replacement,"
|
||||
f" drum: {estimate.drum_pages} since replacement)"
|
||||
)
|
||||
if estimate.approximate:
|
||||
_out(
|
||||
f" {YELLOW}Approximate: counted from the CUPS log, not the"
|
||||
f" printer's own counter, so it misses pages CUPS never saw"
|
||||
f" and reads high.{RESET}"
|
||||
)
|
||||
_out()
|
||||
render_life_bar(
|
||||
"Toner:",
|
||||
estimate.toner_pct_remaining,
|
||||
exhausted=estimate.toner_exhausted,
|
||||
low=estimate.toner_low,
|
||||
exhausted_note=" ← REPLACE NOW",
|
||||
low_note=" ← order soon",
|
||||
)
|
||||
render_life_bar(
|
||||
"Drum: ",
|
||||
estimate.drum_pct_remaining,
|
||||
low=estimate.drum_near_end,
|
||||
low_note=" ← nearing end",
|
||||
)
|
||||
_out(
|
||||
f" {DIM}Based on pages since last replacement"
|
||||
f" vs rated capacity (toner ~{TONER_RATED_PAGES},"
|
||||
f" drum ~{DRUM_RATED_PAGES}).{RESET}"
|
||||
)
|
||||
_out(f" {DIM}Reset after replacing: --reset-toner or --reset-drum{RESET}")
|
||||
if estimate.toner_exhausted:
|
||||
_out()
|
||||
_out(
|
||||
f" {RED}{BOLD}⚠ Toner is likely exhausted."
|
||||
f" This is probably why the orange light is flashing.{RESET}"
|
||||
)
|
||||
_out()
|
||||
|
||||
|
||||
def _display_consumables_reference() -> None:
|
||||
"""Print compatible consumables reference."""
|
||||
_out(f"{BOLD}── Compatible Consumables ──{RESET}")
|
||||
_out()
|
||||
_out(f" {BOLD}Toner:{RESET} TN-1050 / TN-1030 (or compatible third-party)")
|
||||
_out(f" {BOLD}Drum:{RESET} DR-1050 / DR-1030 (or compatible third-party)")
|
||||
_out(f" {DIM} Toner rated ~1000 pages; Drum rated ~10000 pages.{RESET}")
|
||||
_out()
|
||||
|
||||
|
||||
# ── USB display helpers ──────────────────────────────────────────────
|
||||
|
||||
|
||||
|
||||
@ -9,16 +9,21 @@ from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer._page_delivery import (
|
||||
_snapshot_counters,
|
||||
check_page_delivery,
|
||||
)
|
||||
from python_pkg.brother_printer.consumables import (
|
||||
STATE_SCHEMA_CUPS_SCALE,
|
||||
STATE_SCHEMA_PRINTER_SCALE,
|
||||
_cups_total_on_printer_scale,
|
||||
_migrate_state_to_printer_scale,
|
||||
_snapshot_counters,
|
||||
check_page_delivery,
|
||||
)
|
||||
|
||||
MOD = "python_pkg.brother_printer.consumables"
|
||||
# check_page_delivery and _snapshot_counters moved to _page_delivery, so the
|
||||
# state-file helpers they call resolve through that module's globals instead.
|
||||
MOD_PD = "python_pkg.brother_printer._page_delivery"
|
||||
|
||||
|
||||
class TestMigrateStateToPrinterScale:
|
||||
@ -113,9 +118,9 @@ class TestCheckPageDelivery:
|
||||
never actually came out.
|
||||
"""
|
||||
|
||||
@patch(f"{MOD}._snapshot_counters")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1841)
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD_PD}._snapshot_counters")
|
||||
@patch(f"{MOD_PD}._get_cups_total_pages", return_value=1841)
|
||||
@patch(f"{MOD_PD}._load_consumable_state")
|
||||
def test_detects_dropped_pages(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
@ -133,9 +138,9 @@ class TestCheckPageDelivery:
|
||||
assert check.dropped == 63
|
||||
assert check.suspected is True
|
||||
|
||||
@patch(f"{MOD}._snapshot_counters")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1841)
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD_PD}._snapshot_counters")
|
||||
@patch(f"{MOD_PD}._get_cups_total_pages", return_value=1841)
|
||||
@patch(f"{MOD_PD}._load_consumable_state")
|
||||
def test_healthy_job_does_not_warn(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
@ -150,9 +155,9 @@ class TestCheckPageDelivery:
|
||||
assert check.dropped == 0
|
||||
assert check.suspected is False
|
||||
|
||||
@patch(f"{MOD}._snapshot_counters")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1780)
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD_PD}._snapshot_counters")
|
||||
@patch(f"{MOD_PD}._get_cups_total_pages", return_value=1780)
|
||||
@patch(f"{MOD_PD}._load_consumable_state")
|
||||
def test_small_gap_is_not_a_warning(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
@ -175,9 +180,9 @@ class TestCheckPageDelivery:
|
||||
def test_skipped_without_printer_count(self) -> None:
|
||||
assert check_page_delivery(0, queue_idle=True).suspected is False
|
||||
|
||||
@patch(f"{MOD}._snapshot_counters")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1841)
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD_PD}._snapshot_counters")
|
||||
@patch(f"{MOD_PD}._get_cups_total_pages", return_value=1841)
|
||||
@patch(f"{MOD_PD}._load_consumable_state")
|
||||
def test_first_run_only_establishes_baseline(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
@ -189,9 +194,9 @@ class TestCheckPageDelivery:
|
||||
assert check.suspected is False
|
||||
mock_snap.assert_called_once()
|
||||
|
||||
@patch(f"{MOD}._snapshot_counters")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=10)
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD_PD}._snapshot_counters")
|
||||
@patch(f"{MOD_PD}._get_cups_total_pages", return_value=10)
|
||||
@patch(f"{MOD_PD}._load_consumable_state")
|
||||
def test_log_rotation_draws_no_conclusion(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
@ -206,9 +211,9 @@ class TestCheckPageDelivery:
|
||||
check = check_page_delivery(2087, queue_idle=True)
|
||||
assert check.suspected is False
|
||||
|
||||
@patch(f"{MOD}._snapshot_counters")
|
||||
@patch(f"{MOD}._get_cups_total_pages", return_value=1841)
|
||||
@patch(f"{MOD}._load_consumable_state")
|
||||
@patch(f"{MOD_PD}._snapshot_counters")
|
||||
@patch(f"{MOD_PD}._get_cups_total_pages", return_value=1841)
|
||||
@patch(f"{MOD_PD}._load_consumable_state")
|
||||
def test_printer_counter_reset_draws_no_conclusion(
|
||||
self,
|
||||
mock_load: MagicMock,
|
||||
@ -224,7 +229,7 @@ class TestCheckPageDelivery:
|
||||
|
||||
|
||||
class TestSnapshotCounters:
|
||||
@patch(f"{MOD}._save_consumable_state")
|
||||
@patch(f"{MOD_PD}._save_consumable_state")
|
||||
def test_writes_new_snapshot(self, mock_save: MagicMock) -> None:
|
||||
state = {"last_printer_count": 2000, "last_cups_total": 1700}
|
||||
_snapshot_counters(state, 2087, 1778)
|
||||
@ -232,7 +237,7 @@ class TestSnapshotCounters:
|
||||
assert saved["last_printer_count"] == 2087
|
||||
assert saved["last_cups_total"] == 1778
|
||||
|
||||
@patch(f"{MOD}._save_consumable_state")
|
||||
@patch(f"{MOD_PD}._save_consumable_state")
|
||||
def test_unchanged_counters_skip_the_write(self, mock_save: MagicMock) -> None:
|
||||
"""Do not rewrite the file on every run when nothing moved."""
|
||||
state = {"last_printer_count": 2087, "last_cups_total": 1778}
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
"""Tests for brother_printer.cups_queue module - part 2 (interactive fix)."""
|
||||
"""Tests for brother_printer._queue_fix module - part 2 (interactive fix)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import StringIO
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer.cups_queue import (
|
||||
from python_pkg.brother_printer._queue_fix import (
|
||||
_dwj_cancel_and_enable,
|
||||
_dwj_cancel_only,
|
||||
_dwj_enable_only,
|
||||
@ -19,7 +19,7 @@ from python_pkg.brother_printer.cups_queue import (
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import CUPSJob, CUPSQueueStatus
|
||||
|
||||
MOD = "python_pkg.brother_printer.cups_queue"
|
||||
MOD = "python_pkg.brother_printer._queue_fix"
|
||||
|
||||
|
||||
# ── _offer_queue_fix ─────────────────────────────────────────────────
|
||||
|
||||
@ -1,16 +1,16 @@
|
||||
"""Tests for brother_printer.cups_queue module - part 3 (display status)."""
|
||||
"""Tests for brother_printer._queue_fix module - part 3 (display status)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import StringIO
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer.cups_queue import (
|
||||
from python_pkg.brother_printer._queue_fix import (
|
||||
display_cups_queue_status,
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import CUPSJob, CUPSQueueStatus
|
||||
|
||||
MOD = "python_pkg.brother_printer.cups_queue"
|
||||
MOD = "python_pkg.brother_printer._queue_fix"
|
||||
|
||||
|
||||
class TestDisplayCupsQueueStatus:
|
||||
|
||||
@ -1,27 +1,27 @@
|
||||
"""Tests for brother_printer.cups_service module - part 2."""
|
||||
"""Tests for brother_printer._cups_fallback module - part 2."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer.constants import (
|
||||
_CUPS_REASONS_TO_STATUS,
|
||||
DERIVED_CUPS_ERROR,
|
||||
get_status_info,
|
||||
)
|
||||
from python_pkg.brother_printer.cups_service import (
|
||||
from python_pkg.brother_printer._cups_fallback import (
|
||||
_cups_reasons_to_error,
|
||||
_get_cups_economode,
|
||||
_map_cups_to_status_code,
|
||||
_port_status_to_status_code,
|
||||
find_cups_printer_name,
|
||||
)
|
||||
from python_pkg.brother_printer.constants import (
|
||||
_CUPS_REASONS_TO_STATUS,
|
||||
DERIVED_CUPS_ERROR,
|
||||
get_status_info,
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import (
|
||||
USBPortStatus,
|
||||
)
|
||||
|
||||
MOD = "python_pkg.brother_printer.cups_service"
|
||||
MOD = "python_pkg.brother_printer._cups_fallback"
|
||||
|
||||
|
||||
# ── _get_cups_economode ──────────────────────────────────────────────
|
||||
|
||||
@ -1,22 +1,22 @@
|
||||
"""Tests for brother_printer.cups_service module - part 3 (query_usb_via_cups)."""
|
||||
"""Tests for brother_printer._cups_fallback module - part 3 (query_usb_via_cups)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer._cups_fallback import (
|
||||
query_usb_via_cups,
|
||||
)
|
||||
from python_pkg.brother_printer.constants import (
|
||||
DERIVED_TONER_END,
|
||||
DERIVED_TONER_LOW,
|
||||
)
|
||||
from python_pkg.brother_printer.cups_service import (
|
||||
query_usb_via_cups,
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import (
|
||||
PageCountEstimate,
|
||||
USBPortStatus,
|
||||
)
|
||||
|
||||
MOD = "python_pkg.brother_printer.cups_service"
|
||||
MOD = "python_pkg.brother_printer._cups_fallback"
|
||||
|
||||
|
||||
# ── query_usb_via_cups ───────────────────────────────────────────────
|
||||
|
||||
@ -1,16 +1,16 @@
|
||||
"""Tests for brother_printer.cups_service module - part 4 (IPP queries)."""
|
||||
"""Tests for brother_printer._cups_fallback module - part 4 (IPP queries)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer.cups_service import (
|
||||
from python_pkg.brother_printer._cups_fallback import (
|
||||
_get_cups_ipp_status,
|
||||
_parse_ipp_attributes,
|
||||
)
|
||||
|
||||
MOD = "python_pkg.brother_printer.cups_service"
|
||||
MOD = "python_pkg.brother_printer._cups_fallback"
|
||||
|
||||
|
||||
class TestParseIppAttributes:
|
||||
|
||||
@ -1,21 +1,21 @@
|
||||
"""Tests for brother_printer.display - page counts and dropped-page warning."""
|
||||
"""Tests for brother_printer._page_count - page counts and dropped pages."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import StringIO
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer.data_classes import (
|
||||
PageCountEstimate,
|
||||
PageDeliveryCheck,
|
||||
)
|
||||
from python_pkg.brother_printer.display import (
|
||||
from python_pkg.brother_printer._page_count import (
|
||||
_display_consumables_reference,
|
||||
_display_page_count_estimate,
|
||||
_display_page_delivery_warning,
|
||||
)
|
||||
from python_pkg.brother_printer.data_classes import (
|
||||
PageCountEstimate,
|
||||
PageDeliveryCheck,
|
||||
)
|
||||
|
||||
MOD = "python_pkg.brother_printer.display"
|
||||
MOD = "python_pkg.brother_printer._page_count"
|
||||
|
||||
|
||||
class TestDisplayPageCountEstimate:
|
||||
@ -251,7 +251,7 @@ class TestQueryUsbPjl:
|
||||
@patch(f"{MOD}.find_usb_printer_dev", return_value=None)
|
||||
def test_no_dev_falls_back_to_cups(self, f: MagicMock) -> None:
|
||||
with patch(
|
||||
"python_pkg.brother_printer.cups_service.query_usb_via_cups",
|
||||
"python_pkg.brother_printer._cups_fallback.query_usb_via_cups",
|
||||
) as mock_cups:
|
||||
mock_cups.return_value = USBResult(device="cups")
|
||||
result = query_usb_pjl()
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
"""Tests for brother_printer.usb_query - the PJL wire protocol.
|
||||
"""Tests for brother_printer._pjl_io - the PJL wire protocol.
|
||||
|
||||
The printer's fd is non-blocking throughout: usblp blocks forever on open
|
||||
and on writes whenever the printer is unwell, which is exactly when a status
|
||||
@ -9,7 +9,7 @@ from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from python_pkg.brother_printer.usb_query import (
|
||||
from python_pkg.brother_printer._pjl_io import (
|
||||
_drain_buffer,
|
||||
_read_nonblocking,
|
||||
_wait_for_pjl_response,
|
||||
@ -17,7 +17,7 @@ from python_pkg.brother_printer.usb_query import (
|
||||
pjl_query,
|
||||
)
|
||||
|
||||
MOD = "python_pkg.brother_printer.usb_query"
|
||||
MOD = "python_pkg.brother_printer._pjl_io"
|
||||
|
||||
|
||||
class TestDrainBuffer:
|
||||
|
||||
@ -1,18 +1,25 @@
|
||||
"""USB printer discovery and PJL query functions."""
|
||||
"""USB printer discovery and PJL query functions.
|
||||
|
||||
The non-blocking PJL transport lives in _pjl_io.py. Its three entry points are
|
||||
imported back here because tests/test_usb_query.py patches them on this module.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import errno
|
||||
import importlib
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import select
|
||||
import shutil
|
||||
import time
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from python_pkg.brother_printer._pjl_io import (
|
||||
_drain_buffer,
|
||||
_write_with_deadline,
|
||||
pjl_query,
|
||||
)
|
||||
from python_pkg.brother_printer._query import (
|
||||
printer_info_from_cups,
|
||||
run_command_text,
|
||||
@ -45,100 +52,6 @@ def find_usb_printer_dev() -> str | None:
|
||||
return str(devices[0]) if devices else None
|
||||
|
||||
|
||||
# ── PJL over USB ─────────────────────────────────────────────────────
|
||||
|
||||
|
||||
# The printer's fd is opened and kept non-blocking. usblp blocks indefinitely
|
||||
# on a plain open() and on writes whenever the printer is not ready to talk -
|
||||
# stuck mid-job, wedged, or simply asleep - so a blocking fd turns "the printer
|
||||
# is unwell" into "this tool hangs forever", which is the worst possible answer
|
||||
# when a status report is exactly what you wanted.
|
||||
|
||||
|
||||
def _drain_buffer(fd: int) -> None:
|
||||
"""Read and discard any stale data from the USB buffer."""
|
||||
with contextlib.suppress(OSError):
|
||||
while os.read(fd, 4096):
|
||||
pass
|
||||
|
||||
|
||||
def _write_with_deadline(fd: int, data: bytes, deadline: float) -> bool:
|
||||
"""Write all of data to a non-blocking fd. Returns False if the deadline passes.
|
||||
|
||||
Args:
|
||||
fd: Non-blocking file descriptor for the printer.
|
||||
data: Bytes to send.
|
||||
deadline: Absolute monotonic-ish time (time.time()) to give up at.
|
||||
|
||||
Returns:
|
||||
True when everything was written, False on timeout or write error.
|
||||
"""
|
||||
sent = 0
|
||||
while sent < len(data):
|
||||
remaining = deadline - time.time()
|
||||
if remaining <= 0:
|
||||
return False
|
||||
try:
|
||||
sent += os.write(fd, data[sent:])
|
||||
except BlockingIOError:
|
||||
# Printer's buffer is full or it is not accepting data: wait for it
|
||||
# to become writable rather than spinning or blocking forever.
|
||||
_, writable, _ = select.select([], [fd], [], min(remaining, 0.5))
|
||||
if not writable:
|
||||
continue
|
||||
except OSError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _read_nonblocking(fd: int) -> bytes:
|
||||
"""Read all currently available data from a non-blocking fd."""
|
||||
data = b""
|
||||
with contextlib.suppress(OSError):
|
||||
while True:
|
||||
chunk = os.read(fd, 4096)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
return data
|
||||
|
||||
|
||||
def _wait_for_pjl_response(fd: int, deadline: float) -> bytes:
|
||||
"""Poll fd until PJL data arrives or deadline expires."""
|
||||
response = b""
|
||||
while time.time() < deadline:
|
||||
remaining = deadline - time.time()
|
||||
if remaining <= 0:
|
||||
break
|
||||
readable, _, _ = select.select([fd], [], [], min(remaining, 1.0))
|
||||
if readable:
|
||||
response += _read_nonblocking(fd)
|
||||
if response and (b"=" in response or b"@PJL" in response):
|
||||
break
|
||||
return response
|
||||
|
||||
|
||||
def pjl_query(fd: int, cmd: str, timeout_sec: float = 5.0) -> str:
|
||||
"""Send a PJL command via raw fd and read the response.
|
||||
|
||||
Args:
|
||||
fd: Non-blocking file descriptor for the printer.
|
||||
cmd: PJL command, e.g. "@PJL INFO STATUS".
|
||||
timeout_sec: Total budget for sending the command and reading the reply.
|
||||
|
||||
Returns:
|
||||
The printer's reply, or "" if it did not answer in time. A silent
|
||||
printer is a normal outcome here, not an error: it happens whenever the
|
||||
printer is busy digesting a job.
|
||||
"""
|
||||
deadline = time.time() + timeout_sec
|
||||
pjl_cmd = f"\x1b%-12345X@PJL\r\n{cmd}\r\n\x1b%-12345X"
|
||||
if not _write_with_deadline(fd, pjl_cmd.encode(), deadline):
|
||||
return ""
|
||||
response = _wait_for_pjl_response(fd, deadline)
|
||||
return response.decode("ascii", errors="replace")
|
||||
|
||||
|
||||
def _parse_status(resp: str, result: USBResult) -> bool:
|
||||
"""Parse STATUS response into result. Returns True if code was found."""
|
||||
found = False
|
||||
@ -227,10 +140,10 @@ def query_usb_pjl(max_retries: int = 2) -> USBResult:
|
||||
"""Query a Brother printer via PJL over /dev/usb/lp*."""
|
||||
dev_path = find_usb_printer_dev()
|
||||
if not dev_path:
|
||||
cups_service = importlib.import_module(
|
||||
"python_pkg.brother_printer.cups_service",
|
||||
cups_fallback = importlib.import_module(
|
||||
"python_pkg.brother_printer._cups_fallback",
|
||||
)
|
||||
return cups_service.query_usb_via_cups()
|
||||
return cups_fallback.query_usb_via_cups()
|
||||
|
||||
result = _init_usb_result(dev_path)
|
||||
if not os.access(dev_path, os.R_OK | os.W_OK):
|
||||
|
||||
Loading…
Reference in New Issue
Block a user