Internal API¶
Here we document the odds and ends that are more helpful for creating your own interfaces or listeners but generally shouldn’t be required to interact with python-can.
Extending the BusABC
class¶
- Concrete implementations must 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 sentshutdown()
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:
Concrete instances are usually created by can.Bus
which takes the users
configuration into account.
Bus Internals¶
Several methods are not documented in the main can.BusABC
as they are primarily useful for library developers as opposed to
library users. This is the entire ABC bus class with all internal
methods:
- 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
channel (
Any
) – The can interface identifier. Expected type is backend dependent.can_filters (
Optional
[Sequence
[Union
[CanFilter
,CanFilterExtended
]],None
]) – Seeset_filters()
for details.kwargs (dict) – Any backend dependent configurations are passed in this dictionary
- Raises
ValueError – If parameters are out of range
can.CanInterfaceNotImplementedError – If the driver cannot be accessed
can.CanInitializationError – If the bus cannot be initialized
About the IO module¶
Handling of the different file formats is implemented in can.io
.
Each file/IO type is within a separate module and ideally implements both a Reader and a Writer.
The reader usually extends can.io.generic.BaseIOHandler
, while
the writer often additionally extends can.Listener
,
to be able to be passed directly to a can.Notifier
.
Adding support for new file formats¶
This assumes that you want to add a new file format, called canstore. Ideally add both reading and writing support for the new file format, although this is not strictly required.
Create a new module: can/io/canstore.py (or simply copy some existing one like can/io/csv.py)
Implement a reader
CanstoreReader
(which often extendscan.io.generic.BaseIOHandler
, but does not have to). Besides from a constructor, only__iter__(self)
needs to be implemented.Implement a writer
CanstoreWriter
(which often extendscan.io.generic.BaseIOHandler
andcan.Listener
, but does not have to). Besides from a constructor, onlyon_message_received(self, msg)
needs to be implemented.Add a case to
can.io.player.LogReader
’s__new__()
.Document the two new classes (and possibly additional helpers) with docstrings and comments. Please mention features and limitations of the implementation.
Add a short section to the bottom of doc/listeners.rst.
Add tests where appropriate, for example by simply adding a test case called class TestCanstoreFileFormat(ReaderWriterTest) to test/logformats_test.py. That should already handle all of the general testing. Just follow the way the other tests in there do it.
Add imports to can/__init__py and can/io/__init__py so that the new classes can be simply imported as from can import CanstoreReader, CanstoreWriter.
IO Utilities¶
Contains generic base classes for file IO.
- class can.io.generic.BaseIOHandler(file, mode='rt')[source]¶
A generic file handler that can be used for reading and writing.
Can be used as a context manager.
- Attr file
the file-like object that is kept internally, or None if none was opened
- Parameters
file (
Union
[TextIO
,BinaryIO
,GzipFile
,str
,ForwardRef
,None
]) – a path-like object to open a file, a file-like object to be used as a file or None to not use a file at allmode (
str
) – the mode that should be used to open the file, seeopen()
, ignored if file is None
- class can.io.generic.FileIOMessageWriter(file, mode='rt')[source]¶
A specialized base class for all writers with file descriptors.
- Parameters
file (
Union
[TextIO
,BinaryIO
,GzipFile
,str
,ForwardRef
]) – a path-like object to open a file, a file-like object to be used as a file or None to not use a file at allmode (
str
) – the mode that should be used to open the file, seeopen()
, ignored if file is None
- class can.io.generic.MessageReader(file, mode='rt')[source]¶
The base class for all readers.
- Parameters
file (
Union
[TextIO
,BinaryIO
,GzipFile
,str
,ForwardRef
,None
]) – a path-like object to open a file, a file-like object to be used as a file or None to not use a file at allmode (
str
) – the mode that should be used to open the file, seeopen()
, ignored if file is None
- class can.io.generic.MessageWriter(file, mode='rt')[source]¶
The base class for all writers.
- Parameters
file (
Union
[TextIO
,BinaryIO
,GzipFile
,str
,ForwardRef
,None
]) – a path-like object to open a file, a file-like object to be used as a file or None to not use a file at allmode (
str
) – the mode that should be used to open the file, seeopen()
, ignored if file is None
Other Utilities¶
Utilities and configuration file parsing.
- can.util.channel2int(channel)[source]¶
Try to convert the channel to an integer.
- Parameters
channel (
Union
[int
,str
,None
]) – Channel string (e.g. “can0”, “CAN1”) or an integer- Return type
Optional
[int
,None
]- Returns
Channel integer or
None
if unsuccessful
- can.util.deprecated_args_alias(**aliases)[source]¶
Allows to rename/deprecate a function kwarg(s) and optionally have the deprecated kwarg(s) set as alias(es)
Example:
@deprecated_args_alias(oldArg=”new_arg”, anotherOldArg=”another_new_arg”) def library_function(new_arg, another_new_arg):
pass
@deprecated_args_alias(oldArg=”new_arg”, obsoleteOldArg=None) def library_function(new_arg):
pass
- can.util.dlc2len(dlc)[source]¶
Calculate the data length from DLC.
- Parameters
dlc (
int
) – DLC (0-15)- Return type
int
- Returns
Data length in number of bytes (0-64)
- can.util.len2dlc(length)[source]¶
Calculate the DLC from data length.
- Parameters
length (
int
) – Length in number of bytes (0-64)- Return type
int
- Returns
DLC (0-15)
- can.util.load_config(path=None, config=None, context=None)[source]¶
Returns a dict with configuration details which is loaded from (in this order):
config
can.rc
Environment variables CAN_INTERFACE, CAN_CHANNEL, CAN_BITRATE
Config files
/etc/can.conf
or~/.can
or~/.canrc
where the latter may add or replace values of the former.
Interface can be any of the strings from
can.VALID_INTERFACES
for example: kvaser, socketcan, pcan, usb2can, ixxat, nican, virtual.Note
The key
bustype
is copied tointerface
if that one is missing and does never appear in the result.- Parameters
path (
Union
[TextIO
,BinaryIO
,GzipFile
,str
,PathLike
[str
],None
]) – Optional path to config file.config (
Optional
[Dict
[str
,Any
],None
]) – A dict which may set the ‘interface’, and/or the ‘channel’, or neither. It may set other values that are passed through.context (
Optional
[str
,None
]) – Extra ‘context’ pass to config sources. This can be use to section other than ‘default’ in the configuration file.
- Return type
BusConfig
- Returns
A config dictionary that should contain ‘interface’ & ‘channel’:
{ 'interface': 'python-can backend interface to use', 'channel': 'default channel to use', # possibly more }
Note
None
will be used if all the options are exhausted without finding a value.All unused values are passed from
config
over to this.- Raises
CanInterfaceNotImplementedError if the
interface
name isn’t recognized
- can.util.load_environment_config(context=None)[source]¶
Loads config dict from environmental variables (if set):
CAN_INTERFACE
CAN_CHANNEL
CAN_BITRATE
CAN_CONFIG
if context is supplied, “_{context}” is appended to the environment variable name we will look at. For example if context=”ABC”:
CAN_INTERFACE_ABC
CAN_CHANNEL_ABC
CAN_BITRATE_ABC
CAN_CONFIG_ABC
- Return type
Dict
[str
,str
]
- can.util.load_file_config(path=None, section='default')[source]¶
Loads configuration from file with following content:
[default] interface = socketcan channel = can0
- Parameters
path (
Union
[TextIO
,BinaryIO
,GzipFile
,str
,PathLike
[str
],None
]) – path to config file. If not specified, several sensible default locations are tried depending on platform.section (
str
) – name of the section to read configuration from.
- Return type
Dict
[str
,str
]
- can.util.set_logging_level(level_name)[source]¶
Set the logging level for the “can” logger.
- Parameters
level_name (
str
) – One of: ‘critical’, ‘error’, ‘warning’, ‘info’,
‘debug’, ‘subdebug’, or the value None (=default). Defaults to ‘debug’.
- Return type
None
- can.util.time_perfcounter_correlation()[source]¶
Get the perf_counter value nearest to when time.time() is updated
Computed if the default timer used by time.time on this platform has a resolution higher than 10μs, otherwise the current time and perf_counter is directly returned. This was chosen as typical timer resolution on Linux/macOS is ~1μs, and the Windows platform can vary from ~500μs to 10ms.
Note this value is based on when time.time() is observed to update from Python, it is not directly returned by the operating system.
- Return type
Tuple
[float
,float
]- Returns
(t, performance_counter) time.time value and time.perf_counter value when the time.time is updated