Bus

The Bus class, as the name suggests, provides an abstraction of a CAN bus. The bus provides a wrapper around a physical or virtual CAN Bus.

Filtering

Message filtering can be set up for each bus. Where the interface supports it, this is carried out in the hardware or kernel layer - not in Python.

API

class can.BusABC(channel=None, can_filters=None, **config)

CAN Bus Abstract Base Class

Concrete implementations must implement the following methods:
  • send
  • recv

As well as setting the channel_info attribute to a string describing the interface.

__iter__()

Allow iteration on messages as they are received.

>>> for msg in bus:
...     print(msg)
Yields:can.Message msg objects.
channel_info = 'unknown'

a string describing the underlying bus channel

flush_tx_buffer()

Used for CAN interfaces which need to flush their transmit buffer.

recv(timeout=None)

Block waiting for a message from the Bus.

Parameters:timeout (float) – Seconds to wait for a message.
Returns:None on timeout or a can.Message object.
send(msg)

Transmit a message to CAN bus. Override this method to enable the transmit path.

Parameters:msg – A can.Message object.
Raise:can.CanError if the message could not be written.
set_filters(can_filters=None)

Apply filtering to all messages received by this Bus.

Calling without passing any filters will reset the applied filters.

Parameters:can_filters (list) –

A list of dictionaries each containing a “can_id” and a “can_mask”.

>>> [{"can_id": 0x11, "can_mask": 0x21}]

A filter matches, when <received_can_id> & can_mask == can_id & can_mask

shutdown()

Called to carry out any interface specific cleanup required in shutting down a bus.

class can.interfaces.interface.Bus

Instantiates a CAN Bus of the given bustype, falls back to reading a configuration file from default locations.

Transmitting

Writing to the bus is done by calling the send() method and passing a Message object.

Receiving

Reading from the bus is achieved by either calling the recv() method or by directly iterating over the bus:

for msg in bus:
    print(msg.data)

Alternatively the Listener api can be used, which is a list of Listener subclasses that receive notifications when new messages arrive.