Compare commits
5 Commits
9830917b1a
...
836d6b0be9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
836d6b0be9 | ||
|
|
8309399827 | ||
|
|
b50b9abc22 | ||
|
|
d0f4ba8f01 | ||
|
|
3fc41f806a |
@@ -1,11 +1,24 @@
|
||||
# Configuration file the LittlePrynter
|
||||
|
||||
[defaults]
|
||||
signature = "Anonymous"
|
||||
signature = ""
|
||||
|
||||
# Printer settings
|
||||
[printer]
|
||||
upload_folder = "src/static/uploads"
|
||||
# How long do we wait before giving up on waiting for a printer connexion
|
||||
waiting_time = 5
|
||||
|
||||
[printer.epson]
|
||||
# Configurations for EPSON printers
|
||||
profile = "TM-T20III"
|
||||
label_type = 80 # 80 or 58 ( label width in mm )
|
||||
align_text = "center"
|
||||
|
||||
[printer.brother]
|
||||
# Configurations for Brother printers
|
||||
label_type = "62" # See https://github.com/pklaus/brother_ql#usage for label types
|
||||
|
||||
|
||||
# Raspberry Pi Configuration
|
||||
[rpi]
|
||||
|
||||
@@ -5,8 +5,21 @@ signature = "Anonymous"
|
||||
|
||||
# Printer settings
|
||||
[printer]
|
||||
vendor_id = "0x04b8"
|
||||
device_id = "0x0e28"
|
||||
# Where do we upload the pictures and such
|
||||
upload_folder = "src/static/uploads"
|
||||
|
||||
# How long do we wait before giving up on waiting for a printer connexion
|
||||
waiting_time = 5
|
||||
|
||||
[printer.epson]
|
||||
# Configurations for EPSON printers
|
||||
profile = "TM-T20III"
|
||||
label_type = 80 # 80 or 58 ( label width in mm )
|
||||
align_text = "center"
|
||||
|
||||
[printer.brother]
|
||||
# Configurations for Brother printers
|
||||
label_type = 62 # See https://github.com/pklaus/brother_ql#usage for label types
|
||||
|
||||
# Raspberry Pi Configuration
|
||||
[rpi]
|
||||
|
||||
34
src/main.py
34
src/main.py
@@ -111,7 +111,7 @@ web = Web(app, print_queue)
|
||||
# Create a pool of printers
|
||||
try:
|
||||
# comment: Find all printers connected to the system
|
||||
printers_pool = Printers(app)
|
||||
printers_pool = Printers(app, configuration_file)
|
||||
except Exception as e:
|
||||
app.logger.error("Could not create a pool of printers because %s", str(e))
|
||||
sys.exit(-1)
|
||||
@@ -179,7 +179,13 @@ def web_print_sms():
|
||||
do_cut = False
|
||||
|
||||
try:
|
||||
web.print_sms(txt, sign, do_cut)
|
||||
# Clamp value between 1 and
|
||||
many = max(1, min(int(request.form["many"]), 20))
|
||||
except werkzeug.exceptions.BadRequestKeyError:
|
||||
many = 1
|
||||
|
||||
try:
|
||||
web.print_sms(txt, sign, do_cut, many)
|
||||
except RuntimeError as e:
|
||||
app.logger.error("Whoops, we could not print an SMS because : %s ", str(e))
|
||||
flash("Whoops, we could not print an SMS because :" + str(e), "error")
|
||||
@@ -233,9 +239,15 @@ def web_print_img():
|
||||
except werkzeug.exceptions.BadRequestKeyError:
|
||||
process_image = False
|
||||
|
||||
try:
|
||||
# Clamp value between 1 and
|
||||
many = max(1, min(int(request.form["many"]), 20))
|
||||
except werkzeug.exceptions.BadRequestKeyError:
|
||||
many = 1
|
||||
|
||||
try:
|
||||
app.logger.debug("Sending the image to the printer.")
|
||||
web.print_image(file, sign, do_cut, process_image)
|
||||
web.print_image(file, sign, do_cut, process_image, many)
|
||||
except RuntimeError as e:
|
||||
app.logger.error("The image could not be printed because : %s ", str(e))
|
||||
flash("The image could not be printed because : " + str(e), "error")
|
||||
@@ -286,9 +298,15 @@ def api_print_sms():
|
||||
except werkzeug.exceptions.BadRequestKeyError:
|
||||
do_cut = False
|
||||
|
||||
try:
|
||||
# Clamp value between 1 and
|
||||
many = max(1, min(int(request.form["many"]), 20))
|
||||
except werkzeug.exceptions.BadRequestKeyError:
|
||||
many = 1
|
||||
|
||||
try:
|
||||
# comment: We try to print the SMS
|
||||
web.print_sms(txt, sign, do_cut)
|
||||
web.print_sms(txt, sign, do_cut, many)
|
||||
except RuntimeError as e:
|
||||
return str(e), 500
|
||||
# end try
|
||||
@@ -331,9 +349,15 @@ def api_print_image():
|
||||
except werkzeug.exceptions.BadRequestKeyError:
|
||||
process_image = False
|
||||
|
||||
try:
|
||||
# Clamp value between 1 and
|
||||
many = max(1, min(int(request.form["many"]), 20))
|
||||
except werkzeug.exceptions.BadRequestKeyError:
|
||||
many = 1
|
||||
|
||||
try:
|
||||
app.logger.debug("Sending the image to the printer.")
|
||||
web.print_image(file, sign, do_cut, process_image)
|
||||
web.print_image(file, sign, do_cut, process_image, many)
|
||||
except RuntimeError as e:
|
||||
return str(e), 500
|
||||
|
||||
|
||||
154
src/printer.py
154
src/printer.py
@@ -107,7 +107,7 @@ class EscPosPrinter(Printer):
|
||||
Create a new ESC/POS based printer.
|
||||
"""
|
||||
|
||||
def __init__(self, app, vendor_id, device_id):
|
||||
def __init__(self, app, vendor_id, device_id, configuration_file):
|
||||
"""
|
||||
Create a connexion to a ESC/POS Printer via USB,
|
||||
Making sure the printer is alive,
|
||||
@@ -123,7 +123,7 @@ class EscPosPrinter(Printer):
|
||||
try:
|
||||
# This also calls open(), which we need to close()
|
||||
# or else the device will appear as busy.
|
||||
p = escpos.printer.Usb(self.vendor_id, self.device_id, 0, profile="TM-P80")
|
||||
p = escpos.printer.Usb(self.vendor_id, self.device_id, 0, profile=configuration_file["profile"])
|
||||
except escpos.exceptions.DeviceNotFoundError as e:
|
||||
self.app.logger.error(
|
||||
"The USB device is not plugged in : %s",
|
||||
@@ -140,9 +140,21 @@ class EscPosPrinter(Printer):
|
||||
except Exception as e:
|
||||
raise e
|
||||
|
||||
self.printer_info = PrinterInfo(
|
||||
identifier=configuration_file["profile"],
|
||||
backend="pyusb",
|
||||
model=configuration_file["profile"],
|
||||
protocol="ESC/POS",
|
||||
vendor_id=self.vendor_id,
|
||||
product_id=self.device_id,
|
||||
serial_number="",
|
||||
label_type=configuration_file["label_type"],
|
||||
)
|
||||
|
||||
# Setting up the printing options.
|
||||
# TODO : Expose this to the web interface
|
||||
p.set(
|
||||
align="center",
|
||||
align=configuration_file["align_text"],
|
||||
font="a",
|
||||
bold=False,
|
||||
underline=0,
|
||||
@@ -287,22 +299,22 @@ class EscPosPrinter(Printer):
|
||||
except Exception as e:
|
||||
self.app.logger.error(str(e))
|
||||
raise RuntimeError("Could not print the picture") from e
|
||||
finally:
|
||||
try:
|
||||
os.remove(path)
|
||||
os.remove(processed_path)
|
||||
self.app.logger.debug("Removed image : " + str(processed_path))
|
||||
self.app.logger.debug("Removed image : " + str(path))
|
||||
except OSError as e:
|
||||
raise e
|
||||
# finally:
|
||||
# try:
|
||||
# os.remove(path)
|
||||
# os.remove(processed_path)
|
||||
# self.app.logger.debug("Removed image : " + str(processed_path))
|
||||
# self.app.logger.debug("Removed image : " + str(path))
|
||||
# except OSError as e:
|
||||
# raise e
|
||||
|
||||
try:
|
||||
self.printer.close()
|
||||
except Exception as e:
|
||||
self.app.logger.error(
|
||||
"Could not close the printer connexion %s", str(e)
|
||||
)
|
||||
raise RuntimeError("Could not close the printer connexion. ") from e
|
||||
try:
|
||||
self.printer.close()
|
||||
except Exception as e:
|
||||
self.app.logger.error(
|
||||
"Could not close the printer connexion %s", str(e)
|
||||
)
|
||||
raise RuntimeError("Could not close the printer connexion. ") from e
|
||||
|
||||
self.app.logger.info("Printed a picture")
|
||||
self.ready = True
|
||||
@@ -391,7 +403,7 @@ class BrotherPrinter(Printer):
|
||||
Manages connexion and capabilities of a BrotherQL Printer
|
||||
"""
|
||||
|
||||
def __init__(self, app, vendor_id, device_id):
|
||||
def __init__(self, app, vendor_id, device_id, configuration_file):
|
||||
|
||||
super().__init__(app, vendor_id, device_id, printer_type=PrinterType.BROTHER)
|
||||
self.printer = None
|
||||
@@ -445,7 +457,7 @@ class BrotherPrinter(Printer):
|
||||
vendor_id=vendor_id,
|
||||
product_id=self.device_id,
|
||||
serial_number=serial_number,
|
||||
label_type="62",
|
||||
label_type=configuration_file["label_type"], # TODO: Implement automatic label type detection : https://framagit.org/stickoeur/diagnostickoeur/-/blob/no-masters/printit.py?ref_type=heads#L239
|
||||
)
|
||||
self.app.logger.debug("Created a Brother printer !")
|
||||
self.ready = True
|
||||
@@ -461,10 +473,11 @@ class BrotherPrinter(Printer):
|
||||
self._print_img(text_to_image(msg))
|
||||
self._print_img(text_to_image(signature))
|
||||
|
||||
def _print_img(self, data, signature="", process=False):
|
||||
def _print_img(self, data, signature="", process=False,):
|
||||
"""
|
||||
Print a raster image via a Brother QL printer
|
||||
"""
|
||||
self.app.logger.debug("Printing an image %s via Brother printer", data)
|
||||
if process:
|
||||
try:
|
||||
self.app.logger.debug("Proccessing the image")
|
||||
@@ -477,6 +490,7 @@ class BrotherPrinter(Printer):
|
||||
else:
|
||||
processed_path = data
|
||||
self.app.logger.warning("Not proccessing the image")
|
||||
|
||||
try:
|
||||
selected_backend = guess_backend(self.printer_info.identifier)
|
||||
BACKEND_CLASS = backend_factory(selected_backend)["backend_class"]
|
||||
@@ -490,39 +504,95 @@ class BrotherPrinter(Printer):
|
||||
try:
|
||||
im = Image.open(processed_path)
|
||||
qlr = BrotherQLRaster(self.printer_info.model)
|
||||
create_label(qlr, im, self.printer_info.label_type, cut=False, dither=True)
|
||||
# create_label(qlr, im, self.printer_info.label_type, cut=False, dither=True)
|
||||
|
||||
# noinspection PyCallingNonCallable
|
||||
be = BACKEND_CLASS(BACKEND_STRING_DESCR)
|
||||
be.write(qlr.data)
|
||||
be.dispose()
|
||||
del be
|
||||
# be = BACKEND_CLASS(BACKEND_STRING_DESCR)
|
||||
# be.write(qlr.data)
|
||||
# be.dispose()
|
||||
# del be
|
||||
|
||||
instructions = convert(
|
||||
qlr=qlr,
|
||||
images=[im],
|
||||
label=self.printer_info.label_type,
|
||||
dither=True,
|
||||
compress=False,
|
||||
dpi_600=False,
|
||||
cut=False,
|
||||
)
|
||||
|
||||
success = send(
|
||||
instructions=instructions,
|
||||
printer_identifier=BACKEND_STRING_DESCR,
|
||||
backend_identifier="pyusb",
|
||||
blocking=False
|
||||
)
|
||||
|
||||
self.app.logger.debug(str(success))
|
||||
self.app.logger.debug("Printed image")
|
||||
time.sleep(2)
|
||||
|
||||
except usb.core.USBError as e:
|
||||
if "timeout error" in str(e):
|
||||
self.app.logger.error("USB Timeout Error %s", str(e) )
|
||||
except Exception as e:
|
||||
raise e
|
||||
finally:
|
||||
try:
|
||||
os.remove(processed_path)
|
||||
self.app.logger.debug("Removed image : " + str(processed_path))
|
||||
except OSError as e:
|
||||
raise e
|
||||
# finally:
|
||||
# try:
|
||||
# os.remove(processed_path)
|
||||
# self.app.logger.debug("Removed image : " + str(processed_path))
|
||||
# except OSError as e:
|
||||
# raise e
|
||||
|
||||
if signature != "":
|
||||
self.app.logger.debug("Printing signature for the image %s", data)
|
||||
try:
|
||||
im = Image.open(text_to_image(signature))
|
||||
signature_file = text_to_image(signature)
|
||||
im = Image.open(signature_file)
|
||||
qlr = BrotherQLRaster(self.printer_info.model)
|
||||
create_label(
|
||||
qlr, im, self.printer_info.label_type, cut=False, dither=True
|
||||
)
|
||||
# create_label(
|
||||
# qlr, im, self.printer_info.label_type, cut=False, dither=True
|
||||
# )
|
||||
|
||||
# noinspection PyCallingNonCallable
|
||||
be = BACKEND_CLASS(BACKEND_STRING_DESCR)
|
||||
be.write(qlr.data)
|
||||
be.dispose()
|
||||
del be
|
||||
# be = BACKEND_CLASS(BACKEND_STRING_DESCR)
|
||||
# be.write(qlr.data)
|
||||
# be.dispose()
|
||||
# del be
|
||||
instructions = convert(
|
||||
qlr=qlr,
|
||||
images=[signature_file],
|
||||
label=self.printer_info.label_type,
|
||||
dither=True,
|
||||
compress=False,
|
||||
dpi_600=False,
|
||||
cut=False,
|
||||
)
|
||||
|
||||
|
||||
success = send(
|
||||
instructions=instructions,
|
||||
printer_identifier=BACKEND_STRING_DESCR,
|
||||
backend_identifier="pyusb",
|
||||
blocking=False
|
||||
)
|
||||
self.app.logger.debug(str(success))
|
||||
self.app.logger.debug("Printed signature")
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
except Exception as e:
|
||||
raise e
|
||||
finally:
|
||||
try:
|
||||
# os.remove(signature_file)
|
||||
self.app.logger.debug("Removed image : " + str(signature_file))
|
||||
except OSError as e:
|
||||
raise e
|
||||
|
||||
def _cut(self):
|
||||
self.app.logger.debug("Cutting via Brother Printer")
|
||||
try:
|
||||
selected_backend = guess_backend(self.printer_info.identifier)
|
||||
BACKEND_CLASS = backend_factory(selected_backend)["backend_class"]
|
||||
@@ -546,12 +616,14 @@ class BrotherPrinter(Printer):
|
||||
be.write(qlr.data)
|
||||
be.dispose()
|
||||
del be
|
||||
self.app.logger.debug("Finished cutting via Brother Printer")
|
||||
except Exception as e:
|
||||
raise e
|
||||
|
||||
|
||||
def _qr(self):
|
||||
# This should not be reached by a print on a BrotherQL
|
||||
raise NotImplementedError
|
||||
raise NotImplementedError()
|
||||
|
||||
def print_task(self, task_type, data):
|
||||
"""Execute actual print based on task type"""
|
||||
|
||||
@@ -18,11 +18,12 @@ class Printers:
|
||||
Finds and creates a set of Printer that can be used by the Workers to print.
|
||||
"""
|
||||
|
||||
def __init__(self, app):
|
||||
def __init__(self, app, configuration_file):
|
||||
"""
|
||||
Discovers printers connected to the computer
|
||||
"""
|
||||
self.app = app
|
||||
self.configuration_file = configuration_file
|
||||
self.printers = list(self._discover_printers())
|
||||
self._lock = threading.Lock()
|
||||
|
||||
@@ -42,8 +43,7 @@ class Printers:
|
||||
|
||||
printers = set()
|
||||
|
||||
# TODO : this could go in the config ?
|
||||
waiting_time_for_printer = 5
|
||||
waiting_time_for_printer = self.configuration_file["printer"]["waiting_time"]
|
||||
|
||||
while True:
|
||||
# Find all connected USB devices
|
||||
@@ -97,9 +97,7 @@ class Printers:
|
||||
self.app.logger.debug("Trying to create a new EPSON printer")
|
||||
prid = dev.idProduct
|
||||
vendir = dev.idVendor
|
||||
escpos_printer = EscPosPrinter(
|
||||
self.app, vendor_id=vendir, device_id=prid
|
||||
)
|
||||
escpos_printer = EscPosPrinter(self.app, vendir, prid, self.configuration_file["printer"]["epson"] )
|
||||
except Exception as e:
|
||||
raise e
|
||||
|
||||
@@ -111,9 +109,7 @@ class Printers:
|
||||
# We create a new BrotherPrinter()
|
||||
self.app.logger.debug("Trying to create a new BROTHER printer")
|
||||
|
||||
brother_printer = BrotherPrinter(
|
||||
self.app, vendor_id=dev.idVendor, device_id=dev.idProduct
|
||||
)
|
||||
brother_printer = BrotherPrinter(self.app, dev.idVendor, dev.idProduct, self.configuration_file["printer"]["brother"] )
|
||||
except Exception as e:
|
||||
self.app.logger.error(
|
||||
"Could not create a %s printer class with %s:%s",
|
||||
@@ -148,6 +144,8 @@ class Printers:
|
||||
return None
|
||||
|
||||
with self._lock:
|
||||
# So don't always look at the first printer available if need be
|
||||
# this allows for a round-robin lookup
|
||||
for offset in range(len(printers)):
|
||||
index = (start_index + offset) % len(printers)
|
||||
printer = printers[index]
|
||||
@@ -158,9 +156,11 @@ class Printers:
|
||||
|
||||
return None
|
||||
|
||||
def printers_info(self):
|
||||
"""Return the current list of printers"""
|
||||
return self.printers
|
||||
# def printers_info(self):
|
||||
# """Return the current list of printers"""
|
||||
# printers_info_list = {}
|
||||
# for i in self.printers
|
||||
# return self.printers
|
||||
|
||||
|
||||
class _FindClass:
|
||||
|
||||
@@ -9,14 +9,20 @@
|
||||
<textarea class="form-control" type="text" name="txt" placeholder="4096 caractères maximum " maxlength="4096"></textarea>
|
||||
<br>
|
||||
<input class="form-control" type="text" name="signature" placeholder="Signature ou pseudo" maxlength="200"><br>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text">Combien ?</span>
|
||||
<input type="number" aria-label="how-many" class="form-control" name="many" max="20" min="1" value="1">
|
||||
<input class="btn btn-primary float-right" type="submit" value="Imprimer" name="imprimer">
|
||||
</div>
|
||||
<br>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" value="True" id="flexCheckDefault" name="cut" checked>
|
||||
<label class="form-check-label" for="flexCheckDefault">
|
||||
Couper après impression ?
|
||||
</label>
|
||||
</div>
|
||||
<br>
|
||||
<input class="btn btn-primary float-right" type="submit" value="Imprimer" name="imprimer">
|
||||
|
||||
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
@@ -29,6 +35,12 @@
|
||||
<form enctype="multipart/form-data" class="form-group" action="/web/print/img" method="post">
|
||||
<input class="form-control" type="file" name="img" required><br>
|
||||
<input class="form-control" type="text" name="signature" placeholder="Signature ou pseudo" maxlength="200"><br>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text">Combien ?</span>
|
||||
<input type="number" aria-label="how-many" class="form-control" name="many" max="20" min="1" value="1">
|
||||
<input class="btn btn-primary float-right" type="submit" value="Imprimer" name="imprimer">
|
||||
</div>
|
||||
<br>
|
||||
<div class="form-check .form-check-inline">
|
||||
<input class="form-check-input" type="checkbox" value="True" id="flexCheckDefault" name="cut" checked>
|
||||
<label class="form-check-label" for="flexCheckDefault">
|
||||
@@ -41,8 +53,7 @@
|
||||
Traiter l'image ?
|
||||
</label>
|
||||
</div>
|
||||
<br>
|
||||
<input class="btn btn-primary float-right" type="submit" value="Imprimer" name="imprimer">
|
||||
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
42
src/web.py
42
src/web.py
@@ -16,7 +16,7 @@ class Web:
|
||||
self.print_queue = print_queue
|
||||
self.app = app
|
||||
|
||||
def print_sms(self, texte, sign: str, do_cut: bool) -> bool:
|
||||
def print_sms(self, texte, sign: str, do_cut: bool, many: int = 1) -> bool:
|
||||
"""
|
||||
Get text and a signature, prints the text and cuts after that.
|
||||
"""
|
||||
@@ -28,19 +28,20 @@ class Web:
|
||||
# !! there is no garantee !! that both the SMS task and the Cut task
|
||||
# are added back to back, another task could be
|
||||
# inserted between the two.
|
||||
sms = self.print_queue.enqueue(TextTask(content=texte, signature=sign))
|
||||
self.app.logger.info("Added a SMS task at position %s", sms)
|
||||
for i in range(many):
|
||||
sms = self.print_queue.enqueue(TextTask(content=texte, signature=sign))
|
||||
self.app.logger.info("Added a SMS task at position %s", sms)
|
||||
if do_cut:
|
||||
cut = self.print_queue.enqueue(CutTask())
|
||||
self.app.logger.info("Added a CUT task at position %s", cut)
|
||||
|
||||
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:
|
||||
self.app.logger.error(e)
|
||||
raise RuntimeError("Could not add SMS to queue, " + str(e)) from e
|
||||
|
||||
return True
|
||||
|
||||
def print_image(self, image, sign: str, do_cut: bool, process_image: bool) -> bool:
|
||||
def print_image(self, image, sign: str, do_cut: bool, process_image: bool, many: int = 1) -> bool:
|
||||
"""
|
||||
Get an image and a signature, prints the image and cuts after that.
|
||||
"""
|
||||
@@ -53,21 +54,22 @@ class Web:
|
||||
if file_uploaded:
|
||||
self.app.logger.debug("File has been uploaded, printing...")
|
||||
try:
|
||||
img = self.print_queue.enqueue(
|
||||
ImageTask(
|
||||
os.path.join(
|
||||
self.app.config["UPLOAD_FOLDER"],
|
||||
secure_filename(image.filename),
|
||||
),
|
||||
signature=sign,
|
||||
process=process_image,
|
||||
for i in range(many):
|
||||
img = self.print_queue.enqueue(
|
||||
ImageTask(
|
||||
os.path.join(
|
||||
self.app.config["UPLOAD_FOLDER"],
|
||||
secure_filename(image.filename),
|
||||
),
|
||||
signature=sign,
|
||||
process=process_image,
|
||||
)
|
||||
)
|
||||
)
|
||||
self.app.logger.info("Added a IMG task at position %s", img)
|
||||
self.app.logger.info("Added a IMG task at position %s", img)
|
||||
|
||||
if do_cut:
|
||||
cut = self.print_queue.enqueue(CutTask())
|
||||
self.app.logger.info("Added a CUT task at position %s", cut)
|
||||
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:
|
||||
raise RuntimeError("Could not add IMG to queue" + str(e)) from e
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ This is the main printing thread. A worker thread consums Tasks from
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from printers import Printers
|
||||
|
||||
|
||||
class PrintWorker(threading.Thread):
|
||||
@@ -21,7 +20,7 @@ class PrintWorker(threading.Thread):
|
||||
tasks. TODO : Change that
|
||||
"""
|
||||
|
||||
def __init__(self, app, print_queue, printers_pool):
|
||||
def __init__(self, app, print_queue, printers_pool, printer_index=0):
|
||||
super().__init__(daemon=True)
|
||||
self.app = app
|
||||
self.print_queue = print_queue
|
||||
@@ -33,7 +32,9 @@ class PrintWorker(threading.Thread):
|
||||
# All workers share the same pool of printers.
|
||||
self.printers = printers_pool
|
||||
self.printers_obj = self.printers.printers
|
||||
self._printer_index = 0
|
||||
# If we create several workers, we can assign an index
|
||||
# so that we lookup the nth printer for the nth worker
|
||||
self._printer_index = printer_index
|
||||
|
||||
self.app.logger.debug("Worker initialized.")
|
||||
self.app.logger.debug("Printers connected:")
|
||||
@@ -44,11 +45,13 @@ class PrintWorker(threading.Thread):
|
||||
self.app.logger.debug("Ho great, I'm alive... I'm ready to work another day...")
|
||||
|
||||
def _acquire_available_printer(self):
|
||||
result = self.printers.acquire_available_printer(self._printer_index)
|
||||
result = self.printers.acquire_available_printer(start_index=self._printer_index)
|
||||
if result is None:
|
||||
return None
|
||||
|
||||
index, printer = result
|
||||
# In case we need to lookup another printer, we don't
|
||||
# look at the same printer in the printer list
|
||||
self._printer_index = (index + 1) % len(self.printers_obj)
|
||||
return printer
|
||||
|
||||
@@ -78,14 +81,17 @@ class PrintWorker(threading.Thread):
|
||||
)
|
||||
self.printer = self._acquire_available_printer()
|
||||
self.app.logger.debug(
|
||||
"The worker got a %s printer and it's %s",
|
||||
self.printer.printer_type,
|
||||
"Ready" if self.printer.ready else "Not ready",
|
||||
|
||||
"The worker got a %s printer and it's %s",
|
||||
self.printer.printer_type,
|
||||
"Ready" if self.printer.ready else "Not ready",
|
||||
)
|
||||
|
||||
if self.printer is None:
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
|
||||
self.printer.use_printer()
|
||||
|
||||
# If the printer is not ready, we wait for it to become ready.
|
||||
@@ -128,7 +134,6 @@ class PrintWorker(threading.Thread):
|
||||
self.app.logger.error("Could not print : %s", str(e))
|
||||
self.app.logger.error(traceback.format_exc())
|
||||
self.printer.free_printer()
|
||||
raise e
|
||||
|
||||
task.status = "completed"
|
||||
self.print_queue.mark_completed(task.task_id, "completed")
|
||||
@@ -156,7 +161,10 @@ class PrintWorker(threading.Thread):
|
||||
"""
|
||||
self.app.logger.debug("Giving the worker a break")
|
||||
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
|
||||
|
||||
def start_worker(self):
|
||||
|
||||
Reference in New Issue
Block a user