Bus

The BusABC class, as the name suggests, provides an abstraction of a CAN bus. The bus provides a wrapper around a physical or virtual CAN Bus. An interface specific instance of the BusABC is created by the Bus class, for example:

vector_bus = can.Bus(interface='vector', ...)

That bus is then able to handle the interface specific software/hardware interactions and implements the BusABC API.

A thread safe bus wrapper is also available, see Thread safe bus.

Autoconfig Bus

class can.Bus(channel, can_filters=None, **kwargs)[source]

Bases: can.bus.BusABC

Bus wrapper with configuration loading.

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

Construct and open a CAN bus instance of the specified type.

Subclasses should call though this method with all given parameters as it handles generic tasks like applying filters.

Parameters:
  • channel (Any) – The can interface identifier. Expected type is backend dependent.
  • can_filters (Optional[Sequence[Union[CanFilter, CanFilterExtended]]]) – See set_filters() for details.
  • kwargs (dict) – Any backend dependent configurations are passed in this dictionary

API

class can.BusABC(channel, can_filters=None, **kwargs)[source]

Bases: object

The CAN Bus Abstract Base Class that serves as the basis for all concrete interfaces.

This class may be used as an iterator over the received messages.

Construct and open a CAN bus instance of the specified type.

Subclasses should call though this method with all given parameters as it handles generic tasks like applying filters.

Parameters:
  • channel (Any) – The can interface identifier. Expected type is backend dependent.
  • can_filters (Optional[Sequence[Union[CanFilter, CanFilterExtended]]]) – See set_filters() for details.
  • kwargs (dict) – Any backend dependent configurations are passed in this dictionary
__iter__()[source]

Allow iteration on messages as they are received.

>>> for msg in bus:
...     print(msg)
Yields:Message msg objects.
Return type:Iterator[Message]
RECV_LOGGING_LEVEL = 9

Log level for received messages

channel_info = 'unknown'

a string describing the underlying bus and/or channel

fileno()[source]
Return type:int
filters

Modify the filters of this bus. See set_filters() for details.

Return type:Optional[Sequence[Union[CanFilter, CanFilterExtended]]]
flush_tx_buffer()[source]

Discard every message that may be queued in the output buffer(s).

recv(timeout=None)[source]

Block waiting for a message from the Bus.

Parameters:timeout (Optional[float]) – seconds to wait for a message or None to wait indefinitely
Return type:Optional[Message]
Returns:None on timeout or a Message object.
Raises:can.CanError – if an error occurred while reading
send(msg, timeout=None)[source]

Transmit a message to the CAN bus.

Override this method to enable the transmit path.

Parameters:
  • msg (Message) – A message object.
  • timeout (Optional[float]) – If > 0, wait up to this many seconds for message to be ACK’ed or for transmit queue to be ready depending on driver implementation. If timeout is exceeded, an exception will be raised. Might not be supported by all interfaces. None blocks indefinitely.
Raises:

can.CanError – if the message could not be sent

send_periodic(msgs, period, duration=None, store_task=True)[source]

Start sending messages at a given period on this bus.

The task will be active until one of the following conditions are met:

  • the (optional) duration expires
  • the Bus instance goes out of scope
  • the Bus instance is shutdown
  • BusABC.stop_all_periodic_tasks() is called
  • the task’s CyclicTask.stop() method is called.
Parameters:
  • msgs (Union[Sequence[Message], Message]) – Messages to transmit
  • period (float) – Period in seconds between each message
  • duration (Optional[float]) – Approximate duration in seconds to continue sending messages. If no duration is provided, the task will continue indefinitely.
  • store_task (bool) – If True (the default) the task will be attached to this Bus instance. Disable to instead manage tasks manually.
Return type:

CyclicSendTaskABC

Returns:

A started task instance. Note the task can be stopped (and depending on the backend modified) by calling the task’s stop() method.

Note

Note the duration before the messages stop being sent may not be exactly the same as the duration specified by the user. In general the message will be sent at the given rate until at least duration seconds.

Note

For extremely long running Bus instances with many short lived tasks the default api with store_task==True may not be appropriate as the stopped tasks are still taking up memory as they are associated with the Bus instance.

set_filters(filters=None)[source]

Apply filtering to all messages received by this Bus.

All messages that match at least one filter are returned. If filters is None or a zero length sequence, all messages are matched.

Calling without passing any filters will reset the applied filters to None.

Parameters:filters (Optional[Sequence[Union[CanFilter, CanFilterExtended]]]) –

A iterable of dictionaries each containing a “can_id”, a “can_mask”, and an optional “extended” key.

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

A filter matches, when <received_can_id> & can_mask == can_id & can_mask. If extended is set as well, it only matches messages where <received_is_extended> == extended. Else it matches every messages based only on the arbitration ID and mask.

shutdown()[source]

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

state

Return the current state of the hardware

Return type:BusState
stop_all_periodic_tasks(remove_tasks=True)[source]

Stop sending any messages that were started using bus.send_periodic.

Note

The result is undefined if a single task throws an exception while being stopped.

Parameters:remove_tasks (bool) – Stop tracking the stopped tasks.

Transmitting

Writing individual messages to the bus is done by calling the send() method and passing a Message instance. Periodic sending is controlled by the broadcast manager.

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.

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. All messages that match at least one filter are returned.

Example defining two filters, one to pass 11-bit ID 0x451, the other to pass 29-bit ID 0xA0000:

filters = [
    {"can_id": 0x451, "can_mask": 0x7FF, "extended": False},
    {"can_id": 0xA0000, "can_mask": 0x1FFFFFFF, "extended": True},
]
bus = can.interface.Bus(channel="can0", bustype="socketcan", can_filters=filters)

See set_filters() for the implementation.

Thread safe bus

This thread safe version of the BusABC class can be used by multiple threads at once. Sending and receiving is locked separately to avoid unnecessary delays. Conflicting calls are executed by blocking until the bus is accessible.

It can be used exactly like the normal BusABC:

# 'socketcan' is only an example interface, it works with all the others too
my_bus = can.ThreadSafeBus(interface='socketcan', channel='vcan0')
my_bus.send(...)
my_bus.recv(...)
class can.ThreadSafeBus(*args, **kwargs)[source]

Bases: ObjectProxy

Contains a thread safe can.BusABC implementation that wraps around an existing interface instance. All public methods of that base class are now safe to be called from multiple threads. The send and receive methods are synchronized separately.

Use this as a drop-in replacement for BusABC.

Note

This approach assumes that both send() and _recv_internal() of the underlying bus instance can be called simultaneously, and that the methods use _recv_internal() instead of recv() directly.