Bus#

The Bus provides a wrapper around a physical or virtual CAN Bus.

An interface specific instance is created by instantiating the Bus class with a particular interface, for example:

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

The created bus is then able to handle the interface specific software/hardware interactions while giving the user the same top level API.

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

Transmitting#

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

with can.Bus() as bus:
    msg = can.Message(
        arbitration_id=0xC0FFEE,
        data=[0, 25, 0, 1, 3, 1, 4, 1],
        is_extended_id=True
    )
    try:
        bus.send(msg)
        print(f"Message sent on {bus.channel_info}")
    except can.CanError:
        print("Message NOT sent")

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:

with can.Bus() as bus:
    for msg in bus:
        print(msg.data)

Alternatively the Listener api can be used, which is a list of various Listener implementations that receive and handle messages from a Notifier.

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", interface="socketcan", can_filters=filters)

See set_filters() for the implementation.

Bus API#

class can.Bus(channel=None, interface=None, config_context=None, ignore_config=False, **kwargs)[source]#

Bases: BusABC

Bus wrapper with configuration loading.

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

Note

Please note that while the arguments provided to this class take precedence over any existing values from configuration, it is possible that other parameters from the configuration may be added to the bus instantiation. This could potentially have unintended consequences. To prevent this, you may use the ignore_config parameter to ignore any existing configurations.

Parameters:
  • channel (str | int | None) – Channel identification. Expected type is backend dependent. Set to None to let it be resolved automatically from the default Configuration.

  • interface (str | None) – See Interface Names for a list of supported interfaces. Set to None to let it be resolved automatically from the default Configuration.

  • config_context (str | None) – Extra ‘context’, that is passed to config sources. This can be used to select a section other than ‘default’ in the configuration file.

  • ignore_config (bool) – If True, only the given arguments will be used for the bus instantiation. Existing configuration sources will be ignored.

  • kwargs (Any) – interface specific keyword arguments.

Raises:
Return type:

BusABC

RECV_LOGGING_LEVEL = 9#

Log level for received messages

channel_info = 'unknown'#

a string describing the underlying bus and/or channel

property filters: Sequence[CanFilter | CanFilterExtended] | None#

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

flush_tx_buffer()#

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

Return type:

None

recv(timeout=None)#

Block waiting for a message from the Bus.

Parameters:

timeout (float | None) – seconds to wait for a message or None to wait indefinitely

Returns:

None on timeout or a Message object.

Raises:

CanOperationError – If an error occurred while reading

Return type:

Message | None

abstract send(msg, timeout=None)#

Transmit a message to the CAN bus.

Override this method to enable the transmit path.

Parameters:
  • msg (Message) – A message object.

  • timeout (float | None) – 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:

CanOperationError – If an error occurred while sending

Return type:

None

send_periodic(msgs, period, duration=None, store_task=True)#

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

  • stop_all_periodic_tasks() is called

  • the task’s stop() method is called.

Parameters:
  • msgs (Message | Sequence[Message]) – Message(s) to transmit

  • period (float) – Period in seconds between each message

  • duration (float | None) – 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.

Returns:

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

Return type:

CyclicSendTaskABC

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)#

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 (Sequence[CanFilter | CanFilterExtended] | None) –

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.

Return type:

None

shutdown()#

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

Return type:

None

property state: BusState#

Return the current state of the hardware

stop_all_periodic_tasks(remove_tasks=True)#

Stop sending any messages that were started using 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.

Return type:

None

class can.bus.BusState(value)[source]#

The state in which a can.BusABC can be.

ACTIVE = 1#
ERROR = 3#
PASSIVE = 2#

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]#

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.