Change the way cuts are managed, rewrite lock mechanism, add support for
multiple printers
This commit is contained in:
1 parent
aa1f9d1532
commit
52205be6af
8 files changed
+439
-322
No files matched your search
+223
-122
@@ -9,22 +9,24 @@ from dataclasses import dataclass
|
||||
import time
|
||||
from enum import Enum
|
||||
import uuid
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
import usb.core
|
||||
from PIL import Image, ImageEnhance, ImageDraw, ImageFont
|
||||
from PIL import Image, ImageEnhance, ImageDraw, ImageFont, ImageOps
|
||||
import numpy as np
|
||||
|
||||
# Importing the modules needed for each supported printer Type
|
||||
import escpos.printer
|
||||
from brother_ql.models import ModelsManager
|
||||
from brother_ql.labels import LabelsManager, FormFactor
|
||||
from brother_ql.backends import backend_factory, guess_backend
|
||||
from brother_ql.raster import BrotherQLRaster
|
||||
from brother_ql.conversion import convert
|
||||
from brother_ql.backends.helpers import send
|
||||
from brother_ql import create_label
|
||||
|
||||
# Used for typing
|
||||
from task import PrintTask
|
||||
|
||||
class PrinterType(Enum):
|
||||
"""
|
||||
@@ -78,7 +80,6 @@ class Printer(ABC):
|
||||
self.device_id = device_id
|
||||
self.ready = False
|
||||
self.printer_type = printer_type
|
||||
self._lock = threading.Lock()
|
||||
self.used = False
|
||||
|
||||
@abstractmethod
|
||||
@@ -90,7 +91,7 @@ class Printer(ABC):
|
||||
"""Reports the state of the Printer"""
|
||||
|
||||
@abstractmethod
|
||||
def print_task(self, task_type, data) -> None:
|
||||
def print_task(self, task: PrintTask, data) -> None:
|
||||
"""Takes a PrintTask and executes it"""
|
||||
|
||||
def use_printer(self) -> None:
|
||||
@@ -114,7 +115,7 @@ class EscPosPrinter(Printer):
|
||||
Making sure it has paper,
|
||||
Define default print settings
|
||||
"""
|
||||
super().__init__(app, vendor_id, device_id, printer_type=PrinterType.EPSON)
|
||||
super().__init__(app, vendor_id, device_id,printer_type=PrinterType.EPSON)
|
||||
self.printer = None
|
||||
self.usb_args = {}
|
||||
self.usb_args["idVendor"] = self.vendor_id
|
||||
@@ -204,7 +205,7 @@ class EscPosPrinter(Printer):
|
||||
self.printer.close()
|
||||
return True
|
||||
|
||||
def _print_txt(self, msg, signature="", bold=False):
|
||||
def _print_txt(self, msg, signature="", bold=False, do_cut=False):
|
||||
if not isinstance(msg, str):
|
||||
self.app.logger.error(
|
||||
"It is not possible to print a " + str(type(msg)) + ", only strings."
|
||||
@@ -253,10 +254,14 @@ class EscPosPrinter(Printer):
|
||||
"Unable to print a SMS, the printer couldn't do it."
|
||||
) from e
|
||||
|
||||
if do_cut:
|
||||
self._cut()
|
||||
|
||||
|
||||
self.app.logger.info("Printed text")
|
||||
self.ready = True
|
||||
|
||||
def _print_img(self, path, signature="", center=True, process=False):
|
||||
def _print_img(self, path, signature="", center=True, process=False, do_cut=False):
|
||||
clean_signature = str(signature)
|
||||
|
||||
if len(signature) > int(self.configuration_file["signature_max_length"]):
|
||||
@@ -317,6 +322,9 @@ class EscPosPrinter(Printer):
|
||||
self.app.logger.error("Could not close the printer connexion %s", str(e))
|
||||
raise RuntimeError("Could not close the printer connexion. ") from e
|
||||
|
||||
if do_cut:
|
||||
self._cut()
|
||||
|
||||
self.app.logger.info("Printed a picture")
|
||||
self.ready = True
|
||||
|
||||
@@ -356,47 +364,41 @@ class EscPosPrinter(Printer):
|
||||
|
||||
return is_ready and has_paper # and is_online
|
||||
|
||||
def print_task(self, task_type, data):
|
||||
def print_task(self, task, data):
|
||||
"""Execute actual print based on task type"""
|
||||
|
||||
with self._lock:
|
||||
self.app.logger.debug("Acquired lock to start print")
|
||||
|
||||
i_m_ready = self._state()
|
||||
while not i_m_ready:
|
||||
self.app.logger.debug(
|
||||
"Waiting for the printer to become ready, current state %s ",
|
||||
str(i_m_ready),
|
||||
)
|
||||
i_m_ready = self._state()
|
||||
while not i_m_ready:
|
||||
self.app.logger.debug(
|
||||
"Waiting for the printer to become ready, current state %s ",
|
||||
str(i_m_ready),
|
||||
)
|
||||
i_m_ready = self._state()
|
||||
time.sleep(0.3)
|
||||
time.sleep(0.3)
|
||||
|
||||
self.app.logger.debug("Checked state to start printing : %s", self._state())
|
||||
self.ready = False
|
||||
try:
|
||||
self.app.logger.debug("Checking task type")
|
||||
match (task_type.value):
|
||||
case "text":
|
||||
self.app.logger.debug("Checked state to start printing : %s", self._state())
|
||||
self.ready = False
|
||||
try:
|
||||
self.app.logger.debug("Checking task type")
|
||||
match (task.task_type.value):
|
||||
case "text":
|
||||
|
||||
self._print_txt(data["txt"], signature=data["sign"])
|
||||
self.ready = True
|
||||
case "image":
|
||||
self._print_img(
|
||||
data["img"], signature=data["sign"], process=data["process"]
|
||||
)
|
||||
self.ready = True
|
||||
case "cut":
|
||||
self._cut()
|
||||
self.ready = True
|
||||
case "qr":
|
||||
self._qr(data["txt"])
|
||||
self.ready = True
|
||||
case _:
|
||||
raise RuntimeError("This task type is not supported")
|
||||
except Exception as e:
|
||||
self.app.logger.debug("Exception occured while printing %s", str(e))
|
||||
self.ready = True
|
||||
raise RuntimeError from e
|
||||
self._print_txt(data["txt"], signature=data["sign"], do_cut=data["do_cut"])
|
||||
self.ready = True
|
||||
case "image":
|
||||
self._print_img(
|
||||
data["img"], signature=data["sign"], process=data["process"], do_cut=data["do_cut"]
|
||||
)
|
||||
self.ready = True
|
||||
case "qr":
|
||||
self._qr(data["txt"])
|
||||
self.ready = True
|
||||
case _:
|
||||
raise RuntimeError("This task type is not supported")
|
||||
except Exception as e:
|
||||
self.app.logger.debug("Exception occured while printing %s", str(e))
|
||||
self.ready = True
|
||||
raise RuntimeError from e
|
||||
|
||||
|
||||
class BrotherPrinter(Printer):
|
||||
@@ -405,50 +407,79 @@ class BrotherPrinter(Printer):
|
||||
"""
|
||||
|
||||
def __init__(self, app, vendor_id, device_id, configuration_file):
|
||||
super().__init__(
|
||||
app,
|
||||
vendor_id,
|
||||
device_id,
|
||||
printer_type=PrinterType.BROTHER,
|
||||
)
|
||||
|
||||
super().__init__(app, vendor_id, device_id, printer_type=PrinterType.BROTHER)
|
||||
self.printer = None
|
||||
self.usb_args = {}
|
||||
self.usb_args["idVendor"] = self.vendor_id
|
||||
self.usb_args["idProduct"] = self.device_id
|
||||
self.usb_args = {
|
||||
"idVendor": self.vendor_id,
|
||||
"idProduct": self.device_id,
|
||||
}
|
||||
self.model_manager = ModelsManager()
|
||||
|
||||
# Code taken from https://github.com/5shekel/printit/blob/master/printer_utils.py
|
||||
|
||||
# Discover the backend identifier for this specific USB printer.
|
||||
self.app.logger.debug("Creating backend for Brother")
|
||||
backend = backend_factory("pyusb")
|
||||
|
||||
available_devices = backend["list_available_devices"]()
|
||||
|
||||
for printer in available_devices:
|
||||
self.app.logger.debug(f"Found device: {printer}")
|
||||
identifier = printer["identifier"]
|
||||
# Match vendor and product IDs so this instance doesn't accidentally
|
||||
# use the identifier belonging to the last device in the backend list.
|
||||
expected_prefix = (
|
||||
f"usb://0x{vendor_id:04x}:0x{device_id:04x}/"
|
||||
).lower()
|
||||
|
||||
matching_identifiers = []
|
||||
|
||||
for device in available_devices:
|
||||
self.app.logger.debug("Found device: %s", device)
|
||||
|
||||
identifier = device.get("identifier", "")
|
||||
parts = identifier.split("/")
|
||||
|
||||
if len(parts) < 4:
|
||||
self.app.logger.warning(
|
||||
f"Skipping device with invalid identifier format: {identifier}"
|
||||
"Skipping device with invalid identifier format: %s",
|
||||
identifier,
|
||||
)
|
||||
continue
|
||||
|
||||
protocol = parts[0]
|
||||
# device_info = parts[2]
|
||||
serial_number = parts[3]
|
||||
if identifier.lower().startswith(expected_prefix):
|
||||
matching_identifiers.append(identifier)
|
||||
|
||||
if len(matching_identifiers) != 1:
|
||||
self.app.logger.error("Expected one Brother backend device matching %s, found %s", expected_prefix, len(matching_identifiers) )
|
||||
raise RuntimeError("Expected one Brother backend device matching %s, found %s", expected_prefix, len(matching_identifiers) )
|
||||
|
||||
# Extract connection details from the identifier for this printer only.
|
||||
identifier = matching_identifiers[0]
|
||||
parts = identifier.split("/")
|
||||
protocol = parts[0]
|
||||
serial_number = parts[3]
|
||||
|
||||
# Find the model that corresponds to this printer's product ID.
|
||||
try:
|
||||
for m in self.model_manager.iter_elements():
|
||||
if m.product_id == self.device_id:
|
||||
model = m.identifier
|
||||
|
||||
model = None
|
||||
for item in self.model_manager.iter_elements():
|
||||
if item.product_id == self.device_id:
|
||||
model = item.identifier
|
||||
break
|
||||
|
||||
self.app.logger.debug(f"Matched printer model: {model}")
|
||||
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
|
||||
if model is None:
|
||||
raise RuntimeError(
|
||||
f"No Brother model found for product ID {self.device_id:#06x}"
|
||||
)
|
||||
|
||||
self.app.logger.debug("Matched printer model: %s", model)
|
||||
except Exception:
|
||||
self.app.logger.exception(
|
||||
"Error while finding a model for product ID %s",
|
||||
self.device_id,
|
||||
)
|
||||
raise
|
||||
|
||||
self.printer_info = PrinterInfo(
|
||||
identifier=identifier,
|
||||
@@ -458,37 +489,44 @@ class BrotherPrinter(Printer):
|
||||
vendor_id=vendor_id,
|
||||
product_id=self.device_id,
|
||||
serial_number=serial_number,
|
||||
label_type=configuration_file[
|
||||
"label_type"
|
||||
], # TODO: Implement automatic label type detection : https://framagit.org/stickoeur/diagnostickoeur/-/blob/no-masters/printit.py?ref_type=heads#L239
|
||||
label_type=configuration_file["label_type"],
|
||||
# TODO: Implement automatic label type detection.
|
||||
)
|
||||
self.app.logger.debug("Created a Brother printer !")
|
||||
|
||||
self.app.logger.debug("Created a Brother printer!")
|
||||
self.ready = True
|
||||
|
||||
|
||||
def _has_paper(self):
|
||||
raise NotImplementedError("This printer model does not support this.")
|
||||
|
||||
def _state(self):
|
||||
return self.ready
|
||||
|
||||
def _print_txt(self, msg, signature="", bold=False):
|
||||
def _print_txt(self, msg, signature="", bold=False, do_cut=False):
|
||||
"""Print text after converting it to an image"""
|
||||
self._print_img(text_to_image(msg))
|
||||
self._print_img(text_to_image(signature))
|
||||
if signature != "":
|
||||
self._print_img(text_to_image(signature))
|
||||
|
||||
if do_cut:
|
||||
self._cut()
|
||||
|
||||
|
||||
def _print_img(
|
||||
self,
|
||||
data,
|
||||
signature="",
|
||||
process=False,
|
||||
):
|
||||
do_cut=False
|
||||
):
|
||||
"""
|
||||
Print a raster image via a Brother QL printer
|
||||
"""
|
||||
self.app.logger.debug("Printing an image %s via Brother printer", data)
|
||||
self.app.logger.debug("Printing an image %s via Brother printer ( %s )" , data, self.printer_info.model )
|
||||
if process:
|
||||
try:
|
||||
self.app.logger.debug("Proccessing the image")
|
||||
self.app.logger.debug("\t[⚙ %s] Proccessing the image", threading.get_ident())
|
||||
processed_path = _process_image(self, data)
|
||||
except RuntimeError as e:
|
||||
self.app.logger.error(
|
||||
@@ -509,17 +547,21 @@ class BrotherPrinter(Printer):
|
||||
)
|
||||
raise e
|
||||
|
||||
|
||||
|
||||
try:
|
||||
im = Image.open(processed_path)
|
||||
|
||||
qlr = BrotherQLRaster(self.printer_info.model)
|
||||
# create_label(qlr, im, self.printer_info.label_type, cut=False, dither=True)
|
||||
|
||||
# noinspection PyCallingNonCallable
|
||||
# be = BACKEND_CLASS(BACKEND_STRING_DESCR)
|
||||
# be.write(qlr.data)
|
||||
# be.dispose()
|
||||
# del be
|
||||
# Resize the image for the label type
|
||||
# device_pixel_width = qlr.get_pixel_width()
|
||||
# im = _resize_image(
|
||||
# self,
|
||||
# label_type=self.printer_info.label_type, image_path=processed_path,
|
||||
# device_pixel_width=device_pixel_width,
|
||||
# printer_model=qlr.model
|
||||
# )
|
||||
|
||||
im = Image.open(processed_path)
|
||||
instructions = convert(
|
||||
qlr=qlr,
|
||||
images=[im],
|
||||
@@ -528,17 +570,17 @@ class BrotherPrinter(Printer):
|
||||
compress=False,
|
||||
dpi_600=False,
|
||||
cut=False,
|
||||
)
|
||||
)
|
||||
|
||||
success = send(
|
||||
instructions=instructions,
|
||||
printer_identifier=BACKEND_STRING_DESCR,
|
||||
backend_identifier="pyusb",
|
||||
blocking=False,
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
self.app.logger.debug(str(success))
|
||||
self.app.logger.debug("Printed image")
|
||||
self.app.logger.debug("\t[⚙ %s] Printed image", self.id)
|
||||
time.sleep(2)
|
||||
|
||||
except usb.core.USBError as e:
|
||||
@@ -585,7 +627,7 @@ class BrotherPrinter(Printer):
|
||||
blocking=False,
|
||||
)
|
||||
self.app.logger.debug(str(success))
|
||||
self.app.logger.debug("Printed signature")
|
||||
self.app.logger.debug("Printed signature %s", signature)
|
||||
time.sleep(2)
|
||||
|
||||
except Exception as e:
|
||||
@@ -597,6 +639,9 @@ class BrotherPrinter(Printer):
|
||||
except OSError as e:
|
||||
raise e
|
||||
|
||||
if do_cut:
|
||||
self._cut()
|
||||
|
||||
def _cut(self):
|
||||
self.app.logger.debug("Cutting via Brother Printer")
|
||||
try:
|
||||
@@ -630,37 +675,34 @@ class BrotherPrinter(Printer):
|
||||
# This should not be reached by a print on a BrotherQL
|
||||
raise NotImplementedError()
|
||||
|
||||
def print_task(self, task_type, data):
|
||||
def print_task(self, task, data):
|
||||
"""Execute actual print based on task type"""
|
||||
with self._lock:
|
||||
self.app.logger.debug("Acquired lock to start print")
|
||||
i_m_ready = self._state()
|
||||
while not i_m_ready:
|
||||
self.app.logger.debug("\t[⚙ %s] Waiting for the printer to become ready, current state %s ", self.id, str(i_m_ready))
|
||||
i_m_ready = self._state()
|
||||
while not i_m_ready:
|
||||
self.app.logger.debug(
|
||||
"Waiting for the printer to become ready, current state %s ",
|
||||
str(i_m_ready),
|
||||
)
|
||||
i_m_ready = self._state()
|
||||
time.sleep(0.3)
|
||||
time.sleep(0.3)
|
||||
|
||||
self.app.logger.debug("Checked state to start printing : %s", self._state())
|
||||
self.ready = False
|
||||
self.app.logger.debug("\t[⚙ %s] Checked state to start printing %s ", self.id, self._state())
|
||||
|
||||
try:
|
||||
match (task_type.value):
|
||||
case "image":
|
||||
self._print_img(data["img"], signature=data["sign"])
|
||||
self.ready = True
|
||||
case "cut":
|
||||
self._cut()
|
||||
self.ready = True
|
||||
case "text":
|
||||
self._print_txt(data["txt"], signature=data["sign"])
|
||||
self.ready = True
|
||||
case _:
|
||||
raise RuntimeError("This task type is not supported")
|
||||
except Exception as e:
|
||||
raise e
|
||||
self.ready = False
|
||||
|
||||
try:
|
||||
match (task.task_type.value):
|
||||
case "image":
|
||||
self._print_img(data["img"], signature=data["sign"], do_cut=data["do_cut"])
|
||||
case "text":
|
||||
self._print_txt(data["txt"], signature=data["sign"], do_cut=data["do_cut"])
|
||||
case _:
|
||||
raise RuntimeError("This task type is not supported")
|
||||
except ValueError as ve:
|
||||
self.app.logger.error("\t[⚙ %s] The printer couldn't be found, the printing failed for task %s of type , error : %s ",self.id, task.task_id, task.value, str(ve))
|
||||
raise ve
|
||||
except Exception as e:
|
||||
raise e
|
||||
|
||||
self.app.logger.debug("\t[⚙ %s] Finished consuming task %s", self.id, task.task_id)
|
||||
self.ready = True
|
||||
|
||||
|
||||
def _process_image(self, path, max_width=575, max_height=1000):
|
||||
@@ -674,9 +716,9 @@ def _process_image(self, path, max_width=575, max_height=1000):
|
||||
Image.Resampling.LANCZOS,
|
||||
)
|
||||
|
||||
grayscale = img.convert("L")
|
||||
grayscale_image = img.convert("L")
|
||||
|
||||
avg_brightness = np.asarray(grayscale, dtype=np.float32).mean()
|
||||
avg_brightness = np.asarray(grayscale_image, dtype=np.float32).mean()
|
||||
self.app.logger.debug("Average brightness of the image: %.2f", avg_brightness)
|
||||
|
||||
if avg_brightness < brightness_threshold:
|
||||
@@ -691,13 +733,13 @@ def _process_image(self, path, max_width=575, max_height=1000):
|
||||
"Image is dark; increasing brightness by %.2f",
|
||||
brightness_factor,
|
||||
)
|
||||
grayscale = ImageEnhance.Brightness(grayscale).enhance(brightness_factor)
|
||||
grayscale_image = ImageEnhance.Brightness(grayscale_image).enhance(brightness_factor)
|
||||
|
||||
contrast = float(np.asarray(grayscale, dtype=np.float32).std())
|
||||
contrast = float(np.asarray(grayscale_image, dtype=np.float32).std())
|
||||
self.app.logger.debug("Grayscale standard deviation: %.2f", contrast)
|
||||
|
||||
# Save the enhanced result.
|
||||
processed = ImageEnhance.Contrast(grayscale).enhance(contrast_factor)
|
||||
processed = ImageEnhance.Contrast(grayscale_image).enhance(contrast_factor)
|
||||
|
||||
jpeg_path = os.path.splitext(path)[0] + "_processed.jpg"
|
||||
processed.save(jpeg_path, format="JPEG", quality=95, optimize=True)
|
||||
@@ -716,7 +758,7 @@ def text_to_image(
|
||||
background="white",
|
||||
fill="black",
|
||||
output_dir="src/static/uploads",
|
||||
):
|
||||
):
|
||||
"""Converts a string to an image"""
|
||||
|
||||
font = ImageFont.truetype(font_path, font_size)
|
||||
@@ -785,3 +827,62 @@ def text_to_image(
|
||||
image.save(image_path, format="PNG")
|
||||
|
||||
return str(image_path)
|
||||
|
||||
|
||||
def _resize_image(self,label_type: str, image_path: str, device_pixel_width: int, printer_model: object):
|
||||
# """
|
||||
# Resize an image to the specs needed for a label. Only used in Brother printers
|
||||
# """
|
||||
|
||||
# self.app.logger.debug("Resizing the image from %s", image_path)
|
||||
|
||||
# label_specs = LabelsManager().get_label_by_identifier(label_type)
|
||||
|
||||
# right_margin_dots = label_specs.offset_r
|
||||
# model_obj = ModelsManager().get_model_by_identifier(printer_model)
|
||||
# right_margin_dots += model_obj.additional_offset_r
|
||||
# max_image_dimension = label_specs.dots_printable
|
||||
|
||||
# self.app.logger.debug("Found label %s with maximum dimensions %s", label_type, max_image_dimension)
|
||||
|
||||
|
||||
# # Open image
|
||||
# with Image.open(image_path ) as img:
|
||||
# self.app.logger.debug("Image current dimensions before resizing are %s", img.size)
|
||||
|
||||
# # Fit inside the label dimensions while preserving aspect ratio.
|
||||
# max_width = max_image_dimension[0]
|
||||
# max_height = max_image_dimension[1]
|
||||
# img = ImageOps.contain(
|
||||
# img,
|
||||
# (max_width, max_height),
|
||||
# method=Image.Resampling.LANCZOS,
|
||||
# )
|
||||
|
||||
# # Create a new image of the correct dimensions
|
||||
# new_im = Image.new(
|
||||
# img.mode,
|
||||
# (device_pixel_width, max_image_dimension[1]),
|
||||
# (255,) * len(img.mode),
|
||||
# )
|
||||
|
||||
# # Set image position
|
||||
# x = max(0, device_pixel_width - img.size[0] - right_margin_dots)
|
||||
|
||||
# # Paste the resized image into the new image
|
||||
# new_im.paste(img, (x, 0))
|
||||
|
||||
# # Replace the original image
|
||||
# img = new_im
|
||||
|
||||
# # Set path for the image
|
||||
# jpeg_path = os.path.splitext(image_path)[0] + "_resized.jpg"
|
||||
|
||||
# try:
|
||||
# img.save(jpeg_path, format="JPEG", quality=95, optimize=True)
|
||||
# except OSError as e:
|
||||
# self.app.logger.debug("Error while saving the rised image ! %s", str(e))
|
||||
# raise e
|
||||
# # end try
|
||||
# return jpeg_path
|
||||
pass
|
||||
Reference in new issue
Block a user