Browse Source

backend: Add root_logger to request and respons

ble
Andreas Berthoud 4 years ago
parent
commit
4623dff665
  1. 4
      backend/monsun_backend/command_endpoint.py
  2. 14
      backend/monsun_backend/command_execution.py
  3. 41
      backend/monsun_backend/commands.py

4
backend/monsun_backend/command_endpoint.py

@ -29,7 +29,9 @@ def command(role: str):
command_id = get_command_id_from_name(cmd) command_id = get_command_id_from_name(cmd)
try: try:
command = get_request_class(command_id=command_id)(**arguments) command = get_request_class(command_id=command_id)(
root_logger=logging.getLogger(role), **arguments
)
except Exception: except Exception:
return Response(status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_400_BAD_REQUEST)

14
backend/monsun_backend/command_execution.py

@ -4,6 +4,7 @@ import time
from enum import Enum from enum import Enum
from multiprocessing import Process from multiprocessing import Process
from multiprocessing import Queue from multiprocessing import Queue
from struct import error
from struct import unpack from struct import unpack
from typing import Dict from typing import Dict
from typing import List from typing import List
@ -97,7 +98,11 @@ def enter_fsm(
while True: while True:
if state == State.heart_beat: if state == State.heart_beat:
if time.time() - heartbeat_interval > last_heart_beat_time: if time.time() - heartbeat_interval > last_heart_beat_time:
command_queue.put(commands.HeartbeatRequest()) command_queue.put(
commands.HeartbeatRequest(
root_logger=root_logger,
),
)
last_heart_beat_time = time.time() last_heart_beat_time = time.time()
state = State.executing_command state = State.executing_command
@ -213,6 +218,12 @@ def receive(
logger.debug(f"bytes: {bytes_read.hex()}") logger.debug(f"bytes: {bytes_read.hex()}")
try: try:
command_id_int, data_length, _ = unpack(">BHB", bytes_read[:header_size]) command_id_int, data_length, _ = unpack(">BHB", bytes_read[:header_size])
except error:
logger.error("error while interpreting command header")
bytes_read = None
continue
try:
payload = bytes(bytes_read[header_size : header_size + data_length]) payload = bytes(bytes_read[header_size : header_size + data_length])
stop_byte = bytes_read[header_size + data_length] stop_byte = bytes_read[header_size + data_length]
except IndexError: except IndexError:
@ -244,6 +255,7 @@ def receive(
if command_id == CommandId.command_log: if command_id == CommandId.command_log:
command = commands.LogCommand( command = commands.LogCommand(
root_logger=root_logger,
data=payload, data=payload,
) )
commands_received.append(command) commands_received.append(command)

41
backend/monsun_backend/commands.py

@ -77,8 +77,11 @@ class Response(abc.ABC):
class Command(abc.ABC): class Command(abc.ABC):
def __init__(self) -> None: def __init__(
self._logger = logging.getLogger(self.__class__.__name__) self,
root_logger: logging.Logger,
) -> None:
self._logger = root_logger.getChild(self.__class__.__name__)
@property @property
@abc.abstractmethod @abc.abstractmethod
@ -107,8 +110,11 @@ class Command(abc.ABC):
class Request(Command): class Request(Command):
def __init__(self) -> None: def __init__(
super().__init__() self,
root_logger: logging.Logger,
) -> None:
super().__init__(root_logger=root_logger)
self.response_identifier = randint(0, pow(2, 16) - 1) self.response_identifier = randint(0, pow(2, 16) - 1)
@ -144,9 +150,10 @@ class LogCommand(Command):
def __init__( def __init__(
self, self,
root_logger: logging.Logger,
data: bytes, data: bytes,
) -> None: ) -> None:
super().__init__() super().__init__(root_logger=root_logger)
self._logger.setLevel(logging.INFO) self._logger.setLevel(logging.INFO)
@ -160,7 +167,7 @@ class LogCommand(Command):
self._logger.debug("logger_name " + str(logger_name)) self._logger.debug("logger_name " + str(logger_name))
self._logger.debug("Message: " + str(message)) self._logger.debug("Message: " + str(message))
self.received_logger = logging.getLogger(logger_name.decode()) self.received_logger = root_logger.getChild(logger_name.decode())
self.received_logger.setLevel(logging.DEBUG) self.received_logger.setLevel(logging.DEBUG)
self.level = level self.level = level
self.message = message.decode() self.message = message.decode()
@ -215,15 +222,12 @@ class LEDResponse(Response):
data: bytes, data: bytes,
): ):
self.was_successful = bool(data[0]) self.was_successful = bool(data[0])
if self.was_successful:
self._logger.debug("LED command was successful")
else:
self._logger.debug("LED command was not successful")
class LEDRequest(Request): class LEDRequest(Request):
def __init__( def __init__(
self, self,
root_logger: logging.Logger,
id: Union[int, str], id: Union[int, str],
command: Union[int, str], command: Union[int, str],
) -> None: ) -> None:
@ -240,7 +244,7 @@ class LEDRequest(Request):
1: on 1: on
2: toggle 2: toggle
""" """
super().__init__() super().__init__(root_logger=root_logger)
try: try:
self.led_id = int(id) self.led_id = int(id)
except ValueError: except ValueError:
@ -270,6 +274,10 @@ class LEDRequest(Request):
def process_response(self, response: Response): def process_response(self, response: Response):
if not isinstance(response, LEDResponse): if not isinstance(response, LEDResponse):
raise TypeError(f"{response} is not a {LEDResponse}") raise TypeError(f"{response} is not a {LEDResponse}")
if response.was_successful:
self._logger.debug("LED command was successful")
else:
self._logger.debug("LED command was not successful")
def execute(self, serial: Serial): def execute(self, serial: Serial):
payload = pack( payload = pack(
@ -291,18 +299,15 @@ class GPResponse(Response):
data: bytes, data: bytes,
): ):
self.was_successful = bool(data[0]) self.was_successful = bool(data[0])
if self.was_successful:
self._logger.debug("GP command was successful")
else:
self._logger.debug("GP command was not successful")
class GPRequest(Request): class GPRequest(Request):
def __init__( def __init__(
self, self,
root_logger: logging.Logger,
command_id: Union[int, str], command_id: Union[int, str],
) -> None: ) -> None:
super().__init__() super().__init__(root_logger=root_logger)
self.command_id = int(command_id) self.command_id = int(command_id)
@property @property
@ -316,6 +321,10 @@ class GPRequest(Request):
def process_response(self, response: Response): def process_response(self, response: Response):
if not isinstance(response, GPResponse): if not isinstance(response, GPResponse):
raise TypeError(f"{response} is not a {GPResponse}") raise TypeError(f"{response} is not a {GPResponse}")
if response.was_successful:
self._logger.debug("GP command was successful")
else:
self._logger.debug("GP command was not successful")
def execute(self, serial: Serial): def execute(self, serial: Serial):
payload = pack( payload = pack(

Loading…
Cancel
Save