Multi-printers #32
No files matched your search
+35
-17
@@ -50,21 +50,24 @@ from printers import Printers
|
||||
# Logging configuration
|
||||
|
||||
|
||||
dictConfig({
|
||||
'version': 1,
|
||||
'formatters': {'default': {
|
||||
'format': '[%(levelname)s] \033[1m%(message)s\033[0m \033[2m(%(filename)s:%(lineno)d)\033[0m',
|
||||
}},
|
||||
'handlers': {'wsgi': {
|
||||
'class': 'logging.StreamHandler',
|
||||
'stream': 'ext://flask.logging.wsgi_errors_stream',
|
||||
'formatter': 'default'
|
||||
}},
|
||||
'root': {
|
||||
'level': 'INFO',
|
||||
'handlers': ['wsgi']
|
||||
dictConfig(
|
||||
{
|
||||
"version": 1,
|
||||
"formatters": {
|
||||
"default": {
|
||||
"format": "[%(levelname)s] \033[1m%(message)s\033[0m \033[2m(%(filename)s:%(lineno)d)\033[0m",
|
||||
}
|
||||
})
|
||||
},
|
||||
"handlers": {
|
||||
"wsgi": {
|
||||
"class": "logging.StreamHandler",
|
||||
"stream": "ext://flask.logging.wsgi_errors_stream",
|
||||
"formatter": "default",
|
||||
}
|
||||
},
|
||||
"root": {"level": "INFO", "handlers": ["wsgi"]},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# We create the main Flask object
|
||||
@@ -147,7 +150,9 @@ except Exception as e:
|
||||
workers = set()
|
||||
for i in range(len(printers_pool)):
|
||||
try:
|
||||
worker = PrintWorker(app, print_queue, printers_pool=printers_pool, printer_index=i)
|
||||
worker = PrintWorker(
|
||||
app, print_queue, printers_pool=printers_pool, printer_index=i
|
||||
)
|
||||
workers.add(worker)
|
||||
worker.start()
|
||||
except Exception as e:
|
||||
@@ -157,7 +162,9 @@ for i in range(len(printers_pool)):
|
||||
for i in threading.enumerate():
|
||||
app.logger.debug(i)
|
||||
|
||||
app.logger.info("\n\n\t\033[36m🖶\033[0m \033[93m🖶\033[0m \033[95m🖶\033[0m \033[97mWelcome to LittlePrynter !\n\n")
|
||||
app.logger.info(
|
||||
"\n\n\t\033[36m🖶\033[0m \033[93m🖶\033[0m \033[95m🖶\033[0m \033[97mWelcome to LittlePrynter !\n\n"
|
||||
)
|
||||
|
||||
|
||||
# The rate limit
|
||||
@@ -165,6 +172,7 @@ limiter = Limiter(
|
||||
get_remote_address, app=app, default_limits=["104800 per day", "10200 per hour"]
|
||||
)
|
||||
|
||||
|
||||
# General routes
|
||||
@app.route("/")
|
||||
@limiter.limit("5/second", override_defaults=False)
|
||||
@@ -181,6 +189,7 @@ def webcam():
|
||||
app.logger.debug("Loading webcam interface")
|
||||
return render_template("webcam.html")
|
||||
|
||||
|
||||
# General routes
|
||||
@app.route("/queue")
|
||||
@limiter.limit("5/second", override_defaults=False)
|
||||
@@ -189,7 +198,12 @@ def queue():
|
||||
app.logger.debug("Loading queue")
|
||||
current_queue = print_queue.get_queue_state()
|
||||
completed_queue = print_queue.get_queue_completed()
|
||||
return render_template("queue.html", tasks=current_queue, completed_tasks=completed_queue, worker_state=worker.current_state())
|
||||
return render_template(
|
||||
"queue.html",
|
||||
tasks=current_queue,
|
||||
completed_tasks=completed_queue,
|
||||
worker_state=worker.current_state(),
|
||||
)
|
||||
|
||||
|
||||
# Form treatement
|
||||
@@ -453,6 +467,7 @@ def api_worker_start():
|
||||
w.start_worker()
|
||||
return jsonify([w.current_state() for w in workers])
|
||||
|
||||
|
||||
# TODO : Auth
|
||||
@app.route("/api/workers/stop")
|
||||
@limiter.limit("6/minute")
|
||||
@@ -464,6 +479,7 @@ def api_worker_stop():
|
||||
w.stop_worker()
|
||||
return jsonify([w.current_state() for w in workers])
|
||||
|
||||
|
||||
# TODO : Auth
|
||||
@app.route("/api/printers")
|
||||
@limiter.limit("160/minute", override_defaults=True)
|
||||
@@ -474,6 +490,7 @@ def api_printers_info():
|
||||
|
||||
## Authentification
|
||||
|
||||
|
||||
@app.route("/login")
|
||||
@limiter.limit("1/second", override_defaults=False)
|
||||
def login_page():
|
||||
@@ -526,5 +543,6 @@ def camera_status():
|
||||
else:
|
||||
socketio.emit("camera_status", False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(use_reloader=False, host="0.0.0.0", ssl_context="adhoc")
|
||||
+62
-30
@@ -28,6 +28,7 @@ from brother_ql import create_label
|
||||
# Used for typing
|
||||
from task import PrintTask
|
||||
|
||||
|
||||
class PrinterType(Enum):
|
||||
"""
|
||||
What are the capacities of a Printer ?
|
||||
@@ -257,7 +258,6 @@ class EscPosPrinter(Printer):
|
||||
if do_cut:
|
||||
self._cut()
|
||||
|
||||
|
||||
self.app.logger.info("Printed text")
|
||||
self.ready = True
|
||||
|
||||
@@ -383,11 +383,16 @@ class EscPosPrinter(Printer):
|
||||
match (task.task_type.value):
|
||||
case "text":
|
||||
|
||||
self._print_txt(data["txt"], signature=data["sign"], do_cut=data["do_cut"])
|
||||
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"]
|
||||
data["img"],
|
||||
signature=data["sign"],
|
||||
process=data["process"],
|
||||
do_cut=data["do_cut"],
|
||||
)
|
||||
self.ready = True
|
||||
case "qr":
|
||||
@@ -428,9 +433,7 @@ class BrotherPrinter(Printer):
|
||||
|
||||
# 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()
|
||||
expected_prefix = (f"usb://0x{vendor_id:04x}:0x{device_id:04x}/").lower()
|
||||
|
||||
matching_identifiers = []
|
||||
|
||||
@@ -451,8 +454,16 @@ class BrotherPrinter(Printer):
|
||||
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) )
|
||||
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]
|
||||
@@ -496,7 +507,6 @@ class BrotherPrinter(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.")
|
||||
|
||||
@@ -512,21 +522,20 @@ class BrotherPrinter(Printer):
|
||||
if do_cut:
|
||||
self._cut()
|
||||
|
||||
|
||||
def _print_img(
|
||||
self,
|
||||
data,
|
||||
signature="",
|
||||
process=False,
|
||||
do_cut=False
|
||||
):
|
||||
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 ( %s )" , data, self.printer_info.model )
|
||||
self.app.logger.debug(
|
||||
"Printing an image %s via Brother printer ( %s )",
|
||||
data,
|
||||
self.printer_info.model,
|
||||
)
|
||||
if process:
|
||||
try:
|
||||
self.app.logger.debug("\t[⚙ %s] Proccessing the image", threading.get_ident())
|
||||
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(
|
||||
@@ -547,8 +556,6 @@ class BrotherPrinter(Printer):
|
||||
)
|
||||
raise e
|
||||
|
||||
|
||||
|
||||
try:
|
||||
|
||||
qlr = BrotherQLRaster(self.printer_info.model)
|
||||
@@ -679,29 +686,47 @@ class BrotherPrinter(Printer):
|
||||
"""Execute actual print based on task type"""
|
||||
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))
|
||||
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()
|
||||
time.sleep(0.3)
|
||||
|
||||
self.app.logger.debug("\t[⚙ %s] Checked state to start printing %s ", self.id, self._state())
|
||||
self.app.logger.debug(
|
||||
"\t[⚙ %s] Checked state to start printing %s ", self.id, self._state()
|
||||
)
|
||||
|
||||
self.ready = False
|
||||
|
||||
try:
|
||||
match (task.task_type.value):
|
||||
case "image":
|
||||
self._print_img(data["img"], signature=data["sign"], do_cut=data["do_cut"])
|
||||
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"])
|
||||
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))
|
||||
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.app.logger.debug(
|
||||
"\t[⚙ %s] Finished consuming task %s", self.id, task.task_id
|
||||
)
|
||||
self.ready = True
|
||||
|
||||
|
||||
@@ -733,7 +758,9 @@ def _process_image(self, path, max_width=575, max_height=1000):
|
||||
"Image is dark; increasing brightness by %.2f",
|
||||
brightness_factor,
|
||||
)
|
||||
grayscale_image = ImageEnhance.Brightness(grayscale_image).enhance(brightness_factor)
|
||||
grayscale_image = ImageEnhance.Brightness(grayscale_image).enhance(
|
||||
brightness_factor
|
||||
)
|
||||
|
||||
contrast = float(np.asarray(grayscale_image, dtype=np.float32).std())
|
||||
self.app.logger.debug("Grayscale standard deviation: %.2f", contrast)
|
||||
@@ -829,7 +856,13 @@ def text_to_image(
|
||||
return str(image_path)
|
||||
|
||||
|
||||
def _resize_image(self,label_type: str, image_path: str, device_pixel_width: int, printer_model: object):
|
||||
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
|
||||
# """
|
||||
@@ -845,7 +878,6 @@ def _resize_image(self,label_type: str, image_path: str, device_pixel_width: int
|
||||
|
||||
# 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)
|
||||
|
||||
+15
-4
@@ -102,7 +102,9 @@ class Printers:
|
||||
app=self.app,
|
||||
vendor_id=vendir,
|
||||
device_id=prid,
|
||||
configuration_file=self.configuration_file["printer"]["epson"]
|
||||
configuration_file=self.configuration_file["printer"][
|
||||
"epson"
|
||||
],
|
||||
)
|
||||
except Exception as e:
|
||||
raise e
|
||||
@@ -119,7 +121,9 @@ class Printers:
|
||||
self.app,
|
||||
dev.idVendor,
|
||||
dev.idProduct,
|
||||
configuration_file=self.configuration_file["printer"]["brother"]
|
||||
configuration_file=self.configuration_file["printer"][
|
||||
"brother"
|
||||
],
|
||||
)
|
||||
except Exception as e:
|
||||
self.app.logger.error(
|
||||
@@ -132,12 +136,18 @@ class Printers:
|
||||
|
||||
# If the object creation is successfull, we add it to the list of Printers
|
||||
printers.add(brother_printer)
|
||||
self.app.logger.debug("Found a %s printer with id %s", manufacturer, brother_printer.printer_info.identifier)
|
||||
self.app.logger.debug(
|
||||
"Found a %s printer with id %s",
|
||||
manufacturer,
|
||||
brother_printer.printer_info.identifier,
|
||||
)
|
||||
case _:
|
||||
self.app.logger.debug(
|
||||
"Found a printer of unknown manufacturer : %s", manufacturer
|
||||
)
|
||||
self.app.logger.debug("We are not adding this printer to the printers pool. Ignoring.")
|
||||
self.app.logger.debug(
|
||||
"We are not adding this printer to the printers pool. Ignoring."
|
||||
)
|
||||
# end match
|
||||
|
||||
self.app.logger.debug("Found %s printers", len(printers))
|
||||
@@ -188,6 +198,7 @@ class Printers:
|
||||
def __len__(self):
|
||||
return len(self.printers)
|
||||
|
||||
|
||||
class _FindClass:
|
||||
"""
|
||||
Use by usb.core to modify the way USB devices are found
|
||||
|
||||
+8
-1
@@ -96,12 +96,19 @@ class ImageTask(PrintTask):
|
||||
|
||||
def get_print_data(self):
|
||||
# Return image data in printer-compatible format
|
||||
return {"img": self.image_path, "sign": self.signature, "process": self.process, "do_cut": self.do_cut}
|
||||
return {
|
||||
"img": self.image_path,
|
||||
"sign": self.signature,
|
||||
"process": self.process,
|
||||
"do_cut": self.do_cut,
|
||||
}
|
||||
|
||||
|
||||
class RemoveTask(PrintTask):
|
||||
"""
|
||||
This class is used to clear images and leftovers after a print
|
||||
"""
|
||||
|
||||
def __init__(self, task_id, image_path):
|
||||
super().__init__(TaskType.REMOVE)
|
||||
self.task_id = self._generate_id() if not task_id else task_id
|
||||
|
||||
+18
-6
@@ -30,8 +30,14 @@ class Web:
|
||||
# are added back to back, another task could be
|
||||
# inserted between the two.
|
||||
for i in range(many):
|
||||
sms = self.print_queue.enqueue(TextTask(content=texte, signature=sign, do_cut=do_cut))
|
||||
self.app.logger.info("Added a SMS task at position %s, it should %scut", sms, "" if not do_cut else "not ")
|
||||
sms = self.print_queue.enqueue(
|
||||
TextTask(content=texte, signature=sign, do_cut=do_cut)
|
||||
)
|
||||
self.app.logger.info(
|
||||
"Added a SMS task at position %s, it should %scut",
|
||||
sms,
|
||||
"" if not do_cut else "not ",
|
||||
)
|
||||
self.app.logger.debug("%s", do_cut)
|
||||
except Exception as e:
|
||||
self.app.logger.error(e)
|
||||
@@ -62,15 +68,19 @@ class Web:
|
||||
ImageTask(
|
||||
os.path.join(
|
||||
self.app.config["UPLOAD_FOLDER"],
|
||||
secure_filename(str(file_uploaded.split("/").pop()))
|
||||
secure_filename(str(file_uploaded.split("/").pop())),
|
||||
),
|
||||
signature=sign,
|
||||
process=process_image,
|
||||
task_id=str(uuid.uuid4()),
|
||||
do_cut=do_cut
|
||||
do_cut=do_cut,
|
||||
)
|
||||
)
|
||||
self.app.logger.info("Added a IMG task at position %s, it should %s cut", img, "not " if not do_cut else "")
|
||||
self.app.logger.info(
|
||||
"Added a IMG task at position %s, it should %s cut",
|
||||
img,
|
||||
"not " if not do_cut else "",
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
raise RuntimeError("Could not add IMG to queue " + str(e)) from e
|
||||
@@ -107,7 +117,9 @@ class Web:
|
||||
extension = filename.split(".").pop()
|
||||
self.app.logger.debug("File valid")
|
||||
try:
|
||||
image_uuid_path = os.path.join(self.app.config["UPLOAD_FOLDER"], image_uuid + "." + extension)
|
||||
image_uuid_path = os.path.join(
|
||||
self.app.config["UPLOAD_FOLDER"], image_uuid + "." + extension
|
||||
)
|
||||
image.save(image_uuid_path)
|
||||
except OSError as e:
|
||||
self.app.logger.error("Could not save file %s", e)
|
||||
|
||||
+32
-10
@@ -10,7 +10,6 @@ import random
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
|
||||
class PrintWorker(threading.Thread):
|
||||
"""
|
||||
A thread used to consume Tasks added to a Print Queue.
|
||||
@@ -39,7 +38,12 @@ class PrintWorker(threading.Thread):
|
||||
self._printer_index = printer_index
|
||||
self.printer = self._acquire_available_printer()
|
||||
|
||||
self.app.logger.debug("\t[⚙ %s][%s] is ready to work with printer %s", self.id, threading.get_ident(), self.printer.printer_info.model)
|
||||
self.app.logger.debug(
|
||||
"\t[⚙ %s][%s] is ready to work with printer %s",
|
||||
self.id,
|
||||
threading.get_ident(),
|
||||
self.printer.printer_info.model,
|
||||
)
|
||||
|
||||
def _acquire_available_printer(self):
|
||||
result = self.printers.acquire_available_printer(
|
||||
@@ -56,7 +60,9 @@ class PrintWorker(threading.Thread):
|
||||
|
||||
def run(self):
|
||||
"""Background thread that processes queue items"""
|
||||
self.app.logger.debug("\t[⚙ %s][%s] started working", self.id, threading.get_ident())
|
||||
self.app.logger.debug(
|
||||
"\t[⚙ %s][%s] started working", self.id, threading.get_ident()
|
||||
)
|
||||
|
||||
while True:
|
||||
# If the printer is dead or asleep, it can't work.
|
||||
@@ -74,12 +80,15 @@ class PrintWorker(threading.Thread):
|
||||
|
||||
if self.running and self.printer is None:
|
||||
self.app.logger.debug(
|
||||
"\t[⚙ %s] Trying to find a available printer for the worker.", self.id
|
||||
"\t[⚙ %s] Trying to find a available printer for the worker.",
|
||||
self.id,
|
||||
)
|
||||
self.printer = self._acquire_available_printer()
|
||||
self.app.logger.debug(
|
||||
"\t[⚙ %s] Got a %s ( %s ) printer and it's %s", self.id ,
|
||||
self.printer.printer_info.name, self.printer.printer_info.model,
|
||||
"\t[⚙ %s] Got a %s ( %s ) printer and it's %s",
|
||||
self.id,
|
||||
self.printer.printer_info.name,
|
||||
self.printer.printer_info.model,
|
||||
"Ready" if self.printer.ready else "Not ready",
|
||||
)
|
||||
|
||||
@@ -92,7 +101,9 @@ class PrintWorker(threading.Thread):
|
||||
|
||||
# If the printer is not ready, we wait for it to become ready.
|
||||
if not self.printer.ready:
|
||||
self.app.logger.debug("\t[⚙ %s] Waiting for our printer to become ready...", self.id)
|
||||
self.app.logger.debug(
|
||||
"\t[⚙ %s] Waiting for our printer to become ready...", self.id
|
||||
)
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
@@ -108,7 +119,9 @@ class PrintWorker(threading.Thread):
|
||||
# self.app.logger.debug("\t[⚙ %s] Trying to get a task from the queue ", self.id)
|
||||
task = self.print_queue.dequeue()
|
||||
except Exception as e:
|
||||
self.app.logger.error("\t[⚙ %s] Could not get a new task %s ", self.id, str(e))
|
||||
self.app.logger.error(
|
||||
"\t[⚙ %s] Could not get a new task %s ", self.id, str(e)
|
||||
)
|
||||
self.state = "idle"
|
||||
self.printer.free_printer()
|
||||
raise RuntimeError(
|
||||
@@ -116,7 +129,12 @@ class PrintWorker(threading.Thread):
|
||||
) from e
|
||||
|
||||
if task:
|
||||
self.app.logger.debug("\t[⚙ %s] Got a new task %s %s", self.id, task.task_type, task.task_id)
|
||||
self.app.logger.debug(
|
||||
"\t[⚙ %s] Got a new task %s %s",
|
||||
self.id,
|
||||
task.task_type,
|
||||
task.task_id,
|
||||
)
|
||||
|
||||
task.status = "processing"
|
||||
|
||||
@@ -168,5 +186,9 @@ class PrintWorker(threading.Thread):
|
||||
"is_running": self.running,
|
||||
"queue_size": len(self.print_queue),
|
||||
"state": self.state,
|
||||
"printer": self.printer.printer_info.model if self.printer.printer_info.model else "No printer",
|
||||
"printer": (
|
||||
self.printer.printer_info.model
|
||||
if self.printer.printer_info.model
|
||||
else "No printer"
|
||||
),
|
||||
}
|
||||
Reference in new issue
Block a user