Multi-printers #32
No files matched your search
+49
-16
@@ -25,6 +25,7 @@ takes a picture and activates the flash while simply informing the web page.
|
|||||||
import sys
|
import sys
|
||||||
import os # For VARS from the shell.
|
import os # For VARS from the shell.
|
||||||
import pprint # To pretty print JSON
|
import pprint # To pretty print JSON
|
||||||
|
import threading
|
||||||
import toml # Used for the config file parsing
|
import toml # Used for the config file parsing
|
||||||
from flask import (
|
from flask import (
|
||||||
Flask,
|
Flask,
|
||||||
@@ -39,12 +40,33 @@ import werkzeug.exceptions
|
|||||||
from flask_socketio import SocketIO
|
from flask_socketio import SocketIO
|
||||||
from flask_limiter import Limiter
|
from flask_limiter import Limiter
|
||||||
from flask_limiter.util import get_remote_address
|
from flask_limiter.util import get_remote_address
|
||||||
|
from logging.config import dictConfig
|
||||||
from raspberry import Raspberry # The Raspberry pi control Class
|
from raspberry import Raspberry # The Raspberry pi control Class
|
||||||
from web import Web # Wrapper for the web routes and API
|
from web import Web # Wrapper for the web routes and API
|
||||||
from print_queue import PrintQueue
|
from print_queue import PrintQueue
|
||||||
from worker import PrintWorker
|
from worker import PrintWorker
|
||||||
from printers import Printers
|
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']
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
# We create the main Flask object
|
# We create the main Flask object
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
socketio = SocketIO(app, cors_allowed_origins="*")
|
socketio = SocketIO(app, cors_allowed_origins="*")
|
||||||
@@ -97,6 +119,8 @@ app.config["ALLOWED_EXTENSIONS"] = ALLOWED_EXTENSIONS
|
|||||||
app.config["MAX_CONTENT_LENGTH"] = 30 * 1000 * 1000 # Maximum 10Mb for a file upload
|
app.config["MAX_CONTENT_LENGTH"] = 30 * 1000 * 1000 # Maximum 10Mb for a file upload
|
||||||
app.config["TEMPLATES_AUTO_RELOAD"] = True
|
app.config["TEMPLATES_AUTO_RELOAD"] = True
|
||||||
|
|
||||||
|
main_lock = threading.Lock()
|
||||||
|
|
||||||
# Queue creation
|
# Queue creation
|
||||||
print_queue = PrintQueue(app)
|
print_queue = PrintQueue(app)
|
||||||
|
|
||||||
@@ -111,29 +135,36 @@ web = Web(app, print_queue)
|
|||||||
# Create a pool of printers
|
# Create a pool of printers
|
||||||
try:
|
try:
|
||||||
# comment: Find all printers connected to the system
|
# comment: Find all printers connected to the system
|
||||||
printers_pool = Printers(app, configuration_file)
|
printers_pool = Printers(app, configuration_file, main_lock)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
app.logger.error("Could not create a pool of printers because %s", str(e))
|
app.logger.error("Could not create a pool of printers because %s", str(e))
|
||||||
sys.exit(-1)
|
sys.exit(-1)
|
||||||
# end try
|
# end try
|
||||||
|
|
||||||
|
# TODO : Make n worker for every printer
|
||||||
|
|
||||||
# Start worker thread
|
# Start worker thread
|
||||||
|
workers = set()
|
||||||
|
for i in range(len(printers_pool)):
|
||||||
try:
|
try:
|
||||||
worker = PrintWorker(app, print_queue, printers_pool=printers_pool)
|
worker = PrintWorker(app, print_queue, printers_pool=printers_pool, printer_index=i)
|
||||||
|
workers.add(worker)
|
||||||
worker.start()
|
worker.start()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
app.logger.error("Could not start the worker because %s ", str(e))
|
app.logger.error("Could not start the worker because %s ", str(e))
|
||||||
sys.exit(-1)
|
sys.exit(-1)
|
||||||
|
|
||||||
|
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")
|
||||||
|
|
||||||
|
|
||||||
# The rate limit
|
# The rate limit
|
||||||
limiter = Limiter(
|
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"]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
app.logger.info("🖶 Welcome to LittlePrynter !")
|
|
||||||
|
|
||||||
|
|
||||||
# General routes
|
# General routes
|
||||||
@app.route("/")
|
@app.route("/")
|
||||||
@limiter.limit("5/second", override_defaults=False)
|
@limiter.limit("5/second", override_defaults=False)
|
||||||
@@ -404,32 +435,34 @@ def api_queue_completed():
|
|||||||
return jsonify(web.get_queue_completed())
|
return jsonify(web.get_queue_completed())
|
||||||
|
|
||||||
|
|
||||||
@app.route("/api/worker", methods=["GET"])
|
@app.route("/api/workers", methods=["GET"])
|
||||||
@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(worker.current_state())
|
return jsonify([ w.current_state() for w in workers ])
|
||||||
|
|
||||||
|
|
||||||
# TODO : Auth
|
# TODO : Auth
|
||||||
@app.route("/api/worker/start")
|
@app.route("/api/workers/start")
|
||||||
@limiter.limit("6/minute")
|
@limiter.limit("6/minute")
|
||||||
def api_worker_start():
|
def api_worker_start():
|
||||||
"""
|
"""
|
||||||
Enable to worker. This starts to process the print queue.
|
Start workers. This starts to process the print queue.
|
||||||
"""
|
"""
|
||||||
worker.start_worker()
|
for w in workers:
|
||||||
return jsonify(worker.current_state())
|
w.start_worker()
|
||||||
|
return jsonify([ w.current_state() for w in workers ])
|
||||||
|
|
||||||
# TODO : Auth
|
# TODO : Auth
|
||||||
@app.route("/api/worker/stop")
|
@app.route("/api/workers/stop")
|
||||||
@limiter.limit("6/minute")
|
@limiter.limit("6/minute")
|
||||||
def api_worker_stop():
|
def api_worker_stop():
|
||||||
"""
|
"""
|
||||||
Stops the print queue. This stops the processing of the print queue.
|
Stops workers. This stops the processing of the print queue.
|
||||||
"""
|
"""
|
||||||
worker.stop_worker()
|
for w in list(workers):
|
||||||
return jsonify(worker.current_state())
|
w.stop_worker()
|
||||||
|
return jsonify([ w.current_state() for w in workers ])
|
||||||
|
|
||||||
# TODO : Auth
|
# TODO : Auth
|
||||||
@app.route("/api/printers")
|
@app.route("/api/printers")
|
||||||
|
|||||||
+16
-19
@@ -28,6 +28,7 @@ class PrintQueue:
|
|||||||
self.app.logger.debug("Created a new PrintQueue")
|
self.app.logger.debug("Created a new PrintQueue")
|
||||||
|
|
||||||
def __len__(self) -> int:
|
def __len__(self) -> int:
|
||||||
|
with self._lock:
|
||||||
return len(self._queue)
|
return len(self._queue)
|
||||||
|
|
||||||
def enqueue(self, task):
|
def enqueue(self, task):
|
||||||
@@ -57,45 +58,37 @@ class PrintQueue:
|
|||||||
"""Get current position of task in queue (1-indexed)"""
|
"""Get current position of task in queue (1-indexed)"""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if task.task_id in self._completed_tasks:
|
if task.task_id in self._completed_tasks:
|
||||||
return None # Task already completed
|
return None
|
||||||
|
|
||||||
try:
|
|
||||||
# Try to get the position of a Task
|
|
||||||
return self._queue.index(task)
|
return self._queue.index(task)
|
||||||
except ValueError as e:
|
|
||||||
raise e
|
|
||||||
# end try
|
|
||||||
|
|
||||||
def is_empty(self):
|
def is_empty(self):
|
||||||
"""Check if queue is empty"""
|
"""Check if queue is empty"""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self.app.logger.debug("Checking if queue is empty")
|
self.app.logger.debug("Checking if queue is empty")
|
||||||
return len(self._queue) == 0
|
return not self._queue
|
||||||
|
|
||||||
def get_queue_state(self):
|
def get_queue_state(self):
|
||||||
"""Return current queue state"""
|
"""Return current queue state"""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self.app.logger.debug("Return current queue state")
|
tasks = list(self._queue)
|
||||||
|
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
"task_id": t.task_id,
|
"task_id": task.task_id,
|
||||||
"status": t.status,
|
"status": task.status,
|
||||||
"type": str(t.task_type),
|
"type": str(task.task_type),
|
||||||
"content": t.get_print_data(),
|
"content": task.get_print_data(),
|
||||||
}
|
}
|
||||||
for t in self._queue
|
for task in tasks
|
||||||
]
|
]
|
||||||
|
|
||||||
def get_queue_completed(self):
|
def get_queue_completed(self):
|
||||||
"""Return completed queue elements"""
|
"""Return completed queue elements"""
|
||||||
with self._lock:
|
|
||||||
self.app.logger.debug("Return completed queue elements")
|
self.app.logger.debug("Return completed queue elements")
|
||||||
return self._completed_tasks
|
return self._completed_tasks
|
||||||
|
|
||||||
def get_status(self, task_id):
|
def get_status(self, task_id):
|
||||||
"""Get full status info for a task"""
|
"""Get full status info for a task"""
|
||||||
with self._lock:
|
|
||||||
|
|
||||||
if task_id in self._completed_tasks:
|
if task_id in self._completed_tasks:
|
||||||
return self._completed_tasks[task_id]
|
return self._completed_tasks[task_id]
|
||||||
|
|
||||||
@@ -112,6 +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,
|
||||||
}
|
}
|
||||||
|
|
||||||
if task.task_type == TaskType.TEXT:
|
if task.task_type == TaskType.TEXT:
|
||||||
@@ -124,6 +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,
|
||||||
}
|
}
|
||||||
|
|
||||||
if task.task_type == TaskType.CUT:
|
if task.task_type == TaskType.CUT:
|
||||||
@@ -133,12 +128,13 @@ class PrintQueue:
|
|||||||
"type": task.task_type,
|
"type": task.task_type,
|
||||||
"position": index,
|
"position": index,
|
||||||
"in_queue": True,
|
"in_queue": True,
|
||||||
|
"log" : task.log,
|
||||||
}
|
}
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def mark_completed(self, task_id, task_status):
|
def mark_completed(self, task_id, task_status, log=None):
|
||||||
"""Mark task as completed and remove from queue"""
|
"""Record a terminal task status."""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self._completed_tasks[task_id] = {
|
self._completed_tasks[task_id] = {
|
||||||
"task_id": task_id,
|
"task_id": task_id,
|
||||||
@@ -146,4 +142,5 @@ class PrintQueue:
|
|||||||
"position": None,
|
"position": None,
|
||||||
"in_queue": False,
|
"in_queue": False,
|
||||||
"completed_at": datetime.now().isoformat(),
|
"completed_at": datetime.now().isoformat(),
|
||||||
|
"log": log,
|
||||||
}
|
}
|
||||||
+178
-77
@@ -9,22 +9,24 @@ from dataclasses import dataclass
|
|||||||
import time
|
import time
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
import uuid
|
import uuid
|
||||||
import threading
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
import usb.core
|
import usb.core
|
||||||
from PIL import Image, ImageEnhance, ImageDraw, ImageFont
|
from PIL import Image, ImageEnhance, ImageDraw, ImageFont, ImageOps
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
# Importing the modules needed for each supported printer Type
|
# Importing the modules needed for each supported printer Type
|
||||||
import escpos.printer
|
import escpos.printer
|
||||||
from brother_ql.models import ModelsManager
|
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.backends import backend_factory, guess_backend
|
||||||
from brother_ql.raster import BrotherQLRaster
|
from brother_ql.raster import BrotherQLRaster
|
||||||
from brother_ql.conversion import convert
|
from brother_ql.conversion import convert
|
||||||
from brother_ql.backends.helpers import send
|
from brother_ql.backends.helpers import send
|
||||||
from brother_ql import create_label
|
from brother_ql import create_label
|
||||||
|
|
||||||
|
# Used for typing
|
||||||
|
from task import PrintTask
|
||||||
|
|
||||||
class PrinterType(Enum):
|
class PrinterType(Enum):
|
||||||
"""
|
"""
|
||||||
@@ -78,7 +80,6 @@ class Printer(ABC):
|
|||||||
self.device_id = device_id
|
self.device_id = device_id
|
||||||
self.ready = False
|
self.ready = False
|
||||||
self.printer_type = printer_type
|
self.printer_type = printer_type
|
||||||
self._lock = threading.Lock()
|
|
||||||
self.used = False
|
self.used = False
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
@@ -90,7 +91,7 @@ class Printer(ABC):
|
|||||||
"""Reports the state of the Printer"""
|
"""Reports the state of the Printer"""
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def print_task(self, task_type, data) -> None:
|
def print_task(self, task: PrintTask, data) -> None:
|
||||||
"""Takes a PrintTask and executes it"""
|
"""Takes a PrintTask and executes it"""
|
||||||
|
|
||||||
def use_printer(self) -> None:
|
def use_printer(self) -> None:
|
||||||
@@ -204,7 +205,7 @@ class EscPosPrinter(Printer):
|
|||||||
self.printer.close()
|
self.printer.close()
|
||||||
return True
|
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):
|
if not isinstance(msg, str):
|
||||||
self.app.logger.error(
|
self.app.logger.error(
|
||||||
"It is not possible to print a " + str(type(msg)) + ", only strings."
|
"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."
|
"Unable to print a SMS, the printer couldn't do it."
|
||||||
) from e
|
) from e
|
||||||
|
|
||||||
|
if do_cut:
|
||||||
|
self._cut()
|
||||||
|
|
||||||
|
|
||||||
self.app.logger.info("Printed text")
|
self.app.logger.info("Printed text")
|
||||||
self.ready = True
|
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)
|
clean_signature = str(signature)
|
||||||
|
|
||||||
if len(signature) > int(self.configuration_file["signature_max_length"]):
|
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))
|
self.app.logger.error("Could not close the printer connexion %s", str(e))
|
||||||
raise RuntimeError("Could not close the printer connexion. ") from e
|
raise RuntimeError("Could not close the printer connexion. ") from e
|
||||||
|
|
||||||
|
if do_cut:
|
||||||
|
self._cut()
|
||||||
|
|
||||||
self.app.logger.info("Printed a picture")
|
self.app.logger.info("Printed a picture")
|
||||||
self.ready = True
|
self.ready = True
|
||||||
|
|
||||||
@@ -356,12 +364,9 @@ class EscPosPrinter(Printer):
|
|||||||
|
|
||||||
return is_ready and has_paper # and is_online
|
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"""
|
"""Execute actual print based on task type"""
|
||||||
|
|
||||||
with self._lock:
|
|
||||||
self.app.logger.debug("Acquired lock to start print")
|
|
||||||
|
|
||||||
i_m_ready = self._state()
|
i_m_ready = self._state()
|
||||||
while not i_m_ready:
|
while not i_m_ready:
|
||||||
self.app.logger.debug(
|
self.app.logger.debug(
|
||||||
@@ -375,19 +380,16 @@ class EscPosPrinter(Printer):
|
|||||||
self.ready = False
|
self.ready = False
|
||||||
try:
|
try:
|
||||||
self.app.logger.debug("Checking task type")
|
self.app.logger.debug("Checking task type")
|
||||||
match (task_type.value):
|
match (task.task_type.value):
|
||||||
case "text":
|
case "text":
|
||||||
|
|
||||||
self._print_txt(data["txt"], signature=data["sign"])
|
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"]
|
data["img"], signature=data["sign"], process=data["process"], do_cut=data["do_cut"]
|
||||||
)
|
)
|
||||||
self.ready = True
|
self.ready = True
|
||||||
case "cut":
|
|
||||||
self._cut()
|
|
||||||
self.ready = True
|
|
||||||
case "qr":
|
case "qr":
|
||||||
self._qr(data["txt"])
|
self._qr(data["txt"])
|
||||||
self.ready = True
|
self.ready = True
|
||||||
@@ -405,50 +407,79 @@ class BrotherPrinter(Printer):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, app, vendor_id, device_id, configuration_file):
|
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.printer = None
|
||||||
self.usb_args = {}
|
self.usb_args = {
|
||||||
self.usb_args["idVendor"] = self.vendor_id
|
"idVendor": self.vendor_id,
|
||||||
self.usb_args["idProduct"] = self.device_id
|
"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
|
# Discover the backend identifier for this specific USB printer.
|
||||||
|
|
||||||
self.app.logger.debug("Creating backend for Brother")
|
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:
|
# Match vendor and product IDs so this instance doesn't accidentally
|
||||||
self.app.logger.debug(f"Found device: {printer}")
|
# use the identifier belonging to the last device in the backend list.
|
||||||
identifier = printer["identifier"]
|
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("/")
|
parts = identifier.split("/")
|
||||||
|
|
||||||
if len(parts) < 4:
|
if len(parts) < 4:
|
||||||
self.app.logger.warning(
|
self.app.logger.warning(
|
||||||
f"Skipping device with invalid identifier format: {identifier}"
|
"Skipping device with invalid identifier format: %s",
|
||||||
|
identifier,
|
||||||
)
|
)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
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]
|
protocol = parts[0]
|
||||||
# device_info = parts[2]
|
|
||||||
serial_number = parts[3]
|
serial_number = parts[3]
|
||||||
|
|
||||||
|
# Find the model that corresponds to this printer's product ID.
|
||||||
try:
|
try:
|
||||||
for m in self.model_manager.iter_elements():
|
model = None
|
||||||
if m.product_id == self.device_id:
|
for item in self.model_manager.iter_elements():
|
||||||
model = m.identifier
|
if item.product_id == self.device_id:
|
||||||
|
model = item.identifier
|
||||||
break
|
break
|
||||||
|
|
||||||
self.app.logger.debug(f"Matched printer model: {model}")
|
if model is None:
|
||||||
except ValueError as ve:
|
raise RuntimeError(
|
||||||
self.app.logger.warning("Invalid product ID format:" + str(ve))
|
f"No Brother model found for product ID {self.device_id:#06x}"
|
||||||
raise ve
|
)
|
||||||
except Exception as e:
|
|
||||||
self.app.logger.error("Error while finding a model ? : " + str(e))
|
self.app.logger.debug("Matched printer model: %s", model)
|
||||||
raise e
|
except Exception:
|
||||||
|
self.app.logger.exception(
|
||||||
|
"Error while finding a model for product ID %s",
|
||||||
|
self.device_id,
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
|
||||||
self.printer_info = PrinterInfo(
|
self.printer_info = PrinterInfo(
|
||||||
identifier=identifier,
|
identifier=identifier,
|
||||||
@@ -458,37 +489,44 @@ class BrotherPrinter(Printer):
|
|||||||
vendor_id=vendor_id,
|
vendor_id=vendor_id,
|
||||||
product_id=self.device_id,
|
product_id=self.device_id,
|
||||||
serial_number=serial_number,
|
serial_number=serial_number,
|
||||||
label_type=configuration_file[
|
label_type=configuration_file["label_type"],
|
||||||
"label_type"
|
# TODO: Implement automatic label type detection.
|
||||||
], # TODO: Implement automatic label type detection : https://framagit.org/stickoeur/diagnostickoeur/-/blob/no-masters/printit.py?ref_type=heads#L239
|
|
||||||
)
|
)
|
||||||
|
|
||||||
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.")
|
||||||
|
|
||||||
def _state(self):
|
def _state(self):
|
||||||
return self.ready
|
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"""
|
"""Print text after converting it to an image"""
|
||||||
self._print_img(text_to_image(msg))
|
self._print_img(text_to_image(msg))
|
||||||
|
if signature != "":
|
||||||
self._print_img(text_to_image(signature))
|
self._print_img(text_to_image(signature))
|
||||||
|
|
||||||
|
if do_cut:
|
||||||
|
self._cut()
|
||||||
|
|
||||||
|
|
||||||
def _print_img(
|
def _print_img(
|
||||||
self,
|
self,
|
||||||
data,
|
data,
|
||||||
signature="",
|
signature="",
|
||||||
process=False,
|
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", data)
|
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("Proccessing the image")
|
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(
|
||||||
@@ -509,17 +547,21 @@ class BrotherPrinter(Printer):
|
|||||||
)
|
)
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
im = Image.open(processed_path)
|
|
||||||
qlr = BrotherQLRaster(self.printer_info.model)
|
qlr = BrotherQLRaster(self.printer_info.model)
|
||||||
# create_label(qlr, im, self.printer_info.label_type, cut=False, dither=True)
|
# Resize the image for the label type
|
||||||
|
# device_pixel_width = qlr.get_pixel_width()
|
||||||
# noinspection PyCallingNonCallable
|
# im = _resize_image(
|
||||||
# be = BACKEND_CLASS(BACKEND_STRING_DESCR)
|
# self,
|
||||||
# be.write(qlr.data)
|
# label_type=self.printer_info.label_type, image_path=processed_path,
|
||||||
# be.dispose()
|
# device_pixel_width=device_pixel_width,
|
||||||
# del be
|
# printer_model=qlr.model
|
||||||
|
# )
|
||||||
|
|
||||||
|
im = Image.open(processed_path)
|
||||||
instructions = convert(
|
instructions = convert(
|
||||||
qlr=qlr,
|
qlr=qlr,
|
||||||
images=[im],
|
images=[im],
|
||||||
@@ -534,11 +576,11 @@ class BrotherPrinter(Printer):
|
|||||||
instructions=instructions,
|
instructions=instructions,
|
||||||
printer_identifier=BACKEND_STRING_DESCR,
|
printer_identifier=BACKEND_STRING_DESCR,
|
||||||
backend_identifier="pyusb",
|
backend_identifier="pyusb",
|
||||||
blocking=False,
|
blocking=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
self.app.logger.debug(str(success))
|
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)
|
time.sleep(2)
|
||||||
|
|
||||||
except usb.core.USBError as e:
|
except usb.core.USBError as e:
|
||||||
@@ -585,7 +627,7 @@ class BrotherPrinter(Printer):
|
|||||||
blocking=False,
|
blocking=False,
|
||||||
)
|
)
|
||||||
self.app.logger.debug(str(success))
|
self.app.logger.debug(str(success))
|
||||||
self.app.logger.debug("Printed signature")
|
self.app.logger.debug("Printed signature %s", signature)
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -597,6 +639,9 @@ class BrotherPrinter(Printer):
|
|||||||
except OSError as e:
|
except OSError as e:
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
|
if do_cut:
|
||||||
|
self._cut()
|
||||||
|
|
||||||
def _cut(self):
|
def _cut(self):
|
||||||
self.app.logger.debug("Cutting via Brother Printer")
|
self.app.logger.debug("Cutting via Brother Printer")
|
||||||
try:
|
try:
|
||||||
@@ -630,38 +675,35 @@ class BrotherPrinter(Printer):
|
|||||||
# This should not be reached by a print on a BrotherQL
|
# This should not be reached by a print on a BrotherQL
|
||||||
raise NotImplementedError()
|
raise NotImplementedError()
|
||||||
|
|
||||||
def print_task(self, task_type, data):
|
def print_task(self, task, data):
|
||||||
"""Execute actual print based on task type"""
|
"""Execute actual print based on task type"""
|
||||||
with self._lock:
|
|
||||||
self.app.logger.debug("Acquired lock to start print")
|
|
||||||
i_m_ready = self._state()
|
i_m_ready = self._state()
|
||||||
while not i_m_ready:
|
while not i_m_ready:
|
||||||
self.app.logger.debug(
|
self.app.logger.debug("\t[⚙ %s] Waiting for the printer to become ready, current state %s ", self.id, str(i_m_ready))
|
||||||
"Waiting for the printer to become ready, current state %s ",
|
|
||||||
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("Checked state to start printing : %s", 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_type.value):
|
match (task.task_type.value):
|
||||||
case "image":
|
case "image":
|
||||||
self._print_img(data["img"], signature=data["sign"])
|
self._print_img(data["img"], signature=data["sign"], do_cut=data["do_cut"])
|
||||||
self.ready = True
|
|
||||||
case "cut":
|
|
||||||
self._cut()
|
|
||||||
self.ready = True
|
|
||||||
case "text":
|
case "text":
|
||||||
self._print_txt(data["txt"], signature=data["sign"])
|
self._print_txt(data["txt"], signature=data["sign"], do_cut=data["do_cut"])
|
||||||
self.ready = True
|
|
||||||
case _:
|
case _:
|
||||||
raise RuntimeError("This task type is not supported")
|
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:
|
except Exception as e:
|
||||||
raise 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):
|
def _process_image(self, path, max_width=575, max_height=1000):
|
||||||
brightness_threshold = 100
|
brightness_threshold = 100
|
||||||
@@ -674,9 +716,9 @@ def _process_image(self, path, max_width=575, max_height=1000):
|
|||||||
Image.Resampling.LANCZOS,
|
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)
|
self.app.logger.debug("Average brightness of the image: %.2f", avg_brightness)
|
||||||
|
|
||||||
if avg_brightness < brightness_threshold:
|
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",
|
"Image is dark; increasing brightness by %.2f",
|
||||||
brightness_factor,
|
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)
|
self.app.logger.debug("Grayscale standard deviation: %.2f", contrast)
|
||||||
|
|
||||||
# Save the enhanced result.
|
# 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"
|
jpeg_path = os.path.splitext(path)[0] + "_processed.jpg"
|
||||||
processed.save(jpeg_path, format="JPEG", quality=95, optimize=True)
|
processed.save(jpeg_path, format="JPEG", quality=95, optimize=True)
|
||||||
@@ -785,3 +827,62 @@ def text_to_image(
|
|||||||
image.save(image_path, format="PNG")
|
image.save(image_path, format="PNG")
|
||||||
|
|
||||||
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):
|
||||||
|
# """
|
||||||
|
# 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
|
||||||
+12
-11
@@ -18,14 +18,15 @@ class Printers:
|
|||||||
Finds and creates a set of Printer that can be used by the Workers to print.
|
Finds and creates a set of Printer that can be used by the Workers to print.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, app, configuration_file):
|
def __init__(self, app, configuration_file, threadlock):
|
||||||
"""
|
"""
|
||||||
Discovers printers connected to the computer
|
Discovers printers connected to the computer
|
||||||
"""
|
"""
|
||||||
self.app = app
|
self.app = app
|
||||||
self.configuration_file = configuration_file
|
self.configuration_file = configuration_file
|
||||||
|
self._lock = threadlock
|
||||||
|
with self._lock:
|
||||||
self.printers = list(self._discover_printers())
|
self.printers = list(self._discover_printers())
|
||||||
self._lock = threading.Lock()
|
|
||||||
|
|
||||||
def _discover_printers(self) -> Set[Printer]:
|
def _discover_printers(self) -> Set[Printer]:
|
||||||
"""
|
"""
|
||||||
@@ -98,10 +99,10 @@ class Printers:
|
|||||||
prid = dev.idProduct
|
prid = dev.idProduct
|
||||||
vendir = dev.idVendor
|
vendir = dev.idVendor
|
||||||
escpos_printer = EscPosPrinter(
|
escpos_printer = EscPosPrinter(
|
||||||
self.app,
|
app=self.app,
|
||||||
vendir,
|
vendor_id=vendir,
|
||||||
prid,
|
device_id=prid,
|
||||||
self.configuration_file["printer"]["epson"],
|
configuration_file=self.configuration_file["printer"]["epson"]
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise e
|
raise e
|
||||||
@@ -118,7 +119,7 @@ class Printers:
|
|||||||
self.app,
|
self.app,
|
||||||
dev.idVendor,
|
dev.idVendor,
|
||||||
dev.idProduct,
|
dev.idProduct,
|
||||||
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(
|
||||||
@@ -131,11 +132,12 @@ 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", manufacturer)
|
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.")
|
||||||
# end match
|
# end match
|
||||||
|
|
||||||
self.app.logger.debug("Found %s printers", len(printers))
|
self.app.logger.debug("Found %s printers", len(printers))
|
||||||
@@ -183,6 +185,8 @@ class Printers:
|
|||||||
|
|
||||||
return printers_info_list
|
return printers_info_list
|
||||||
|
|
||||||
|
def __len__(self):
|
||||||
|
return len(self.printers)
|
||||||
|
|
||||||
class _FindClass:
|
class _FindClass:
|
||||||
"""
|
"""
|
||||||
@@ -196,9 +200,6 @@ class _FindClass:
|
|||||||
|
|
||||||
def __call__(self, device):
|
def __call__(self, device):
|
||||||
# first, let's check the device
|
# first, let's check the device
|
||||||
self.app.logger.debug(
|
|
||||||
"Found a USB device of class %s", str(device.bDeviceClass)
|
|
||||||
)
|
|
||||||
if device.bDeviceClass == self._class:
|
if device.bDeviceClass == self._class:
|
||||||
return True
|
return True
|
||||||
# ok, transverse all devices to find an
|
# ok, transverse all devices to find an
|
||||||
|
|||||||
+1
-1
@@ -12,7 +12,7 @@ import os
|
|||||||
from time import sleep, gmtime, strftime
|
from time import sleep, gmtime, strftime
|
||||||
from gpiozero import Button, LED, DigitalOutputDevice
|
from gpiozero import Button, LED, DigitalOutputDevice
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
from task import TextTask, ImageTask, CutTask
|
from task import PrintTask
|
||||||
|
|
||||||
|
|
||||||
class Raspberry:
|
class Raspberry:
|
||||||
|
|||||||
+21
-17
@@ -33,6 +33,7 @@ class TaskType(Enum):
|
|||||||
IMAGE = "image"
|
IMAGE = "image"
|
||||||
CUT = "cut"
|
CUT = "cut"
|
||||||
QR = "qr"
|
QR = "qr"
|
||||||
|
REMOVE = "remove"
|
||||||
|
|
||||||
|
|
||||||
class PrintTask(ABC):
|
class PrintTask(ABC):
|
||||||
@@ -40,10 +41,12 @@ class PrintTask(ABC):
|
|||||||
A print task holds information about what we are looking to print.
|
A print task holds information about what we are looking to print.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, task_type: TaskType):
|
def __init__(self, task_type: TaskType, do_cut=False):
|
||||||
self.task_id = self._generate_id()
|
self.task_id = self._generate_id()
|
||||||
self.task_type = task_type
|
self.task_type = task_type
|
||||||
self.status = "pending" # pending, processing, completed, failed
|
self.status = "pending" # pending, processing, completed, failed
|
||||||
|
self.log = ""
|
||||||
|
self.do_cut = do_cut
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def get_print_data(self):
|
def get_print_data(self):
|
||||||
@@ -59,25 +62,25 @@ class TextTask(PrintTask):
|
|||||||
This tasks represents a texte content, and it's signature.
|
This tasks represents a texte content, and it's signature.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, content, signature):
|
def __init__(self, content, signature="", do_cut=False):
|
||||||
super().__init__(TaskType.TEXT)
|
super().__init__(TaskType.TEXT, do_cut)
|
||||||
self.content = content
|
self.content = content
|
||||||
self.signature = signature
|
self.signature = signature
|
||||||
|
|
||||||
def get_print_data(self):
|
def get_print_data(self):
|
||||||
return {"txt": self.content, "sign": self.signature}
|
return {"txt": self.content, "sign": self.signature, "do_cut": self.do_cut}
|
||||||
|
|
||||||
|
|
||||||
class QRTask(TextTask):
|
class QRTask(TextTask):
|
||||||
"""This task prints a QR-Code, the signature is ignore and is always the content itself"""
|
"""This task prints a QR-Code, the signature is ignore and is always the content itself"""
|
||||||
|
|
||||||
def __init__(self, content):
|
def __init__(self, content, do_cut):
|
||||||
super().__init__(content, signature="")
|
super().__init__(content, signature="", do_cut=False)
|
||||||
self.content = content
|
self.content = content
|
||||||
self.signature = content
|
self.signature = content
|
||||||
|
|
||||||
def get_print_data(self):
|
def get_print_data(self):
|
||||||
return {"txt": self.content, "sign": self.signature}
|
return {"txt": self.content, "sign": self.signature, "do_cut": self.do_cut}
|
||||||
|
|
||||||
|
|
||||||
class ImageTask(PrintTask):
|
class ImageTask(PrintTask):
|
||||||
@@ -85,8 +88,8 @@ class ImageTask(PrintTask):
|
|||||||
This tasks represents a image content ( in the form of it's path ), and it's signature.
|
This tasks represents a image content ( in the form of it's path ), and it's signature.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, image_path, signature, process, task_id):
|
def __init__(self, image_path, signature, process, task_id, do_cut):
|
||||||
super().__init__(TaskType.IMAGE)
|
super().__init__(TaskType.IMAGE, do_cut)
|
||||||
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
|
||||||
self.image_path = image_path
|
self.image_path = image_path
|
||||||
self.signature = signature
|
self.signature = signature
|
||||||
@@ -94,18 +97,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}
|
return {"img": self.image_path, "sign": self.signature, "process": self.process, "do_cut": self.do_cut}
|
||||||
|
|
||||||
|
class RemoveTask(PrintTask):
|
||||||
class CutTask(PrintTask):
|
|
||||||
"""
|
"""
|
||||||
This class activates the cutter on the printer if it exists
|
This class is used to clear images and leftovers after a print
|
||||||
"""
|
"""
|
||||||
|
def __init__(self, task_id, image_path):
|
||||||
def __init__(self):
|
super().__init__(TaskType.REMOVE)
|
||||||
super().__init__(TaskType.CUT)
|
self.task_id = self._generate_id() if not task_id else task_id
|
||||||
|
self.image_path = image_path
|
||||||
|
|
||||||
# There is no print data,
|
# There is no print data,
|
||||||
# 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 None
|
# Return image data in printer-compatible format
|
||||||
|
return {"img": self.image_path}
|
||||||
+7
-12
@@ -5,7 +5,7 @@ Manage all of the inputs from a web source
|
|||||||
import os
|
import os
|
||||||
from werkzeug.utils import secure_filename
|
from werkzeug.utils import secure_filename
|
||||||
import uuid
|
import uuid
|
||||||
from task import TextTask, ImageTask, CutTask
|
from task import TextTask, ImageTask
|
||||||
|
|
||||||
|
|
||||||
class Web:
|
class Web:
|
||||||
@@ -30,12 +30,9 @@ 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))
|
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", sms)
|
self.app.logger.info("Added a SMS task at position %s, it should %scut", sms, "" if not do_cut else "not ")
|
||||||
if do_cut:
|
self.app.logger.debug("%s", do_cut)
|
||||||
cut = self.print_queue.enqueue(CutTask())
|
|
||||||
self.app.logger.info("Added a CUT task at position %s", cut)
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.app.logger.error(e)
|
self.app.logger.error(e)
|
||||||
raise RuntimeError("Could not add SMS to queue, " + str(e)) from e
|
raise RuntimeError("Could not add SMS to queue, " + str(e)) from e
|
||||||
@@ -69,14 +66,12 @@ class Web:
|
|||||||
),
|
),
|
||||||
signature=sign,
|
signature=sign,
|
||||||
process=process_image,
|
process=process_image,
|
||||||
task_id=image_uuid
|
task_id=str(uuid.uuid4()),
|
||||||
|
do_cut=do_cut
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
self.app.logger.info("Added a IMG task at position %s", img)
|
self.app.logger.info("Added a IMG task at position %s, it should %s cut", img, "not " if not do_cut else "")
|
||||||
|
|
||||||
if do_cut:
|
|
||||||
cut = self.print_queue.enqueue(CutTask())
|
|
||||||
self.app.logger.info("Added a CUT task at position %s", cut)
|
|
||||||
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
|
||||||
|
|
||||||
|
|||||||
+30
-44
@@ -6,6 +6,9 @@ This is the main printing thread. A worker thread consums Tasks from
|
|||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
import traceback
|
import traceback
|
||||||
|
import random
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class PrintWorker(threading.Thread):
|
class PrintWorker(threading.Thread):
|
||||||
@@ -24,10 +27,9 @@ class PrintWorker(threading.Thread):
|
|||||||
super().__init__(daemon=True)
|
super().__init__(daemon=True)
|
||||||
self.app = app
|
self.app = app
|
||||||
self.print_queue = print_queue
|
self.print_queue = print_queue
|
||||||
self.printer = None
|
|
||||||
self._lock = threading.Lock()
|
|
||||||
self.running = True
|
self.running = True
|
||||||
self.state = "idle" # idle, printing, dead, drinking-a-beer
|
self.state = "idle" # idle, printing, dead, drinking-a-beer
|
||||||
|
self.id = str(uuid4())
|
||||||
|
|
||||||
# All workers share the same pool of printers.
|
# All workers share the same pool of printers.
|
||||||
self.printers = printers_pool
|
self.printers = printers_pool
|
||||||
@@ -35,14 +37,9 @@ class PrintWorker(threading.Thread):
|
|||||||
# If we create several workers, we can assign an index
|
# If we create several workers, we can assign an index
|
||||||
# so that we lookup the nth printer for the nth worker
|
# so that we lookup the nth printer for the nth worker
|
||||||
self._printer_index = printer_index
|
self._printer_index = printer_index
|
||||||
|
self.printer = self._acquire_available_printer()
|
||||||
|
|
||||||
self.app.logger.debug("Worker initialized.")
|
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("Printers connected:")
|
|
||||||
for printer in self.printers_obj:
|
|
||||||
self.app.logger.debug("Printer type: %s", printer.printer_type)
|
|
||||||
self.app.logger.debug("Printer state: %s", printer.ready)
|
|
||||||
|
|
||||||
self.app.logger.debug("Ho great, I'm alive... I'm ready to work another day...")
|
|
||||||
|
|
||||||
def _acquire_available_printer(self):
|
def _acquire_available_printer(self):
|
||||||
result = self.printers.acquire_available_printer(
|
result = self.printers.acquire_available_printer(
|
||||||
@@ -59,15 +56,13 @@ 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("Worker %s started working.", threading.get_ident())
|
self.app.logger.debug("\t[⚙ %s][%s] started working", self.id, threading.get_ident())
|
||||||
self.app.logger.debug("Current threads : %s", threading.active_count())
|
|
||||||
self.app.logger.debug("Threads actives : %s ", threading.enumerate())
|
|
||||||
|
|
||||||
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.
|
||||||
if not self.running:
|
if not self.running:
|
||||||
time.sleep(0.2)
|
self.app.logger.debug("\t[⚙ %s] Worker is asleep", self.id)
|
||||||
|
time.sleep(0.4)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# If we have no available printer, we look at the list printers
|
# If we have no available printer, we look at the list printers
|
||||||
@@ -77,39 +72,43 @@ class PrintWorker(threading.Thread):
|
|||||||
|
|
||||||
# If we do not have a printer, we try to find one
|
# If we do not have a printer, we try to find one
|
||||||
|
|
||||||
while self.running and self.printer is None:
|
if self.running and self.printer is None:
|
||||||
self.app.logger.debug(
|
self.app.logger.debug(
|
||||||
"Trying to find a available printer for the worker."
|
"\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(
|
||||||
"The worker got a %s printer and it's %s",
|
"\t[⚙ %s] Got a %s ( %s ) printer and it's %s", self.id ,
|
||||||
self.printer.printer_type,
|
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",
|
||||||
)
|
)
|
||||||
|
|
||||||
if self.printer is None:
|
if self.printer is None:
|
||||||
|
self.app.logger.debug("\t[⚙ %s] Could not get a printer ", self.id)
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
continue
|
||||||
|
|
||||||
self.printer.use_printer()
|
self.printer.use_printer()
|
||||||
|
|
||||||
# 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.
|
||||||
while not self.printer.ready:
|
if not self.printer.ready:
|
||||||
self.app.debug("Waiting for our printer to become ready...")
|
self.app.logger.debug("\t[⚙ %s] Waiting for our printer to become ready...", self.id)
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
continue
|
||||||
|
|
||||||
if self.state != "idle":
|
if self.state != "idle":
|
||||||
self.app.logger("We are not idle, waiting...")
|
self.app.logger("\t[⚙ %s] We are not idle, waiting...", self.id)
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
self.state = "printing"
|
self.state = "printing"
|
||||||
|
# self.app.logger.debug("\t[⚙ %s] Set the printer to printing state", self.id)
|
||||||
|
|
||||||
with self._lock:
|
|
||||||
try:
|
try:
|
||||||
|
# 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("Could not get a new task ! %s ", 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(
|
||||||
@@ -117,40 +116,30 @@ class PrintWorker(threading.Thread):
|
|||||||
) from e
|
) from e
|
||||||
|
|
||||||
if task:
|
if task:
|
||||||
try:
|
self.app.logger.debug("\t[⚙ %s] Got a new task %s %s", self.id, task.task_type, task.task_id)
|
||||||
self.app.logger.info("Got a new task")
|
|
||||||
self.app.logger.debug(
|
|
||||||
"Got task %s %s", task.task_type, task.task_id
|
|
||||||
)
|
|
||||||
task.status = "processing"
|
task.status = "processing"
|
||||||
|
|
||||||
print_data = task.get_print_data()
|
print_data = task.get_print_data()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self.printer.print_task(task.task_type, print_data)
|
self.printer.print_task(task, print_data)
|
||||||
except RuntimeError as e:
|
except RuntimeError as e:
|
||||||
self.state = "idle"
|
self.state = "idle"
|
||||||
self.app.logger.error("Could not print : %s", str(e))
|
self.app.logger.error("Could not print : %s", str(e))
|
||||||
|
self.print_queue.mark_completed(task.task_id, "failed", log=str(e))
|
||||||
self.app.logger.error(traceback.format_exc())
|
self.app.logger.error(traceback.format_exc())
|
||||||
self.printer.free_printer()
|
self.printer.free_printer()
|
||||||
|
|
||||||
task.status = "completed"
|
task.status = "completed"
|
||||||
self.print_queue.mark_completed(task.task_id, "completed")
|
self.print_queue.mark_completed(task.task_id, "completed")
|
||||||
self.app.logger.debug(
|
self.app.logger.debug(
|
||||||
"Finished printing task %s ", task.task_id
|
"\t[⚙ %s] Finished printing task %s ", self.id, task.task_id
|
||||||
)
|
)
|
||||||
self.state = "idle"
|
self.state = "idle"
|
||||||
|
|
||||||
except RuntimeError as e:
|
|
||||||
task.status = "failed"
|
|
||||||
self.state = "idle"
|
|
||||||
self.print_queue.mark_completed(task.task_id, "failed")
|
|
||||||
self.app.logger.error(
|
|
||||||
"Could not print task %s because %s ", task.task_id, str(e)
|
|
||||||
)
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# When they are no new tasks to handle, we put the thread to sleep.
|
# When they are no new tasks to handle, we put the thread to sleep.
|
||||||
|
# self.app.logger.debug("\t[⚙ %s] No new tasks in the queue, sleeping", self.id)
|
||||||
self.state = "idle"
|
self.state = "idle"
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
|
|
||||||
@@ -160,10 +149,6 @@ class PrintWorker(threading.Thread):
|
|||||||
"""
|
"""
|
||||||
self.app.logger.debug("Giving the worker a break")
|
self.app.logger.debug("Giving the worker a break")
|
||||||
self.state = "drinking-a-beer"
|
self.state = "drinking-a-beer"
|
||||||
# Free the printer during the worker break
|
|
||||||
# so it can be used by someone else
|
|
||||||
self.printer.free_printer()
|
|
||||||
self.printer = None
|
|
||||||
self.running = False
|
self.running = False
|
||||||
|
|
||||||
def start_worker(self):
|
def start_worker(self):
|
||||||
@@ -179,8 +164,9 @@ class PrintWorker(threading.Thread):
|
|||||||
Return the worker state
|
Return the worker state
|
||||||
"""
|
"""
|
||||||
return {
|
return {
|
||||||
|
"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,
|
||||||
"printers": len(self.printers_obj),
|
"printer": self.printer.printer_info.model if self.printer.printer_info.model else "No printer",
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user