WIP: Multi-printers #32

Draft
n07070 wants to merge 29 commits from multi-printers into master
Showing only changes of commit ebb317b98e - Show all commits

View File

@@ -379,17 +379,19 @@ class BrotherPrinter(Printer):
def __init__(self, app, vendor_id, device_id):
super().__init__(
app, vendor_id="", device_id="", printer_type=PrinterType.BROTHER
app, vendor_id, device_id, printer_type=PrinterType.BROTHER
)
self.printer = None
self.usb_args = {}
self.usb_args["idVendor"] = self.device_id
self.usb_args["idProduct"] = self.vendor_id
self.usb_args["idVendor"] = self.vendor_id
self.usb_args["idProduct"] = self.device_id
self.model_manager = ModelsManager()
# Code taken from https://github.com/5shekel/printit/blob/master/printer_utils.py
self.app.logger.debug("Creating backend for Brother")
backend = backend_factory("pyusb")
available_devices = backend["list_available_devices"]()
for printer in available_devices:
@@ -408,14 +410,19 @@ class BrotherPrinter(Printer):
serial_number = parts[3]
try:
product_id_int = int(self.device_id, 16)
for m in self.model_manager.iter_elements():
if m.product_id == product_id_int:
if m.product_id == self.device_id:
model = m.identifier
break
self.app.logger.debug(f"Matched printer model: {model}")
except ValueError:
self.app.logger.warning(f"Invalid product ID format: {m.product_id}")
except ValueError as ve:
self.app.logger.warning("Invalid product ID format:"+ str(ve))
raise ve
except Exception as e:
self.app.logger.error("Error while finding a model ? : " + str(e))
raise e
self.printer_info = PrinterInfo(
identifier=identifier,
@@ -426,7 +433,7 @@ class BrotherPrinter(Printer):
product_id=self.device_id,
serial_number=serial_number,
)
self.app.logger.debug("Created a Brother printer !")
self.ready = True
def _has_paper(self):
@@ -439,17 +446,19 @@ class BrotherPrinter(Printer):
"""
Print a raster image via a Brother QL printer
"""
self.ready = False
label_type = "102"
rotate = 0
dither = False
data = _process_image(self, path=data, max_width=720, max_height=720)
try:
# Prepare the image for printing
qlr = BrotherQLRaster(self.printer_info["model"])
instructions = convert(
qlr=qlr,
images=[data["img"]],
images=[data],
label=label_type,
rotate=rotate,
threshold=70,
@@ -486,6 +495,7 @@ class BrotherPrinter(Printer):
printer_identifier=self.printer_info["identifier"],
backend_identifier="pyusb",
)
self.app.logger.debug("Status: " + str(status))
if (
not status["did_print"]
@@ -494,10 +504,11 @@ class BrotherPrinter(Printer):
):
raise RuntimeError("Failed to print using Python API")
if status["printer_state"]:
self.ready = bool(status["printer_state"])
else:
self.ready = True
# if status["printer_state"]:
# self.ready = bool(status["printer_state"])
# self.app.logger.debug("Printer is borky : " + str(self.ready))
# else:
# self.ready = True
except usb.core.USBError as e:
# Treat timeout errors as successful since they often occur after print completion
@@ -508,29 +519,29 @@ class BrotherPrinter(Printer):
self.app.logger.debug("Print completed (timeout is normal)")
self.ready = True
error_msg = f"USBError encountered: {e}"
self.app.logger.debug(error_msg)
self.app.logger.debug(f"USBError encountered: {e}")
raise RuntimeError from e
except Exception as e:
error_msg = f"Unexpected error during printing: {str(e)}"
self.app.logger.debug(error_msg)
self.app.logger.debug(f"Unexpected error during printing: {str(e)}")
raise RuntimeError from e
def print_task(self, task_type, data):
"""Execute actual print based on task type"""
with self._lock:
if self._state:
self._state = False
match (task_type.value):
case "image":
self._print_img(data["img"])
self._state = True
case "cut":
# The cut happens by default on Brother QL printers.
self._state = True
case _:
raise RuntimeError("This task type is not supported")
if self.ready:
try:
match (task_type.value):
case "image":
self._print_img(data["img"])
case "cut":
# The cut happens by default on Brother QL printers.
pass
case _:
raise RuntimeError("This task type is not supported")
except Exception as e:
raise e
# end try
else:
raise RuntimeError("The printer is not ready to print yet !")
@@ -539,12 +550,10 @@ class BrotherPrinter(Printer):
# raise NotImplementedError("This printer type is not implemented yet")
def _process_image(self, path):
def _process_image(self, path, max_width=575, max_height=1000):
brightness_factor = 1.5 # Used only if image is too dark
brightness_threshold = 100 # Brightness threshold (0–255)
contrast_factor = 2 # Less than 1.0 = lower contrast
max_width = 575
max_height = 1000
with Image.open(path) as original_img:
# Convert to RGB if needed (JPEG doesn't support alpha)
@@ -553,7 +562,7 @@ def _process_image(self, path):
original_img = original_img.convert("RGB")
# Resize while maintaining aspect ratio
original_img.thumbnail((max_width, max_height), Image.Resampling.LANCZOS)
original_img = original_img.resize((max_width, max_height), Image.Resampling.LANCZOS)
self.app.logger.debug("Resized the image")
# # Convert to grayscale for dithering