Apply black formatter

This commit is contained in:
n07070
2026-06-04 00:31:04 +02:00
parent a2d1779e2b
commit 3c490e10b4
8 changed files with 103 additions and 49 deletions

View File

@@ -1,8 +1,10 @@
"""
This class manages connexion to a Printer
"""
from time import sleep
import os.path
import os
from abc import ABC, abstractmethod
from dataclasses import dataclass
@@ -14,7 +16,6 @@ import threading
from PIL import Image, ImageEnhance
import numpy as np
# Importing the modules needed for each supported printer Type
import escpos.printer
from brother_ql.models import ModelsManager
@@ -24,12 +25,15 @@ from brother_ql.raster import BrotherQLRaster
from brother_ql.conversion import convert
from brother_ql.backends.helpers import send
class PrinterType(Enum):
"""
What are the capacities of a Printer ?
"""
EPSON = "epson"
BROTHER = "brother"
"""
What are the capacities of a Printer ?
"""
EPSON = "epson"
BROTHER = "brother"
# For Brother-QL Printers
@dataclass
@@ -44,7 +48,7 @@ class PrinterInfo:
model: str = "QL-570"
status: str = "unknown"
label_type: str = "unknown"
label_size : str = "unknown"
label_size: str = "unknown"
label_width: int = 0
label_height: int = 0
@@ -54,6 +58,7 @@ class PrinterInfo:
def __setitem__(self, key, value):
setattr(self, key, value)
class Printer(ABC):
"""
If it outputs printed paper and speaks like a printer, then it must be a printer.
@@ -80,7 +85,7 @@ class Printer(ABC):
"""Reports the state of the Printer"""
@abstractmethod
def print_task(self, task_type, data)-> None:
def print_task(self, task_type, data) -> None:
"""Takes a PrintTask and executes it"""
@@ -96,7 +101,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
@@ -105,9 +110,7 @@ class EscPosPrinter(Printer):
try:
# This also calls open(), which we need to close()
# or else the device will appear as busy.
p = escpos.printer.Usb(
self.vendor_id, self.device_id, 0, profile="TM-P80"
)
p = escpos.printer.Usb(self.vendor_id, self.device_id, 0, profile="TM-P80")
except escpos.exceptions.DeviceNotFoundError as e:
self.app.logger.error(
"The USB device is not plugged in : %s",
@@ -141,7 +144,7 @@ class EscPosPrinter(Printer):
# Beware : if we print every time the printer becomes ready, it means
# we are printing before and after every print !
self.printer = p
self.printer.close() # We close the connexion to the Printer
self.printer.close() # We close the connexion to the Printer
try:
self._has_paper()
@@ -339,13 +342,16 @@ class EscPosPrinter(Printer):
else:
raise RuntimeError("The printer is not ready to print yet !")
class BrotherPrinter(Printer):
"""
Manages connexion and capabilities of a BrotherQL Printer
"""
def __init__(self, app, vendor_id, device_id):
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.device_id
@@ -363,7 +369,9 @@ class BrotherPrinter(Printer):
parts = identifier.split("/")
if len(parts) < 4:
self.app.logger.warning(f"Skipping device with invalid identifier format: {identifier}")
self.app.logger.warning(
f"Skipping device with invalid identifier format: {identifier}"
)
continue
protocol = parts[0]
@@ -378,7 +386,7 @@ class BrotherPrinter(Printer):
break
self.app.logger.debug(f"Matched printer model: {model}")
except ValueError:
self.app.logger.warning(f"Invalid product ID format: {product_id}")
self.app.logger.warning(f"Invalid product ID format: {m.product_id}")
self.printer_info = PrinterInfo(
identifier=identifier,
@@ -392,14 +400,13 @@ class BrotherPrinter(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_img(self,data):
def _print_img(self, data):
"""
Print a raster image via a Brother QL printer
"""
@@ -426,7 +433,7 @@ class BrotherPrinter(Printer):
)
# Debug logging
if FLASK_DEBUG:
if os.getenv("FLASK_DEBUG"):
self.app.logger.debug(f"""
Print parameters:
- Label type: {label_type}
@@ -447,11 +454,15 @@ class BrotherPrinter(Printer):
# }
status = send(
instructions=instructions,
printer_identifier= self.printer_info["identifier"],
backend_identifier="pyusb"
printer_identifier=self.printer_info["identifier"],
backend_identifier="pyusb",
)
if not status["did_print"] or status["outcome"] == "error" or status["outcome"] == "unknown":
if (
not status["did_print"]
or status["outcome"] == "error"
or status["outcome"] == "unknown"
):
raise RuntimeError("Failed to print using Python API")
if status["printer_state"]:
@@ -462,7 +473,9 @@ class BrotherPrinter(Printer):
except usb.core.USBError as e:
# Treat timeout errors as successful since they often occur after print completion
if e.errno == 110: # Operation timed out
self.app.logger.debug("USB timeout occurred - this is normal and the print likely completed")
self.app.logger.debug(
"USB timeout occurred - this is normal and the print likely completed"
)
self.app.logger.debug("Print completed (timeout is normal)")
self.ready = True
@@ -496,6 +509,7 @@ class BrotherPrinter(Printer):
# raise NotImplementedError("This printer type is not implemented yet")
def _process_image(self, path):
brightness_factor = 1.5 # Used only if image is too dark
brightness_threshold = 100 # Brightness threshold (0255)