Skip to content

Commit

Permalink
cache link status method to reduce CPU time
Browse files Browse the repository at this point in the history
  • Loading branch information
janitza-bjag authored and mr-manuel committed Jan 21, 2025
1 parent df33f63 commit 04d6c40
Showing 1 changed file with 18 additions and 9 deletions.
27 changes: 18 additions & 9 deletions dbus-serialbattery/utils_can.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@ def __init__(self, channel, bustype):
self.daemon = True
self._running = True # flag to control the running state
self.can_bus = None
self.initial_interface_state = self.get_link_status(self.channel)
self.initial_interface_state = self.get_link_status
self.can_initialised = threading.Event()
self._link_status_cache = {"timestamp": 0, "result": None}

@classmethod
def get_instance(cls, channel, bustype) -> "CanReceiverThread":
Expand Down Expand Up @@ -66,7 +67,7 @@ def run(self) -> None:
self.can_initialised.set()

while self._running:
link_status = self.get_link_status(self.channel)
link_status = self.get_link_status
if link_status:
try:
message = self.can_bus.recv(timeout=1.0) # wait for max 1 second to receive message
Expand Down Expand Up @@ -132,19 +133,27 @@ def get_message_cache(self) -> dict:
# return a copy of the current cache
return dict(self.message_cache)

@staticmethod
def get_link_status(channel: str) -> bool:
def get_link_status(self) -> bool:
"""
Check if the CAN interface is up
:param channel: CAN interface name
:return: True if interface is up, False otherwise
"""
result = subprocess.run(["ip", "link", "show", channel], capture_output=True, text=True, check=True)
if "UP" in result.stdout:
return True
else:
return False

current_time = time.time()
# Check if cached result is still valid
if self._link_status_cache["timestamp"] + 1 > current_time:
return self._link_status_cache["result"]

result = subprocess.run(["ip", "link", "show", self.channel], capture_output=True, text=True, check=True)
status = "UP" in result.stdout

# Update the cache
self._link_status_cache["timestamp"] = current_time
self._link_status_cache["result"] = status

return status

@staticmethod
def get_bitrate(channel: str) -> int:
Expand Down

0 comments on commit 04d6c40

Please sign in to comment.