Developer’s Overview

Contributing

Contribute to source code, documentation, examples and report issues: https://github.com/hardbyte/python-can

There is also a python-can mailing list for development discussion.

Building & Installing

The following assumes that the commands are executed from the root of the repository:

  • The project can be built and installed with python setup.py build and python setup.py install.
  • The unit tests can be run with python setup.py test. The tests can be run with python2, python3, pypy or pypy3 to test with other python versions, if they are installed. Maybe, you need to execute pip3 install python-can[test] (or only pip for Python 2), if some dependencies are missing.
  • The docs can be built with sphinx-build doc/ doc/_build. Appending -n to the command makes Sphinx complain about more subtle problems.

Creating a new interface/backend

These steps are a guideline on how to add a new backend to python-can.

  • Create a module (either a *.py or an entire subdirectory depending on the complexity) inside can.interfaces
  • Implement the central part of the backend: the bus class that extends can.BusABC. See below for more info on this one!
  • Register your backend bus class in can.interface.BACKENDS and can.interfaces.VALID_INTERFACES in can.interfaces.__init__.py.
  • Add docs where appropriate. At a minimum add to doc/interfaces.rst and add a new interface specific document in doc/interface/*.
  • Update doc/scripts.rst accordingly.
  • Add tests in test/* where appropriate.

About the BusABC class

Concrete implementations have to implement the following:
  • send() to send individual messages
  • _recv_internal() to receive individual messages (see note below!)
  • set the channel_info attribute to a string describing the underlying bus and/or channel
They might implement the following:
  • flush_tx_buffer() to allow discarding any messages yet to be sent
  • shutdown() to override how the bus should shut down
  • _send_periodic_internal() to override the software based periodic sending and push it down to the kernel or hardware.
  • _apply_filters() to apply efficient filters to lower level systems like the OS kernel or hardware.
  • _detect_available_configs() to allow the interface to report which configurations are currently available for new connections.
  • state() property to allow reading and/or changing the bus state.

Note

TL;DR: Only override _recv_internal(), never recv() directly.

Previously, concrete bus classes had to override recv() directly instead of _recv_internal(), but that has changed to allow the abstract base class to handle in-software message filtering as a fallback. All internal interfaces now implement that new behaviour. Older (custom) interfaces might still be implemented like that and thus might not provide message filtering:

This is the entire ABC bus class with all internal methods:

class can.BusABC(channel, can_filters=None, **config)[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.
  • config (dict) – Any backend dependent configurations are passed in this dictionary
RECV_LOGGING_LEVEL = 9

Log level for received messages

__init__(channel, can_filters=None, **config)[source]

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.
  • config (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.
__metaclass__

alias of abc.ABCMeta

__str__()[source]

Return str(self).

__weakref__

list of weak references to the object (if defined)

_apply_filters(filters)[source]

Hook for applying the filters to the underlying kernel or hardware if supported/implemented by the interface.

Parameters:filters (Iterator[dict]) – See set_filters() for details.
static _detect_available_configs()[source]

Detect all configurations/channels that this interface could currently connect with.

This might be quite time consuming.

May not to be implemented by every interface on every platform.

Return type:Iterator[dict]
Returns:an iterable of dicts, each being a configuration suitable for usage in the interface’s bus constructor.
_matches_filters(msg)[source]

Checks whether the given message matches at least one of the current filters. See set_filters() for details on how the filters work.

This method should not be overridden.

Parameters:msg (can.Message) – the message to check if matching
Return type:bool
Returns:whether the given message matches at least one filter
_recv_internal(timeout)[source]

Read a message from the bus and tell whether it was filtered. This methods may be called by recv() to read a message multiple times if the filters set by set_filters() do not match and the call has not yet timed out.

New implementations should always override this method instead of recv(), to be able to take advantage of the software based filtering provided by recv() as a fallback. This method should never be called directly.

Note

This method is not an @abstractmethod (for now) to allow older external implementations to continue using their existing recv() implementation.

Note

The second return value (whether filtering was already done) may change over time for some interfaces, like for example in the Kvaser interface. Thus it cannot be simplified to a constant value.

Parameters:

timeout (float) – seconds to wait for a message, see send()

Return type:

tuple[can.Message, bool] or tuple[None, bool]

Returns:

  1. a message that was read or None on timeout
  2. a bool that is True if message filtering has already been done and else False

Raises:
_send_periodic_internal(msg, period, duration=None)[source]

Default implementation of periodic message sending using threading.

Override this method to enable a more efficient backend specific approach.

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.
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

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 indefinitly.
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
  • Bus.stop_all_periodic_tasks() is called
  • the task’s Task.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 :return: ACTIVE, PASSIVE or ERROR :rtype: NamedTuple

stop_all_periodic_tasks(remove_tasks=True)[source]

Stop sending any messages that were started using bus.send_periodic

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

Concrete instances are created by can.Bus.

Code Structure

The modules in python-can are:

Module Description
interfaces Contains interface dependent code.
bus Contains the interface independent Bus object.
message Contains the interface independent Message object.
io Contains a range of file readers and writers.
broadcastmanager Contains interface independent broadcast manager code.
CAN Legacy API. Deprecated.

Creating a new Release

  • Release from the master branch.
  • Update the library version in __init__.py using semantic versioning.
  • Check if any deprecations are pending.
  • Run all tests and examples against available hardware.
  • Update CONTRIBUTORS.txt with any new contributors.
  • For larger changes update doc/history.rst.
  • Sanity check that documentation has stayed inline with code.
  • Create a temporary virtual environment. Run python setup.py install and python setup.py test.
  • Create and upload the distribution: python setup.py sdist bdist_wheel.
  • Sign the packages with gpg gpg --detach-sign -a dist/python_can-X.Y.Z-py3-none-any.whl.
  • Upload with twine twine upload dist/python-can-X.Y.Z*.
  • In a new virtual env check that the package can be installed with pip: pip install python-can==X.Y.Z.
  • Create a new tag in the repository.
  • Check the release on PyPi, Read the Docs and GitHub.