From 04d6c407af561b5a0fc9cc24ada15677d59582db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Agel?= Date: Tue, 21 Jan 2025 18:28:00 +0100 Subject: [PATCH] cache link status method to reduce CPU time --- dbus-serialbattery/utils_can.py | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/dbus-serialbattery/utils_can.py b/dbus-serialbattery/utils_can.py index 0b2ef1e..505b98c 100644 --- a/dbus-serialbattery/utils_can.py +++ b/dbus-serialbattery/utils_can.py @@ -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": @@ -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 @@ -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: