Compare commits

...

10 Commits
a ... main

Author SHA1 Message Date
537d3725d7 j 2025-04-08 10:35:26 -04:00
8c552af606 a 2025-04-08 10:33:46 -04:00
6b900ef16d j 2025-04-08 10:32:34 -04:00
d028ecb842 f 2025-04-08 10:29:26 -04:00
c51c95c42b a 2025-04-08 10:14:15 -04:00
00d737714b asdfasd 2025-04-07 17:54:54 -04:00
d06716ac92 FSGHDFG 2025-04-07 17:53:07 -04:00
a60cfae01c ASDFASDFAS 2025-04-07 17:50:44 -04:00
fe07e61505 asdf 2025-04-07 17:49:19 -04:00
357e47cc73 asdfdasfasd 2025-04-07 17:44:19 -04:00

67
app.py
View File

@ -4,7 +4,7 @@ import threading
import queue import queue
import pdf2image import pdf2image
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, status
from brother_ql.raster import BrotherQLRaster from brother_ql.raster import BrotherQLRaster
from PIL import Image from PIL import Image
import mimetypes import mimetypes
@ -16,12 +16,19 @@ app = Flask(__name__)
# Set up logging # Set up logging
log_file = 'log.txt' log_file = 'log.txt'
# Create a rotating file handler for logging
log_handler = RotatingFileHandler(log_file, maxBytes=10*1024*1024, backupCount=5) # 10MB per log file, keep 5 backups log_handler = RotatingFileHandler(log_file, maxBytes=10*1024*1024, backupCount=5) # 10MB per log file, keep 5 backups
log_handler.setLevel(logging.INFO) log_handler.setLevel(logging.DEBUG)
log_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') log_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
log_handler.setFormatter(log_formatter) log_handler.setFormatter(log_formatter)
# Add the log handler to the Flask app's logger
app.logger.addHandler(log_handler) app.logger.addHandler(log_handler)
# Ensure Flask app uses our logger, not its default one
app.logger.setLevel(logging.DEBUG)
# Create a queue to hold the files for processing # Create a queue to hold the files for processing
file_queue = queue.Queue() file_queue = queue.Queue()
@ -34,9 +41,6 @@ printer_model = "QL-1100"
backend = 'pyusb' backend = 'pyusb'
printer = 'usb://0x04f9:0x20a7' printer = 'usb://0x04f9:0x20a7'
# Create a lock to manage printer access
printer_lock = threading.Lock()
# Convert PDF to image # Convert PDF to image
def convert_pdf_to_image(pdf_path): def convert_pdf_to_image(pdf_path):
"""Converts a PDF to a PIL Image""" """Converts a PDF to a PIL Image"""
@ -50,19 +54,6 @@ def convert_pdf_to_image(pdf_path):
app.logger.error(f"Error converting PDF: {str(e)}") app.logger.error(f"Error converting PDF: {str(e)}")
return None return None
# Reinitialize the printer by disconnecting and reconnecting
def reinitialize_printer():
try:
app.logger.info("Reinitializing printer...")
usb_device = usb.core.find(idVendor=0x04f9, idProduct=0x20a7)
if usb_device:
usb_device.reset()
app.logger.info("Printer reinitialized successfully.")
else:
app.logger.error("Failed to find printer device.")
except Exception as e:
app.logger.error(f"Error reinitializing printer: {str(e)}")
# Function to print address labels # Function to print address labels
def print_address_label(pdf_path): def print_address_label(pdf_path):
try: try:
@ -71,6 +62,13 @@ def print_address_label(pdf_path):
if not image: if not image:
raise Exception("Failed to create label images") raise Exception("Failed to create label images")
if 'address' in pdf_path.lower():
target_width = 1660
target_height = 1164
image = image.convert("RGB")
image = image.resize((target_width, target_height), Image.LANCZOS)
image = image.rotate(90, expand=True)
else:
target_width = 1164 target_width = 1164
target_height = 1660 target_height = 1660
image = image.convert("RGB") image = image.convert("RGB")
@ -93,40 +91,18 @@ def print_address_label(pdf_path):
cut=True cut=True
) )
# Try to acquire the printer lock with a longer timeout app.logger.info("Sending to printer...")
max_retries = 5 # Retry up to 5 times status = send(
retry_delay = 5 # Retry every 5 seconds
for attempt in range(max_retries):
if printer_lock.acquire(timeout=30): # 30 seconds timeout to allow more time for the printer
try:
app.logger.info(f"Attempting to send print job (Attempt {attempt + 1})...")
send(
instructions=instructions, instructions=instructions,
printer_identifier=printer, printer_identifier=printer,
backend_identifier=backend, backend_identifier=backend,
blocking=True # Ensure blocking, so we wait for the print to complete blocking=True
) )
app.logger.info(f"Printer status: {status}")
app.logger.info("Print job sent successfully") app.logger.info("Print job sent successfully")
break
except Exception as e:
app.logger.error(f"Error during printing: {str(e)}")
if attempt < max_retries - 1:
app.logger.info(f"Retrying after {retry_delay} seconds...")
time.sleep(retry_delay)
else:
app.logger.error("Max retries reached. Failed to send print job.")
reinitialize_printer() # Reinitialize printer after retries
else:
app.logger.error(f"Failed to acquire printer lock (Attempt {attempt + 1}). Printer is busy.")
if attempt < max_retries - 1:
app.logger.info(f"Retrying after {retry_delay} seconds...")
time.sleep(retry_delay)
else:
app.logger.error("Printer is still busy after retries.")
raise Exception("Printer is busy. Try again later.")
except Exception as e: except Exception as e:
app.logger.error(f"Error during label printing: {str(e)}") app.logger.error(f"Error during printing: {str(e)}")
# Worker thread that processes files from the queue # Worker thread that processes files from the queue
def process_queue(): def process_queue():
@ -138,7 +114,6 @@ def process_queue():
# 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_address_label(file_path)
time.sleep(10)
# Signal that the task is done # Signal that the task is done
file_queue.task_done() file_queue.task_done()