Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 39 additions & 22 deletions can/interfaces/socketcan/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import logging
import os
import struct
import sys
import re
import subprocess
from typing import List, Optional, cast

Expand Down Expand Up @@ -46,28 +48,43 @@ def find_available_interfaces() -> List[str]:

:return: The list of available and active CAN interfaces or an empty list of the command failed
"""

try:
command = ["ip", "-json", "link", "list", "up"]
output_str = subprocess.check_output(command, text=True)
except Exception: # pylint: disable=broad-except
# subprocess.CalledProcessError is too specific
log.exception("failed to fetch opened can devices from ip link")
return []

try:
output_json = json.loads(output_str)
except json.JSONDecodeError:
log.exception("Failed to parse ip link JSON output: %s", output_str)
return []

log.debug(
"find_available_interfaces(): detected these interfaces (before filtering): %s",
output_json,
)

interfaces = [i["ifname"] for i in output_json if i.get("link_type") == "can"]
return interfaces
if sys.platform == 'darwin':
try:
command = ["ifconfig", "-a"]
output_str = subprocess.check_output(command, text=True)
except Exception: # pylint: disable=broad-except
log.exception("failed to fetch opened can devices from ifconfig")
return []

try:
interfaces = re.findall(r'^(\w+):', output_str, re.MULTILINE)
can_interfaces = [iface for iface in interfaces if 'can' in iface]
return can_interfaces
except Exception:
log.exception("Failed to parse ifconfig output: %s", output_str)
return []
else:
try:
command = ["ip", "-json", "link", "list", "up"]
output_str = subprocess.check_output(command, text=True)
except Exception: # pylint: disable=broad-except
# subprocess.CalledProcessError is too specific
log.exception("failed to fetch opened can devices from ip link")
return []

try:
output_json = json.loads(output_str)
except json.JSONDecodeError:
log.exception("Failed to parse ip link JSON output: %s", output_str)
return []

log.debug(
"find_available_interfaces(): detected these interfaces (before filtering): %s",
output_json,
)

interfaces = [i["ifname"] for i in output_json if i.get("link_type") == "can"]
return interfaces


def error_code_to_str(code: Optional[int]) -> str:
Expand Down