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