Formatting
This commit is contained in:
1 parent
12508bda83
commit
99f9eccf00
7 files changed
+187
-85
No files matched your search
+38
-20
@@ -50,21 +50,24 @@ from printers import Printers
|
|||||||
# Logging configuration
|
# Logging configuration
|
||||||
|
|
||||||
|
|
||||||
dictConfig({
|
dictConfig(
|
||||||
'version': 1,
|
{
|
||||||
'formatters': {'default': {
|
"version": 1,
|
||||||
'format': '[%(levelname)s] \033[1m%(message)s\033[0m \033[2m(%(filename)s:%(lineno)d)\033[0m',
|
"formatters": {
|
||||||
}},
|
"default": {
|
||||||
'handlers': {'wsgi': {
|
"format": "[%(levelname)s] \033[1m%(message)s\033[0m \033[2m(%(filename)s:%(lineno)d)\033[0m",
|
||||||
'class': 'logging.StreamHandler',
|
}
|
||||||
'stream': 'ext://flask.logging.wsgi_errors_stream',
|
},
|
||||||
'formatter': 'default'
|
"handlers": {
|
||||||
}},
|
"wsgi": {
|
||||||
'root': {
|
"class": "logging.StreamHandler",
|
||||||
'level': 'INFO',
|
"stream": "ext://flask.logging.wsgi_errors_stream",
|
||||||
'handlers': ['wsgi']
|
"formatter": "default",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {"level": "INFO", "handlers": ["wsgi"]},
|
||||||
}
|
}
|
||||||
})
|
)
|
||||||
|
|
||||||
|
|
||||||
# We create the main Flask object
|
# We create the main Flask object
|
||||||
@@ -147,7 +150,9 @@ except Exception as e:
|
|||||||
workers = set()
|
workers = set()
|
||||||
for i in range(len(printers_pool)):
|
for i in range(len(printers_pool)):
|
||||||
try:
|
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)
|
workers.add(worker)
|
||||||
worker.start()
|
worker.start()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -157,7 +162,9 @@ for i in range(len(printers_pool)):
|
|||||||
for i in threading.enumerate():
|
for i in threading.enumerate():
|
||||||
app.logger.debug(i)
|
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
|
# The rate limit
|
||||||
@@ -165,6 +172,7 @@ limiter = Limiter(
|
|||||||
get_remote_address, app=app, default_limits=["104800 per day", "10200 per hour"]
|
get_remote_address, app=app, default_limits=["104800 per day", "10200 per hour"]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
# General routes
|
# General routes
|
||||||
@app.route("/")
|
@app.route("/")
|
||||||
@limiter.limit("5/second", override_defaults=False)
|
@limiter.limit("5/second", override_defaults=False)
|
||||||
@@ -181,6 +189,7 @@ def webcam():
|
|||||||
app.logger.debug("Loading webcam interface")
|
app.logger.debug("Loading webcam interface")
|
||||||
return render_template("webcam.html")
|
return render_template("webcam.html")
|
||||||
|
|
||||||
|
|
||||||
# General routes
|
# General routes
|
||||||
@app.route("/queue")
|
@app.route("/queue")
|
||||||
@limiter.limit("5/second", override_defaults=False)
|
@limiter.limit("5/second", override_defaults=False)
|
||||||
@@ -189,7 +198,12 @@ def queue():
|
|||||||
app.logger.debug("Loading queue")
|
app.logger.debug("Loading queue")
|
||||||
current_queue = print_queue.get_queue_state()
|
current_queue = print_queue.get_queue_state()
|
||||||
completed_queue = print_queue.get_queue_completed()
|
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
|
# Form treatement
|
||||||
@@ -439,7 +453,7 @@ def api_queue_completed():
|
|||||||
@limiter.limit("160/minute", override_defaults=True)
|
@limiter.limit("160/minute", override_defaults=True)
|
||||||
def api_worker_state():
|
def api_worker_state():
|
||||||
"""API endpoint to get the worker state"""
|
"""API endpoint to get the worker state"""
|
||||||
return jsonify([ w.current_state() for w in workers ])
|
return jsonify([w.current_state() for w in workers])
|
||||||
|
|
||||||
|
|
||||||
# TODO : Auth
|
# TODO : Auth
|
||||||
@@ -451,7 +465,8 @@ def api_worker_start():
|
|||||||
"""
|
"""
|
||||||
for w in workers:
|
for w in workers:
|
||||||
w.start_worker()
|
w.start_worker()
|
||||||
return jsonify([ w.current_state() for w in workers ])
|
return jsonify([w.current_state() for w in workers])
|
||||||
|
|
||||||
|
|
||||||
# TODO : Auth
|
# TODO : Auth
|
||||||
@app.route("/api/workers/stop")
|
@app.route("/api/workers/stop")
|
||||||
@@ -462,7 +477,8 @@ def api_worker_stop():
|
|||||||
"""
|
"""
|
||||||
for w in list(workers):
|
for w in list(workers):
|
||||||
w.stop_worker()
|
w.stop_worker()
|
||||||
return jsonify([ w.current_state() for w in workers ])
|
return jsonify([w.current_state() for w in workers])
|
||||||
|
|
||||||
|
|
||||||
# TODO : Auth
|
# TODO : Auth
|
||||||
@app.route("/api/printers")
|
@app.route("/api/printers")
|
||||||
@@ -474,6 +490,7 @@ def api_printers_info():
|
|||||||
|
|
||||||
## Authentification
|
## Authentification
|
||||||
|
|
||||||
|
|
||||||
@app.route("/login")
|
@app.route("/login")
|
||||||
@limiter.limit("1/second", override_defaults=False)
|
@limiter.limit("1/second", override_defaults=False)
|
||||||
def login_page():
|
def login_page():
|
||||||
@@ -526,5 +543,6 @@ def camera_status():
|
|||||||
else:
|
else:
|
||||||
socketio.emit("camera_status", False)
|
socketio.emit("camera_status", False)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
app.run(use_reloader=False, host="0.0.0.0", ssl_context="adhoc")
|
app.run(use_reloader=False, host="0.0.0.0", ssl_context="adhoc")
|
||||||
+2
-2
@@ -105,7 +105,7 @@ class PrintQueue:
|
|||||||
"in_queue": True,
|
"in_queue": True,
|
||||||
"content": task.content,
|
"content": task.content,
|
||||||
"signature": task.signature,
|
"signature": task.signature,
|
||||||
"log" : task.log,
|
"log": task.log,
|
||||||
}
|
}
|
||||||
|
|
||||||
if task.task_type == TaskType.TEXT:
|
if task.task_type == TaskType.TEXT:
|
||||||
@@ -118,7 +118,7 @@ class PrintQueue:
|
|||||||
"image_path": str(task.image_path),
|
"image_path": str(task.image_path),
|
||||||
"signature": task.signature,
|
"signature": task.signature,
|
||||||
"process": str(task.process),
|
"process": str(task.process),
|
||||||
"log" : task.log,
|
"log": task.log,
|
||||||
}
|
}
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|||||||
+65
-33
@@ -28,6 +28,7 @@ from brother_ql import create_label
|
|||||||
# Used for typing
|
# Used for typing
|
||||||
from task import PrintTask
|
from task import PrintTask
|
||||||
|
|
||||||
|
|
||||||
class PrinterType(Enum):
|
class PrinterType(Enum):
|
||||||
"""
|
"""
|
||||||
What are the capacities of a Printer ?
|
What are the capacities of a Printer ?
|
||||||
@@ -115,7 +116,7 @@ class EscPosPrinter(Printer):
|
|||||||
Making sure it has paper,
|
Making sure it has paper,
|
||||||
Define default print settings
|
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.printer = None
|
||||||
self.usb_args = {}
|
self.usb_args = {}
|
||||||
self.usb_args["idVendor"] = self.vendor_id
|
self.usb_args["idVendor"] = self.vendor_id
|
||||||
@@ -257,7 +258,6 @@ class EscPosPrinter(Printer):
|
|||||||
if do_cut:
|
if do_cut:
|
||||||
self._cut()
|
self._cut()
|
||||||
|
|
||||||
|
|
||||||
self.app.logger.info("Printed text")
|
self.app.logger.info("Printed text")
|
||||||
self.ready = True
|
self.ready = True
|
||||||
|
|
||||||
@@ -383,11 +383,16 @@ class EscPosPrinter(Printer):
|
|||||||
match (task.task_type.value):
|
match (task.task_type.value):
|
||||||
case "text":
|
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
|
self.ready = True
|
||||||
case "image":
|
case "image":
|
||||||
self._print_img(
|
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
|
self.ready = True
|
||||||
case "qr":
|
case "qr":
|
||||||
@@ -428,9 +433,7 @@ class BrotherPrinter(Printer):
|
|||||||
|
|
||||||
# Match vendor and product IDs so this instance doesn't accidentally
|
# Match vendor and product IDs so this instance doesn't accidentally
|
||||||
# use the identifier belonging to the last device in the backend list.
|
# use the identifier belonging to the last device in the backend list.
|
||||||
expected_prefix = (
|
expected_prefix = (f"usb://0x{vendor_id:04x}:0x{device_id:04x}/").lower()
|
||||||
f"usb://0x{vendor_id:04x}:0x{device_id:04x}/"
|
|
||||||
).lower()
|
|
||||||
|
|
||||||
matching_identifiers = []
|
matching_identifiers = []
|
||||||
|
|
||||||
@@ -451,8 +454,16 @@ class BrotherPrinter(Printer):
|
|||||||
matching_identifiers.append(identifier)
|
matching_identifiers.append(identifier)
|
||||||
|
|
||||||
if len(matching_identifiers) != 1:
|
if len(matching_identifiers) != 1:
|
||||||
self.app.logger.error("Expected one Brother backend device matching %s, found %s", expected_prefix, len(matching_identifiers) )
|
self.app.logger.error(
|
||||||
raise RuntimeError("Expected one Brother backend device matching %s, found %s", expected_prefix, len(matching_identifiers) )
|
"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.
|
# Extract connection details from the identifier for this printer only.
|
||||||
identifier = matching_identifiers[0]
|
identifier = matching_identifiers[0]
|
||||||
@@ -496,7 +507,6 @@ class BrotherPrinter(Printer):
|
|||||||
self.app.logger.debug("Created a Brother printer!")
|
self.app.logger.debug("Created a Brother printer!")
|
||||||
self.ready = True
|
self.ready = True
|
||||||
|
|
||||||
|
|
||||||
def _has_paper(self):
|
def _has_paper(self):
|
||||||
raise NotImplementedError("This printer model does not support this.")
|
raise NotImplementedError("This printer model does not support this.")
|
||||||
|
|
||||||
@@ -512,21 +522,20 @@ class BrotherPrinter(Printer):
|
|||||||
if do_cut:
|
if do_cut:
|
||||||
self._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
|
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:
|
if process:
|
||||||
try:
|
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)
|
processed_path = _process_image(self, data)
|
||||||
except RuntimeError as e:
|
except RuntimeError as e:
|
||||||
self.app.logger.error(
|
self.app.logger.error(
|
||||||
@@ -547,8 +556,6 @@ class BrotherPrinter(Printer):
|
|||||||
)
|
)
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
||||||
qlr = BrotherQLRaster(self.printer_info.model)
|
qlr = BrotherQLRaster(self.printer_info.model)
|
||||||
@@ -570,7 +577,7 @@ class BrotherPrinter(Printer):
|
|||||||
compress=False,
|
compress=False,
|
||||||
dpi_600=False,
|
dpi_600=False,
|
||||||
cut=False,
|
cut=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
success = send(
|
success = send(
|
||||||
instructions=instructions,
|
instructions=instructions,
|
||||||
@@ -679,29 +686,47 @@ class BrotherPrinter(Printer):
|
|||||||
"""Execute actual print based on task type"""
|
"""Execute actual print based on task type"""
|
||||||
i_m_ready = self._state()
|
i_m_ready = self._state()
|
||||||
while not i_m_ready:
|
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()
|
i_m_ready = self._state()
|
||||||
time.sleep(0.3)
|
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
|
self.ready = False
|
||||||
|
|
||||||
try:
|
try:
|
||||||
match (task.task_type.value):
|
match (task.task_type.value):
|
||||||
case "image":
|
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":
|
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 _:
|
case _:
|
||||||
raise RuntimeError("This task type is not supported")
|
raise RuntimeError("This task type is not supported")
|
||||||
except ValueError as ve:
|
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
|
raise ve
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise 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
|
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",
|
"Image is dark; increasing brightness by %.2f",
|
||||||
brightness_factor,
|
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())
|
contrast = float(np.asarray(grayscale_image, dtype=np.float32).std())
|
||||||
self.app.logger.debug("Grayscale standard deviation: %.2f", contrast)
|
self.app.logger.debug("Grayscale standard deviation: %.2f", contrast)
|
||||||
@@ -758,7 +785,7 @@ def text_to_image(
|
|||||||
background="white",
|
background="white",
|
||||||
fill="black",
|
fill="black",
|
||||||
output_dir="src/static/uploads",
|
output_dir="src/static/uploads",
|
||||||
):
|
):
|
||||||
"""Converts a string to an image"""
|
"""Converts a string to an image"""
|
||||||
|
|
||||||
font = ImageFont.truetype(font_path, font_size)
|
font = ImageFont.truetype(font_path, font_size)
|
||||||
@@ -829,7 +856,13 @@ def text_to_image(
|
|||||||
return str(image_path)
|
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
|
# 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)
|
# self.app.logger.debug("Found label %s with maximum dimensions %s", label_type, max_image_dimension)
|
||||||
|
|
||||||
|
|
||||||
# # Open image
|
# # Open image
|
||||||
# with Image.open(image_path ) as img:
|
# with Image.open(image_path ) as img:
|
||||||
# self.app.logger.debug("Image current dimensions before resizing are %s", img.size)
|
# self.app.logger.debug("Image current dimensions before resizing are %s", img.size)
|
||||||
|
|||||||
+20
-9
@@ -102,8 +102,10 @@ class Printers:
|
|||||||
app=self.app,
|
app=self.app,
|
||||||
vendor_id=vendir,
|
vendor_id=vendir,
|
||||||
device_id=prid,
|
device_id=prid,
|
||||||
configuration_file=self.configuration_file["printer"]["epson"]
|
configuration_file=self.configuration_file["printer"][
|
||||||
)
|
"epson"
|
||||||
|
],
|
||||||
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
@@ -119,8 +121,10 @@ class Printers:
|
|||||||
self.app,
|
self.app,
|
||||||
dev.idVendor,
|
dev.idVendor,
|
||||||
dev.idProduct,
|
dev.idProduct,
|
||||||
configuration_file=self.configuration_file["printer"]["brother"]
|
configuration_file=self.configuration_file["printer"][
|
||||||
)
|
"brother"
|
||||||
|
],
|
||||||
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.app.logger.error(
|
self.app.logger.error(
|
||||||
"Could not create a %s printer class with %s:%s",
|
"Could not create a %s printer class with %s:%s",
|
||||||
@@ -132,12 +136,18 @@ class Printers:
|
|||||||
|
|
||||||
# If the object creation is successfull, we add it to the list of Printers
|
# If the object creation is successfull, we add it to the list of Printers
|
||||||
printers.add(brother_printer)
|
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 _:
|
case _:
|
||||||
self.app.logger.debug(
|
self.app.logger.debug(
|
||||||
"Found a printer of unknown manufacturer : %s", manufacturer
|
"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
|
# end match
|
||||||
|
|
||||||
self.app.logger.debug("Found %s printers", len(printers))
|
self.app.logger.debug("Found %s printers", len(printers))
|
||||||
@@ -177,9 +187,9 @@ class Printers:
|
|||||||
printers_info_list.append(
|
printers_info_list.append(
|
||||||
{
|
{
|
||||||
"Name": i.printer_type.name,
|
"Name": i.printer_type.name,
|
||||||
"Used" : i.used,
|
"Used": i.used,
|
||||||
"Ready" : i.ready,
|
"Ready": i.ready,
|
||||||
"Info" : i.printer_info,
|
"Info": i.printer_info,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -188,6 +198,7 @@ class Printers:
|
|||||||
def __len__(self):
|
def __len__(self):
|
||||||
return len(self.printers)
|
return len(self.printers)
|
||||||
|
|
||||||
|
|
||||||
class _FindClass:
|
class _FindClass:
|
||||||
"""
|
"""
|
||||||
Use by usb.core to modify the way USB devices are found
|
Use by usb.core to modify the way USB devices are found
|
||||||
|
|||||||
+9
-2
@@ -96,12 +96,19 @@ class ImageTask(PrintTask):
|
|||||||
|
|
||||||
def get_print_data(self):
|
def get_print_data(self):
|
||||||
# Return image data in printer-compatible format
|
# 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):
|
class RemoveTask(PrintTask):
|
||||||
"""
|
"""
|
||||||
This class is used to clear images and leftovers after a print
|
This class is used to clear images and leftovers after a print
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, task_id, image_path):
|
def __init__(self, task_id, image_path):
|
||||||
super().__init__(TaskType.REMOVE)
|
super().__init__(TaskType.REMOVE)
|
||||||
self.task_id = self._generate_id() if not task_id else task_id
|
self.task_id = self._generate_id() if not task_id else task_id
|
||||||
@@ -111,4 +118,4 @@ class RemoveTask(PrintTask):
|
|||||||
# the task existence in itself is indication of what to do
|
# the task existence in itself is indication of what to do
|
||||||
def get_print_data(self):
|
def get_print_data(self):
|
||||||
# Return image data in printer-compatible format
|
# Return image data in printer-compatible format
|
||||||
return {"img": self.image_path}
|
return {"img": self.image_path}
|
||||||
+19
-7
@@ -30,8 +30,14 @@ class Web:
|
|||||||
# are added back to back, another task could be
|
# are added back to back, another task could be
|
||||||
# inserted between the two.
|
# inserted between the two.
|
||||||
for i in range(many):
|
for i in range(many):
|
||||||
sms = self.print_queue.enqueue(TextTask(content=texte, signature=sign, do_cut=do_cut))
|
sms = self.print_queue.enqueue(
|
||||||
self.app.logger.info("Added a SMS task at position %s, it should %scut", sms, "" if not do_cut else "not ")
|
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)
|
self.app.logger.debug("%s", do_cut)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.app.logger.error(e)
|
self.app.logger.error(e)
|
||||||
@@ -41,7 +47,7 @@ class Web:
|
|||||||
|
|
||||||
def print_image(
|
def print_image(
|
||||||
self, image, sign: str, do_cut: bool, process_image: bool, many: int = 1
|
self, image, sign: str, do_cut: bool, process_image: bool, many: int = 1
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""
|
"""
|
||||||
Get an image and a signature, prints the image and cuts after that.
|
Get an image and a signature, prints the image and cuts after that.
|
||||||
"""
|
"""
|
||||||
@@ -62,15 +68,19 @@ class Web:
|
|||||||
ImageTask(
|
ImageTask(
|
||||||
os.path.join(
|
os.path.join(
|
||||||
self.app.config["UPLOAD_FOLDER"],
|
self.app.config["UPLOAD_FOLDER"],
|
||||||
secure_filename(str(file_uploaded.split("/").pop()))
|
secure_filename(str(file_uploaded.split("/").pop())),
|
||||||
),
|
),
|
||||||
signature=sign,
|
signature=sign,
|
||||||
process=process_image,
|
process=process_image,
|
||||||
task_id=str(uuid.uuid4()),
|
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:
|
except Exception as e:
|
||||||
raise RuntimeError("Could not add IMG to queue " + str(e)) from e
|
raise RuntimeError("Could not add IMG to queue " + str(e)) from e
|
||||||
@@ -107,7 +117,9 @@ class Web:
|
|||||||
extension = filename.split(".").pop()
|
extension = filename.split(".").pop()
|
||||||
self.app.logger.debug("File valid")
|
self.app.logger.debug("File valid")
|
||||||
try:
|
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)
|
image.save(image_uuid_path)
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
self.app.logger.error("Could not save file %s", e)
|
self.app.logger.error("Could not save file %s", e)
|
||||||
|
|||||||
+34
-12
@@ -10,7 +10,6 @@ import random
|
|||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class PrintWorker(threading.Thread):
|
class PrintWorker(threading.Thread):
|
||||||
"""
|
"""
|
||||||
A thread used to consume Tasks added to a Print Queue.
|
A thread used to consume Tasks added to a Print Queue.
|
||||||
@@ -23,7 +22,7 @@ class PrintWorker(threading.Thread):
|
|||||||
tasks. TODO : Change that
|
tasks. TODO : Change that
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, app, print_queue, printers_pool, printer_index=0 ):
|
def __init__(self, app, print_queue, printers_pool, printer_index=0):
|
||||||
super().__init__(daemon=True)
|
super().__init__(daemon=True)
|
||||||
self.app = app
|
self.app = app
|
||||||
self.print_queue = print_queue
|
self.print_queue = print_queue
|
||||||
@@ -39,7 +38,12 @@ class PrintWorker(threading.Thread):
|
|||||||
self._printer_index = printer_index
|
self._printer_index = printer_index
|
||||||
self.printer = self._acquire_available_printer()
|
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):
|
def _acquire_available_printer(self):
|
||||||
result = self.printers.acquire_available_printer(
|
result = self.printers.acquire_available_printer(
|
||||||
@@ -56,7 +60,9 @@ class PrintWorker(threading.Thread):
|
|||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
"""Background thread that processes queue items"""
|
"""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:
|
while True:
|
||||||
# If the printer is dead or asleep, it can't work.
|
# 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:
|
if self.running and self.printer is None:
|
||||||
self.app.logger.debug(
|
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.printer = self._acquire_available_printer()
|
||||||
self.app.logger.debug(
|
self.app.logger.debug(
|
||||||
"\t[⚙ %s] Got a %s ( %s ) printer and it's %s", self.id ,
|
"\t[⚙ %s] Got a %s ( %s ) printer and it's %s",
|
||||||
self.printer.printer_info.name, self.printer.printer_info.model,
|
self.id,
|
||||||
|
self.printer.printer_info.name,
|
||||||
|
self.printer.printer_info.model,
|
||||||
"Ready" if self.printer.ready else "Not ready",
|
"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 the printer is not ready, we wait for it to become ready.
|
||||||
if not self.printer.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)
|
time.sleep(1)
|
||||||
continue
|
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)
|
# self.app.logger.debug("\t[⚙ %s] Trying to get a task from the queue ", self.id)
|
||||||
task = self.print_queue.dequeue()
|
task = self.print_queue.dequeue()
|
||||||
except Exception as e:
|
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.state = "idle"
|
||||||
self.printer.free_printer()
|
self.printer.free_printer()
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
@@ -116,7 +129,12 @@ class PrintWorker(threading.Thread):
|
|||||||
) from e
|
) from e
|
||||||
|
|
||||||
if task:
|
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"
|
task.status = "processing"
|
||||||
|
|
||||||
@@ -164,9 +182,13 @@ class PrintWorker(threading.Thread):
|
|||||||
Return the worker state
|
Return the worker state
|
||||||
"""
|
"""
|
||||||
return {
|
return {
|
||||||
"id" : self.id,
|
"id": self.id,
|
||||||
"is_running": self.running,
|
"is_running": self.running,
|
||||||
"queue_size": len(self.print_queue),
|
"queue_size": len(self.print_queue),
|
||||||
"state": self.state,
|
"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