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 – The can interface identifier. Expected type is backend dependent.
  • can_filters (list) – 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 – The can interface identifier. Expected type is backend dependent.
  • can_filters (list) – 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:can.Message msg objects.
RECV_LOGGING_LEVEL = 9

Log level for received messages

channel_info = 'unknown'

a string describing the underlying bus and/or channel

filters

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

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 (float or None) – seconds to wait for a message or None to wait indefinitely
Return type:can.Message or None
Returns:None on timeout or a can.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 (can.Message) – A message object.
  • timeout (float or 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:

can.CanError – if the message could not be sent

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

Start sending a message 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:
  • msg (can.Message) – Message to transmit
  • period (float) – Period in seconds between each message
  • duration (float) – The duration to keep sending this message at given rate. 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 stop() method.

Return type:

can.broadcastmanager.CyclicSendTaskABC

Note

Note the duration before the message stops 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

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

Type:can.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.

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.