This commit is contained in:
zman 2025-04-07 17:53:07 -04:00
parent a60cfae01c
commit d06716ac92

43
app.py
View File

@ -11,6 +11,7 @@ import mimetypes
import logging import logging
from logging.handlers import RotatingFileHandler from logging.handlers import RotatingFileHandler
import time import time
import fcntl # For file locking
app = Flask(__name__) app = Flask(__name__)
@ -48,7 +49,7 @@ def convert_pdf_to_image(pdf_path):
return None return None
# Function to print address labels # Function to print address labels
def print_address_label(pdf_path, print_complete_event): def print_address_label(pdf_path):
try: try:
# Convert PDF to image # Convert PDF to image
image = convert_pdf_to_image(pdf_path) image = convert_pdf_to_image(pdf_path)
@ -84,22 +85,27 @@ def print_address_label(pdf_path, print_complete_event):
cut=True cut=True
) )
app.logger.info("Sending to printer...") app.logger.info("Attempting to acquire printer lock...")
send(
instructions=instructions, # Open the printer device and lock it to prevent concurrent access
printer_identifier=printer, with open(printer, 'wb') as printer_device:
backend_identifier=backend, fcntl.flock(printer_device, fcntl.LOCK_EX) # Exclusive lock on printer device
blocking=True try:
) app.logger.info("Sending to printer...")
app.logger.info("Print job sent successfully") send(
instructions=instructions,
printer_identifier=printer,
backend_identifier=backend,
blocking=True
)
app.logger.info("Print job sent successfully")
finally:
# Ensure the lock is released after the print job is finished
fcntl.flock(printer_device, fcntl.LOCK_UN)
except Exception as e: except Exception as e:
app.logger.error(f"Error during printing: {str(e)}") app.logger.error(f"Error during printing: {str(e)}")
finally:
# Signal that the current print job is done
print_complete_event.set()
# Worker thread that processes files from the queue # Worker thread that processes files from the queue
def process_queue(): def process_queue():
while True: while True:
@ -107,17 +113,10 @@ def process_queue():
file_path = file_queue.get() file_path = file_queue.get()
if file_path is None: # Shutdown signal if file_path is None: # Shutdown signal
break break
# Create an event to signal print job completion
print_complete_event = threading.Event()
# Process the file (convert and print) # Process the file (convert and print)
app.logger.info(f"Processing file: {file_path}") app.logger.info(f"Processing file: {file_path}")
print_address_label(file_path, print_complete_event) print_address_label(file_path)
time.sleep(10)
# Wait until the current print job is completed before processing the next one
print_complete_event.wait()
# Signal that the task is done # Signal that the task is done
file_queue.task_done() file_queue.task_done()