Skip to content

Commit

Permalink
Refactor fiscalberry service and enhance logging in ComandosHandler a…
Browse files Browse the repository at this point in the history
…nd EscPComandos
  • Loading branch information
alevilar committed Nov 7, 2024
1 parent 33cf451 commit ba890c4
Show file tree
Hide file tree
Showing 5 changed files with 28 additions and 21 deletions.
3 changes: 1 addition & 2 deletions fiscalberry.service
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ After=network.target network-online.target
Restart=always
RestartSec=5
Type=simple
ExecStart=/opt/fiscalberry/.venv/bin/python /opt/fiscalberry/src/cli.py
EnvironmentFile=/etc/fiscalberry/.env
ExecStart=/usr/bin/fiscalberry
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=fiscalberry
Expand Down
21 changes: 14 additions & 7 deletions src/common/ComandosHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,12 @@ def process_print_jobs():
jsonTicket, q = print_queue.get()
if jsonTicket is None:
break
runTraductor(jsonTicket, q)

try:
runTraductor(jsonTicket, q)
except Exception as e:
logging.error(f"Error al procesar el trabajo de impresión: {e}")

print_queue.task_done()

# Iniciar el hilo que procesa la cola de trabajos de impresión
Expand Down Expand Up @@ -128,7 +133,10 @@ def runTraductor(jsonTicket, queue):
raise DriverError(f"Invalid driver: {driver}")

comando = EscPComandos(driver)

logging.info(f"Imprimiendo en: {printerName}")
logging.info(f"Driver: {driverName}")
logging.info(f"DriverOps: {driverOps}")
logging.info(f"Comando:\n%s" % jsonTicket)
comando.run(jsonTicket)


Expand All @@ -139,18 +147,15 @@ class ComandosHandler:

def send_command(self, comando):
response = {}
logger.info(f"Tipo de dato de comando: {type(comando)}")
try:
if isinstance(comando, str):
logger.info("es un string??")
jsonMes = json.loads(comando, strict=False)
#si es un diccionario o json, no hacer nada
elif isinstance(comando, dict):
logger.info("es un diccionario??")
jsonMes = comando
#si es del typo class bytes, convertir a string y luego a json
elif isinstance(comando, bytes):
logger.info("es un bytes??")
jsonMes = json.loads(comando.decode("utf-8"), strict=False)
else:
raise TypeError("Tipo de dato no soportado")
Expand All @@ -173,7 +178,7 @@ def send_command(self, comando):
logger.exception(errtxt)
response["err"] = errtxt

logger.info("Response \n <- %s" % response)
logger.info("Command Response \n <- %s" % response)
return response

def __json_to_comando(self, jsonTicket):
Expand All @@ -188,6 +193,8 @@ def __json_to_comando(self, jsonTicket):
# seleccionar impresora
# esto se debe ejecutar antes que cualquier otro comando
if 'printerName' in jsonTicket:
logger.info("Imprimiendo en: \"%s\"" % jsonTicket.get('printerName'))

# run multiprocessing
q = Queue()
print_queue.put((jsonTicket, q))
Expand Down
19 changes: 8 additions & 11 deletions src/common/EscPComandos.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,6 @@ def printPedido(self, escpos: EscposIO, **kwargs):
encabezado = kwargs.get("encabezado", None)
items = kwargs.get("items", [])

if encabezado is None or len(items) == 0:
logger.error("No hay datos suficientes para imprimir")
return False

printer.set(font='a', height=1, align='center', normal_textsize=True)

Expand Down Expand Up @@ -208,7 +205,7 @@ def printFacturaElectronica(self, escpos: EscposIO, **kwargs):
setTrailer = kwargs.get("setTrailer", False)

if encabezado is None or len(items) == 0:
logger.error("No hay datos suficientes para imprimir")
logger.error("No hay datos en el encabezado para imprimir factura electronica")
return False


Expand Down Expand Up @@ -485,7 +482,7 @@ def printRemito(self, escpos: EscposIO, **kwargs):
setTrailer = kwargs.get("setTrailer", None)

if encabezado is None or len(items) == 0:
logger.error("No hay datos suficientes para imprimir")
logger.error("No hay datos en el encabezado para imprimir remito")
return False

printer.set(font='a', height=1, align='center')
Expand Down Expand Up @@ -677,7 +674,7 @@ def printComanda(self, escpos: EscposIO, comanda, setHeader=None, setTrailer=Non

def print_plato(plato):
"Imprimir platos"
printer.set(font='a', bold=True, height=2, width=2, align='left', double_height=True)
printer.set(font='a', bold=True, height=2, width=2, align='left', double_height=True, double_width=True)

printer.text(f"{plato['cant']}) {plato['nombre']}")

Expand All @@ -690,26 +687,26 @@ def print_plato(plato):
printer.text(f" OBS: {plato['observacion']}\n")

if 'observacion' in comanda:
printer.set(font='a', height=1, bold=True, align='center')
printer.set(font='a', bold=True, height=2, width=2, align='center', double_height=True, double_width=True)
printer.text(u"OBSERVACIÓN\n")
printer.text(comanda['observacion'])
printer.text("\n\n")

if 'entradas' in comanda:
printer.set(font='a', height=1, bold=True, align='center')
printer.set(font='a', bold=True, height=2, width=2, align='left', double_height=True, double_width=True)
printer.text(u"** ENTRADA **\n")
for entrada in comanda['entradas']:
print_plato(entrada)
printer.text("\n\n")

if 'platos' in comanda:
printer.set(font='a', height=2, bold=True, align='center')
printer.set(font='a', bold=True, height=2, width=2, align='left', double_height=True, double_width=True)
printer.text(u"----- PRINCIPAL -----\n")
for plato in comanda['platos']:
print_plato(plato)
printer.text("\n\n")

printer.set(font='a', height=2, width=2, align='center', bold=True)
printer.set(font='a', bold=True, height=2, width=2, align='left', double_height=True, double_width=True)
if self.__preFillTrailer:
self._setTrailer(escpos, self.__preFillTrailer)

Expand Down Expand Up @@ -739,7 +736,7 @@ def printArqueo(self, escpos: EscposIO, **kwargs):
encabezado: dict = kwargs.get('encabezado', None)

if encabezado is None:
logger.error("No hay datos suficientes para imprimir")
logger.error("No hay datos suficientes para imprimir: Encabezado es obligatorio")
return False

totalIngresosPorVenta = 0
Expand Down
4 changes: 4 additions & 0 deletions src/common/fiscalberry_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,15 @@
logging.basicConfig(level=logging.WARNING)


logging.getLogger("pika").setLevel(logging.WARNING)


try:
from kivy.logger import Logger
except ImportError:
import logging
Logger = logging.getLogger("** Fiscalberry ** ")



def getLogger():
Expand Down
2 changes: 1 addition & 1 deletion src/common/rabbit_mq_consumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def __init__(self, host, port, user, password, queue, vhost="/"):

def start(self):

print(f"Connecting to RabbitMQ server: {self.host}:{self.port} con user {self.user}")
print(f"Connecting to RabbitMQ server: {self.host}:{self.port}")
connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, port=self.port, virtual_host=self.vhost, credentials=pika.PlainCredentials(self.user, self.password)))
channel = connection.channel()

Expand Down

0 comments on commit ba890c4

Please sign in to comment.