feat: implement retry logic and increase connection timeout for kitchen printer network requests

This commit is contained in:
Suherdy Yacob 2026-05-12 10:27:41 +07:00
parent f82b09f0b7
commit 86ee02c030

View File

@ -10,23 +10,29 @@ def _isolated_printer_thread(ip, data):
Completely isolated printer thread.
Does not touch Odoo environment to avoid GIL/Locking issues.
"""
s = None
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 2 seconds is enough for a local network printer.
# Reducing from 5s to avoid holding resources too long.
s.settimeout(2.0)
s.connect((ip, 9100))
s.sendall(data)
_logger.info("POS_PRINTER: Successfully printed to %s", ip)
except Exception as e:
_logger.error("POS_PRINTER: Background print failed for IP %s: %s", ip, e)
finally:
if s:
try:
s.close()
except:
pass
max_retries = 3
timeout = 10.0
for attempt in range(max_retries):
s = None
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Increased timeout to 10s to handle slow networks or waking printers
s.settimeout(timeout)
s.connect((ip, 9100))
s.sendall(data)
_logger.info("POS_PRINTER: Successfully printed to %s (Attempt %d)", ip, attempt + 1)
return
except Exception as e:
if attempt < max_retries - 1:
_logger.warning("POS_PRINTER: Print attempt %d failed for IP %s: %s. Retrying...", attempt + 1, ip, e)
else:
_logger.error("POS_PRINTER: Background print failed for IP %s after %d attempts: %s", ip, max_retries, e)
finally:
if s:
try:
s.close()
except:
pass
class PosPrinter(models.Model):
_inherit = 'pos.printer'
@ -72,7 +78,7 @@ class PosPrinter(models.Model):
NEWLINE = b'\n'
data = INIT
data += ALIGN_CENTER + SIZE_DOUBLE + BOLD_ON
data += ALIGN_CENTER + SIZE_NORMAL + BOLD_ON
data += b"KITCHEN RECEIPT" + NEWLINE
data += SIZE_NORMAL + BOLD_OFF + NEWLINE