perf: offload network printer socket communication to background thread to prevent POS blocking
This commit is contained in:
parent
035dfe3dab
commit
9248f9b7c8
@ -1,5 +1,6 @@
|
||||
import socket
|
||||
import logging
|
||||
import threading
|
||||
from odoo import models, fields, api, _
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
@ -28,19 +29,24 @@ class PosPrinter(models.Model):
|
||||
def print_network_kitchen_receipt(self, printer_id, receipt_data):
|
||||
"""
|
||||
Receives structural receipt_data from POS frontend and sends ESC/POS string to network printer.
|
||||
receipt_data expected format:
|
||||
{
|
||||
'order_name': 'Order 0001',
|
||||
'order_time': '2023-10-01 12:00:00',
|
||||
'lines': [ { 'name': 'Burger', 'qty': 1, 'note': 'No onions' } ],
|
||||
'waiter': 'Mitchell Admin',
|
||||
'table': 'T1'
|
||||
}
|
||||
Optimized to use background threading to prevent blocking the POS transaction/RPC.
|
||||
"""
|
||||
printer = self.browse(printer_id)
|
||||
if not printer or not printer.network_printer_ip:
|
||||
return {'successful': False, 'message': 'Printer IP not configured'}
|
||||
|
||||
# Start printing in a background thread to avoid POS timeout
|
||||
# We don't need a new cursor here as we've already browsed the printer
|
||||
# and we don't write to the database in the thread.
|
||||
thread = threading.Thread(target=self._threaded_print, args=(printer.network_printer_ip, receipt_data))
|
||||
thread.daemon = True # Ensure thread doesn't block server shutdown
|
||||
thread.start()
|
||||
|
||||
return {'successful': True, 'message': 'Print job sent to background queue'}
|
||||
|
||||
def _threaded_print(self, ip, receipt_data):
|
||||
"""Perform the actual socket communication in the background."""
|
||||
try:
|
||||
# Build basic ESC/POS commands
|
||||
ESC = b'\x1b'
|
||||
GS = b'\x1d'
|
||||
@ -87,13 +93,11 @@ class PosPrinter(models.Model):
|
||||
data += b"-" * 32 + NEWLINE + NEWLINE + NEWLINE + CUT
|
||||
|
||||
# Send to printer
|
||||
try:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.settimeout(3.0)
|
||||
s.connect((printer.network_printer_ip, 9100))
|
||||
s.settimeout(5.0) # Slightly longer timeout for background print
|
||||
s.connect((ip, 9100))
|
||||
s.sendall(data)
|
||||
s.close()
|
||||
return {'successful': True}
|
||||
_logger.info("Successfully printed to kitchen printer at %s", ip)
|
||||
except Exception as e:
|
||||
_logger.error("Failed to print to network ESC/POS printer %s: %s", printer.network_printer_ip, e)
|
||||
return {'successful': False, 'message': str(e)}
|
||||
_logger.error("Background kitchen print failed for IP %s: %s", ip, e)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user