Skip to content

Conversation

lumagi
Copy link
Collaborator

@lumagi lumagi commented Jan 6, 2023

Until now, the helper method to find locally available SocketCAN interfaces uses string manipulations to parse the ip link output. Additionally, it uses a regular expression to parse the interface name and determine which of these interfaces are CAN interfaces. As a result, it does not properly detect CAN interfaces with customized names (see #1475 ).

_PATTERN_CAN_INTERFACE = re.compile(r"(sl|v|vx)?can\d+")
def find_available_interfaces() -> Iterable[str]:
"""Returns the names of all open can/vcan interfaces using
the ``ip link list`` command. If the lookup fails, an error
is logged to the console and an empty list is returned.
"""
try:
# adding "type vcan" would exclude physical can devices
command = ["ip", "-o", "link", "list", "up"]
output = subprocess.check_output(command, text=True)
except Exception as e: # pylint: disable=broad-except
# subprocess.CalledProcessError is too specific
log.error("failed to fetch opened can devices: %s", e)
return []
else:
# log.debug("find_available_interfaces(): output=\n%s", output)
# output contains some lines like "1: vcan42: <NOARP,UP,LOWER_UP> ..."
# extract the "vcan42" of each line
interfaces = [line.split(": ", 3)[1] for line in output.splitlines()]
log.debug(
"find_available_interfaces(): detected these interfaces (before filtering): %s",
interfaces,
)
return filter(_PATTERN_CAN_INTERFACE.match, interfaces)

In #1475 , @1atabey1 proposed a more reliable approach to instead use the interface link_type for CAN interface detection. This pull request additionally uses the ip link (Changelog) JSON output option to make parsing the information easier.

JSON output has been available in ip link since version 4.14.0. All Debian / Ubuntu versions with the minimum supported Python version 3.7 also ship with an ip link version > 4.14.0.

@lumagi lumagi force-pushed the find_socketcan_if_json branch from 89b7370 to 3c5c611 Compare January 6, 2023 09:46
Copy link
Contributor

@1atabey1 1atabey1 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the nicer implementation, gave it a try and works for me as well!

Copy link
Collaborator

@zariiii9003 zariiii9003 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, thanks you both

@zariiii9003 zariiii9003 merged commit 15b8af0 into hardbyte:develop Jan 7, 2023
@zariiii9003 zariiii9003 added this to the Next Release milestone Jan 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants