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]¶
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
- Raises
ValueError – If parameters are out of range
can.CanInterfaceNotImplementedError – If the driver cannot be accessed
can.CanInitializationError – If the bus cannot be initialized
API¶
- class can.BusABC(channel, can_filters=None, **kwargs)[source]¶
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 and as a context manager for auto-closing the bus when done using it.
Please refer to Errors for possible exceptions that may be thrown by certain operations on this bus.
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
- Raises
ValueError – If parameters are out of range
can.CanInterfaceNotImplementedError – If the driver cannot be accessed
can.CanInitializationError – If the bus cannot be initialized
- __iter__()[source]¶
Allow iteration on messages as they are received.
>>> for msg in bus: ... print(msg)
- RECV_LOGGING_LEVEL = 9¶
Log level for received messages
- channel_info = 'unknown'¶
a string describing the underlying bus and/or channel
- property filters: Optional[Sequence[Union[can.typechecking.CanFilter, can.typechecking.CanFilterExtended]]]¶
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).
- Return type
- abstract 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.CanOperationError – If an error occurred while sending
- Return type
- 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 calledthe task’s
CyclicTask.stop()
method is called.
- Parameters
msgs (
Union
[Message
,Sequence
[Message
]]) – Message(s) to transmitperiod (
float
) – Period in seconds between each messageduration (
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
- 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
. Ifextended
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
- shutdown()[source]¶
Called to carry out any interface specific cleanup required in shutting down a bus.
- Return type
- property state: can.bus.BusState¶
Return the current state of the hardware
- Return type
BusState
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]¶
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
.