Skip to content

Core Concepts of Sockcan

Sockcan is built around a few fundamental concepts that enable its high performance, flexibility, and python-can compatibility. Understanding these concepts is key to effectively using the library.

1. SocketCAN-alike Protocol

At its heart, Sockcan implements a protocol that mimics the Linux SocketCAN interface. This allows it to interact with CAN devices in a standardized way, even on platforms that don't natively support SocketCAN.

Key Components

  • CanMessage: A dataclass that serves as a container for CAN message data. It includes arbitration_id, data, is_extended_id, and timestamp, closely matching python-can's Message object for compatibility.
  • SocketcanConfig: A dataclass used to configure the SocketCAN connection, including the channel (e.g., 'can0') and loopback mode.

2. Loopback Modes

Sockcan provides different loopback modes to control whether transmitted messages are also received by the sending socket or by other sockets on the same CAN device.

LoopbackMode Enum

  • OFF: Transmitted messages are not received by any socket (including the sender).
  • FOR_OTHER_SOCKS: (Default) Transmitted messages are received by other sockets connected to the same CAN device but not by the sender.
  • ON: Transmitted messages are received by the sending socket itself, as well as other connected sockets.

3. Message Sending and Receiving Functions

Sockcan provides flexible functions to build send and receive operations, allowing for optimized message handling.

connect_to_socketcan(config: SocketcanConfig) -> SocketcanFd

This function creates and configures a socket.socket object based on the provided SocketcanConfig, returning a SocketcanFd ready for use.

build_recv_func(fd: SocketcanFd, *, use_native_timestamps: bool = True, is_stream: bool = False) -> RecvFn

This factory function constructs a receive function (RecvFn) for a given SocketcanFd. It can be configured to use native hardware timestamps (if available and use_native_timestamps is True) and to operate in a stream-like manner (is_stream). The returned RecvFn is a callable that, when invoked, returns a CanMessage.

build_send_func(fd: SocketcanFd, *, expects_msg_cls: bool = False) -> SendFn | MessageSendFn

This factory function creates a send function (SendFn or MessageSendFn) for a SocketcanFd. If expects_msg_cls is True, the returned function expects a CanMessageProtocol object; otherwise, it expects individual arbitration_id, data, and is_extended parameters.