Skip to content

Commit

Permalink
Improve logger class (#112)
Browse files Browse the repository at this point in the history
Co-authored-by: blakejameson <[email protected]>
Co-authored-by: Davit Babayan <[email protected]>
Co-authored-by: Michael Pham <[email protected]>
Co-authored-by: Nate Gay <[email protected]>
  • Loading branch information
5 people authored Jan 29, 2025
1 parent d1b983b commit ddb2f51
Show file tree
Hide file tree
Showing 11 changed files with 205 additions and 154 deletions.
2 changes: 0 additions & 2 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@
"Woah is that the Launcher Orbiter?????",
"Everything in life is a spring if you think hard enough!"
],

"debug": true,
"legacy": false,
"heating": false,
"orpheus":true,
Expand Down
8 changes: 3 additions & 5 deletions lib/pysquared/Big_Data.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@


class Face:
def __init__(self, Add, Pos, debug_state, tca, logger: Logger):
def __init__(self, Add, Pos, tca, logger: Logger):
self.tca = tca
self.address = Add
self.position = Pos
self.debug = debug_state
self.logger = logger

# Use tuple instead of list for immutable data
Expand Down Expand Up @@ -65,16 +64,15 @@ def Sensorinit(self, senlist, address):


class AllFaces:
def __init__(self, debug, tca, logger: Logger):
def __init__(self, tca, logger: Logger):
self.tca = tca
self.debug = debug
self.faces = []
self.logger = logger

# Create faces using a loop instead of individual variables
positions = [("y+", 0), ("y-", 1), ("x+", 2), ("x-", 3), ("z-", 4)]
for pos, addr in positions:
face = Face(addr, pos, debug, tca, self.logger)
face = Face(addr, pos, tca, self.logger)
face.Sensorinit(face.senlist, face.address)
self.faces.append(face)
gc.collect() # Clean up after each face initialization
Expand Down
3 changes: 1 addition & 2 deletions lib/pysquared/Field.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@


class Field:
def __init__(self, cubesat, debug, logger: Logger):
self.debug = debug
def __init__(self, cubesat, logger: Logger):
self.cubesat = cubesat
self.logger = logger

Expand Down
13 changes: 4 additions & 9 deletions lib/pysquared/battery_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ def __init__(self, pysquared, logger: Logger):
"""
self.uart = pysquared.uart
self.last_command_time = 0
self.debug_mode = True
self.logger = logger

def _flush_input(self):
Expand All @@ -54,8 +53,7 @@ def _wait_for_ack(self):
while (time.monotonic() - start) * 1000 < 10:
if self.uart.in_waiting:
byte = self.uart.read(1)
if self.debug_mode:
self.logger.info("ACK received", ack=byte)
self.logger.info("ACK received", ack=byte)
if byte == b"A":
return True
time.sleep(0.001)
Expand All @@ -82,8 +80,7 @@ def _read_message(self, timeout_ms=150):

try:
text = response.decode("utf-8")
if self.debug_mode:
self.logger.info("Read message", buffer=text)
self.logger.info("Read message", buffer=text)

# Check for complete message
if "AA<" in text and ">" in text:
Expand Down Expand Up @@ -156,11 +153,9 @@ def get_power_metrics(self):
)

except Exception as e:
if self.debug_mode:
self.logger.error("Error parsing metrics", err=e)
self.logger.error("Error parsing metrics", err=e)

if self.debug_mode:
self.logger.warning("Failed to get valid power metrics")
self.logger.warning("Failed to get valid power metrics")
return (0.0, 0.0, 0.0, 0.0, False, 0.0)

def get_error_metrics(self):
Expand Down
21 changes: 8 additions & 13 deletions lib/pysquared/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ def __init__(self, cubesat: Satellite, logger: Logger, config: Config) -> None:
self.logger = logger
self.cubesat: Satellite = cubesat
self.battery: BatteryHelper = BatteryHelper(cubesat, logger)
self.debug: bool = cubesat.debug
self.logger.info("Initializing Functionalities")

self.pm: PacketManager = PacketManager(logger=self.logger, max_packet_size=128)
Expand Down Expand Up @@ -100,7 +99,7 @@ def send(self, msg: Union[str, bytearray]) -> None:
"""
import lib.pysquared.Field as Field

self.field: Field.Field = Field.Field(self.cubesat, self.debug, self.logger)
self.field: Field.Field = Field.Field(self.cubesat, self.logger)
message: str = f"{self.callsign} " + str(msg) + f" {self.callsign}"
self.field.Beacon(message)
if self.cubesat.is_licensed:
Expand Down Expand Up @@ -128,7 +127,7 @@ def beacon(self) -> None:
lora_beacon: str = (
f"{self.callsign} Hello I am {self.cubesat_name}! I am: "
+ str(self.cubesat.power_mode)
+ f" UT:{self.cubesat.uptime} BN:{self.cubesat.boot_count.get()} EC:{self.cubesat.error_count.get()} "
+ f" UT:{self.cubesat.uptime} BN:{self.cubesat.boot_count.get()} EC:{self.logger.get_error_count()} "
+ f"IHBPFJASTMNE! {self.callsign}"
)
except Exception as e:
Expand All @@ -142,7 +141,7 @@ def beacon(self) -> None:
+ f". IHBPFJASTMNE! {self.callsign}"
)

self.field: Field.Field = Field.Field(self.cubesat, self.debug, self.logger)
self.field: Field.Field = Field.Field(self.cubesat, self.logger)
self.field.Beacon(lora_beacon)
del self.field
del Field
Expand Down Expand Up @@ -191,15 +190,15 @@ def state_of_health(self) -> None:
f"RT:{self.last_radio_temp()}",
f"AT:{self.cubesat.internal_temperature}",
f"BT:{self.last_battery_temp}",
f"EC:{self.cubesat.error_count.get()}",
f"EC:{self.logger.get_error_count()}",
f"AB:{int(self.cubesat.f_burned.get())}",
f"BO:{int(self.cubesat.f_brownout.get())}",
f"FK:{int(self.cubesat.f_fsk.get())}",
]
except Exception as e:
self.logger.error("Couldn't aquire data for the state of health: ", err=e)

self.field: Field.Field = Field.Field(self.cubesat, self.debug, self.logger)
self.field: Field.Field = Field.Field(self.cubesat, self.logger)
if not self.state_bool:
self.field.Beacon(
f"{self.callsign} Yearling^2 State of Health 1/2"
Expand All @@ -222,7 +221,7 @@ def send_face(self) -> None:
"""Calls the data transmit function from the field class"""
import lib.pysquared.Field as Field

self.field: Field.Field = Field.Field(self.cubesat, self.debug, self.logger)
self.field: Field.Field = Field.Field(self.cubesat, self.logger)
self.logger.debug("Sending Face Data")
self.field.Beacon(
f"{self.callsign} Y-: {self.facestring[0]} Y+: {self.facestring[1]} X-: {self.facestring[2]} X+: {self.facestring[3]} Z-: {self.facestring[4]} {self.callsign}"
Expand Down Expand Up @@ -295,9 +294,7 @@ def all_face_data(self) -> list:
)

gc.collect()
a: Big_Data.AllFaces = Big_Data.AllFaces(
self.debug, self.cubesat.tca, self.logger
)
a: Big_Data.AllFaces = Big_Data.AllFaces(self.cubesat.tca, self.logger)
self.logger.debug(
"Free Memory Stat after initializing All Faces object",
bytes_free=gc.mem_free(),
Expand Down Expand Up @@ -359,9 +356,7 @@ def detumble(self, dur: int = 7, margin: float = 0.2, seq: int = 118) -> None:
try:
import lib.pysquared.Big_Data as Big_Data

a: Big_Data.AllFaces = Big_Data.AllFaces(
self.debug, self.cubesat.tca, self.logger
)
a: Big_Data.AllFaces = Big_Data.AllFaces(self.cubesat.tca, self.logger)
except Exception as e:
self.logger.error("Error Importing Big Data", err=e)

Expand Down
41 changes: 32 additions & 9 deletions lib/pysquared/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,31 @@
import json
import time

from lib.pysquared.nvm.counter import Counter


class LogLevel:
NOTSET = 0
DEBUG = 1
INFO = 2
WARNING = 3
ERROR = 4
CRITICAL = 5


class Logger:
def __init__(self) -> None:
self.logToStandardOut: bool = True
def __init__(
self,
error_counter: Counter,
log_level: int = LogLevel.NOTSET,
) -> None:
self._error_counter: Counter = error_counter
self._log_level: int = log_level

def _log(self, level: str, message: str, **kwargs) -> None:
def _can_print_this_level(self, level_value: int) -> bool:
return level_value >= self._log_level

def _log(self, level: str, level_value: int, message: str, **kwargs) -> None:
"""
Log a message with a given severity level and any addional key/values.
"""
Expand All @@ -24,35 +43,39 @@ def _log(self, level: str, message: str, **kwargs) -> None:

json_output = json.dumps(kwargs)

if self.logToStandardOut:
if self._can_print_this_level(level_value):
print(json_output)

def debug(self, message: str, **kwargs) -> None:
"""
Log a message with severity level DEBUG.
"""
self._log("DEBUG", message, **kwargs)
self._log("DEBUG", 1, message, **kwargs)

def info(self, message: str, **kwargs) -> None:
"""
Log a message with severity level INFO.
"""
self._log("INFO", message, **kwargs)
self._log("INFO", 2, message, **kwargs)

def warning(self, message: str, **kwargs) -> None:
"""
Log a message with severity level WARNING.
"""
self._log("WARNING", message, **kwargs)
self._log("WARNING", 3, message, **kwargs)

def error(self, message: str, **kwargs) -> None:
"""
Log a message with severity level ERROR.
"""
self._log("ERROR", message, **kwargs)
self._error_counter.increment()
self._log("ERROR", 4, message, **kwargs)

def critical(self, message: str, **kwargs) -> None:
"""
Log a message with severity level CRITICAL.
"""
self._log("CRITICAL", message, **kwargs)
self._log("CRITICAL", 5, message, **kwargs)

def get_error_count(self) -> int:
return self._error_counter.get()
6 changes: 6 additions & 0 deletions lib/pysquared/nvm/register.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from micropython import const

# NVM register numbers
BOOTCNT = const(0)
ERRORCNT = const(7)
FLAG = const(16)
Loading

0 comments on commit ddb2f51

Please sign in to comment.