Skip to content

Commit

Permalink
Refactor server startup and configuration
Browse files Browse the repository at this point in the history
This commit refactors the server startup and configuration in the `cli.py` file. It removes unnecessary imports and logging configurations. The server now starts three services in separate threads: RabbitMQ, SocketIO, and discovery. The `start_services` function is introduced to handle the initialization of these services. Additionally, error handling is added to catch any exceptions that may occur during the startup process.
  • Loading branch information
alevilar committed Sep 20, 2024
1 parent 6eec9d9 commit 8a6d8eb
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 44 deletions.
79 changes: 50 additions & 29 deletions src/cli.py
Original file line number Diff line number Diff line change
@@ -1,53 +1,74 @@
#!/usr/bin/env python3
import time
import os
import logging

from common.Configberry import Configberry

configberry = Configberry()

environment = configberry.config.get("SERVIDOR", "environment", fallback="production")

# configuro logger segun ambiente
if environment == 'development':
print("* * * * * Modo de desarrollo * * * * *")
logging.basicConfig(level=logging.DEBUG)
else:
print("@ @ @ @ @ Modo de producción @ @ @ @ @")
logging.basicConfig(level=logging.WARNING)

import os, asyncio
import threading

from common.fiscalberry_logger import getLogger
logger = getLogger()


from common.Configberry import Configberry
configberry = Configberry()


# importo el modulo que se encarga de la comunicacion con el servidor
from common.rabbit_mq_consumer import RabbitMQConsumer
from common.discover import send_discover_in_thread
import asyncio


def startRabbit():
from common.rabbit_mq_consumer import RabbitMQConsumer

def start():
logger.info("Iniciando Fiscalberry Server")

uuid = configberry.config.get("SERVIDOR", "uuid")
host = configberry.config.get("RabbitMq", "host", fallback="localhost")
port = configberry.config.get("RabbitMq", "port", fallback="5672")
user = configberry.config.get("RabbitMq", "user", fallback="guest")
password = configberry.config.get("RabbitMq", "password", fallback="guest")
#send_discover_in_thread()

rb = RabbitMQConsumer(host, port, user, password, uuid)
# Inside the while loop
rb.start()
logger.warning("Termino ejecucion de server socketio?.. reconectando en 5s")


def startSocketio():
from common.fiscalberry_sio import FiscalberrySio
serverUrl = configberry.config.get("SERVIDOR", "sio_host", fallback="")
uuid = configberry.config.get("SERVIDOR", "uuid")
sio = FiscalberrySio(serverUrl, uuid)
sio.start_print_server()
logger.warning("Termino ejecucion de server socketio?.. reconectando en 5s")


def discover():
send_discover_in_thread()
logger.info("Discover enviado")


while True:
def start_services():
logger.info("Iniciando Fiscalberry Server")

# iniciar en 3 threads distintos los servicios
discover_thread = threading.Thread(target=discover)
socketio_thread = threading.Thread(target=startSocketio)
rabbit_thread = threading.Thread(target=startRabbit)

discover_thread.start()
socketio_thread.start()
rabbit_thread.start()

sio = RabbitMQConsumer(host, port, user, password, uuid)
# Inside the while loop
sio.start()
logger.warning("Termino ejecucion de server socketio?.. reconectando en 5s")
time.sleep(5)
discover_thread.join()
socketio_thread.join()
rabbit_thread.join()


if __name__ == "__main__":
start()


try:
start_services()
except Exception as e:
logger.error(f"Error occurred: {e}")
os._exit(1)


9 changes: 0 additions & 9 deletions src/common/Configberry.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
import os
import uuid
import platformdirs
from common.fiscalberry_logger import getLogger
import logging


appname = 'Fiscalberry'
Expand All @@ -26,7 +24,6 @@ def __init__(self):
if not hasattr(self, 'initialized'):
self.initialized = True
# Inicializa aquí los atributos de la instancia
self.logger = getLogger()

self.config.read( self.getConfigFIle() )
self.__create_config_if_not_exists()
Expand Down Expand Up @@ -65,9 +62,7 @@ def findByMac(self, mac):
for s in self.sections()[1:]:
if self.config.has_option(s, 'mac'):
mymac = self.config.get(s, 'mac')
self.logger.debug("mymac %s y la otra es mac %s" % (mymac, mac))
if mymac == mac:
self.logger.debug("encontre la mac %s" % mac)
return (s, self.get_config_for_printer(s))
return False

Expand Down Expand Up @@ -104,11 +99,7 @@ def writeSectionWithKwargs(self, section, kwargs):
return 1

def __create_config_if_not_exists(self):
#show info only once
self.logger = logging.getLogger("Configberry")

# read config file and list all sections
self.logger.debug("Config Sections: %s" % self.sections())
# menos el primero que es el de SERVIDOR, mostrar el el resto en consola ya que son las impresoras
for s in self.sections()[1:]:
print("Impresora en Config: %s" % s)
Expand Down
17 changes: 17 additions & 0 deletions src/common/fiscalberry_logger.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,21 @@
import os
import logging

from common.Configberry import Configberry

configberry = Configberry()

environment = configberry.config.get("SERVIDOR", "environment", fallback="production")


# configuro logger segun ambiente
if environment == 'development':
print("* * * * * Modo de desarrollo * * * * *")
logging.basicConfig(level=logging.DEBUG)
else:
print("@ @ @ @ @ Modo de producción @ @ @ @ @")
logging.basicConfig(level=logging.WARNING)


try:
from kivy.logger import Logger
Expand Down
6 changes: 0 additions & 6 deletions src/common/fiscalberry_sio.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,6 @@ def __run(self):


def start_print_server(self):
@self.sio.on('command', namespace='/paxaprinter')
def handle_command(data):
logger.debug(f"message received with {data}")
comandoHandler = ComandosHandler()
return comandoHandler.send_command(data)

self.__run()


Expand Down
2 changes: 2 additions & 0 deletions src/common/rabbit_mq_consumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ def __init__(self, host, port, user, password, uuid):

def start(self):


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

Expand Down

0 comments on commit 8a6d8eb

Please sign in to comment.