SocketCAN (python)

Python 3.3 added support for socketcan for linux systems.

The socketcan_native interface directly uses Python’s socket module to access SocketCAN on linux. This is the most direct route to the kernel and should provide the most responsive.

The implementation features efficient filtering of can_id’s, this filtering occurs in the kernel and is much much more efficient than filtering messages in Python.

Python 3.4 added support for the Broadcast Connection Manager (BCM) protocol, which if enabled should be used for queueing periodic tasks.

Documentation for the socket can backend file can be found:

https://www.kernel.org/doc/Documentation/networking/can.txt

Bus

class can.interfaces.socketcan_native.SocketcanNative_Bus(channel, **kwargs)[source]

Bases: can.bus.BusABC

Parameters:
  • channel (str) – The can interface name with which to create this bus. An example channel would be ‘vcan0’.
  • can_filters (list) – A list of dictionaries, each containing a “can_id” and a “can_mask”.

Internals

createSocket

can.interfaces.socketcan_native.createSocket(can_protocol=None)[source]

Creates a CAN socket. The socket can be BCM or RAW. The socket will be returned unbound to any interface.

Parameters:can_protocol (int) –
The protocol to use for the CAN socket, either:
  • socket.CAN_RAW
  • socket.CAN_BCM.
Returns:
  • -1 if socket creation unsuccessful
  • socketID - successful creation

bindSocket

can.interfaces.socketcan_native.bindSocket(sock, channel='can0')[source]

Binds the given socket to the given interface.

Parameters:socketID (Socket) – The ID of the socket to be bound
Raise:OSError if the specified interface isn’t found.

capturePacket

can.interfaces.socketcan_native.capturePacket(sock)[source]

Captures a packet of data from the given socket.

Parameters:sock (socket) – The socket to read a packet from.
Returns:A namedtuple with the following fields: * timestamp * arbitration_id * is_extended_frame_format * is_remote_transmission_request * is_error_frame * dlc * data