API for can4python

This page shows the public part of the API. For a more detailed documentation on all objects, see the can4python sub page: CanBus

If you are using KCD file based configuration, you should really only need to interact with the CanBus object.

class can4python.CanBus(config, interfacename, timeout=None, use_bcm=False)[source]

CAN bus abstraction.

Uses Python 3.3 (or later) and the Linux SocketCAN interface.

The SocketCan Broadcast Manager (BCM) handles periodic sending of CAN frames, and can throttle incoming CAN frames to a slower rate, or to only receive frames when the data content has changed. Python 3.4 (or later) is required to use the BCM.

If you need to receive all frames, do not use the BCM.

Parameters:
  • config (Configuration object) – Configuration object describing what is happening on the bus.
  • interfacename (str) – Name of the Linux SocketCan interface to use. For example 'vcan0' or 'can1'.
  • timeout (numerical) – Timeout value in seconds for recv_next_signals(). Defaults to None (blocking read).
  • use_bcm (bool) – True if the SocketCan Broadcast manager (BCM) should be used. Defaults to False.
classmethod from_kcd_file(filename, interfacename, timeout=None, busname=None, use_bcm=False, ego_node_ids=None)[source]

Create a CanBus, using settings from a configuration file.

This is a convenience function, to avoid creating a separate configuration object.

Parameters:
  • filename (str) – Full path to existing configutation file, in the KCD file format.
  • interfacename (str) – For example 'vcan0' or 'can1'.
  • timeout (numerical) – Timeout value in seconds for recv_next_signals(). Defaults to None (the recv_next_signals call will be blocking).
  • busname (str or None) – Which bus name in the messagedefinitions file to use. Defaults to None (using first alphabetically).
  • use_bcm (bool) – True if the SocketCan Broadcast manager (BCM) should be used. Defaults to False.
  • ego_node_ids (set of strings) – Set of nodes that this program will enact. You can also pass it a list.
config

Get the configuration (read-only). The configuration is set in the constructor.

use_bcm

Return True if BCM is used (read-only). Is set in the constructor.

init_reception()[source]

Setup the CAN frame reception.

When using the RAW protocol, this enables filtering to reduce the input frame flow.

It works the opposite for the BCM protocol, where it explicitly subscribes to frame IDs.

recv_next_signals()[source]

Receive one CAN frame, and unpack it to signal values.

Returns:A dictionary of signal values, where the keys are the signalname (str) and the items are the values (numerical).

If the frame not is defined for this CanBus instance, an empty dictionary is returned.

Raises:CanTimeoutException – If a timeout is defined and no frame is received. See CanTimeoutException.
recv_next_frame()[source]

Receive one CAN frame. Returns a CanFrame object.

Raises:CanTimeoutException – If a timeout is defined and no frame is received. See CanTimeoutException.
stop_reception()[source]

Stop receiving, when using the BCM.

send_signals(*args, **kwargs)[source]

Send CAN signals in frames.

Parameters:signals_to_send (dict) – The signal values to send_frame. The keys are the signalnames (str), and the items are the values (numerical or None). If the value is None the default value is used.

You can also use signal names as function arguments (keyword arguments). These are equal:

mycanbus.send_signals({"VehicleSpeed": 70.3, "EngineSpeed": 2821})
mycanbus.send_signals(VehicleSpeed=70.3, EngineSpeed=2821)

The signal names must be already defined for this CanBus instance.

Raises:CanException – When failing to set signal value etc. See CanException.
start_sending_all_signals()[source]

Start sending all configured frames, when using the BCM.

The default value for the signals are used, until updated via the send_signals() function.

If you do not use this start_sending_all_signals() method, the periodic transmission for each frame will start at first send_signals() call.

send_frame(frame_to_send)[source]

Send a single CAN frame.

Parameters:frame_to_send (CanFrame) – The frame to send.
stop_sending()[source]

Stop periodic sending, when using the BCM.

stop()[source]

Stop periodic sending and receiving, when using the BCM.

get_descriptive_ascii_art()[source]

Display an overview of the CanBus object with frame definitions and signal definitions.

Returns:A multi-line string.
write_configuration(filename)[source]

Write configuration to file.

Parameters:filename (str) – Full path to file with configuration.

Saves to an XML file in the KCD file format.

class can4python.Configuration(framedefinitions=None, busname=None, ego_node_ids=None)[source]

Configuration object for the things that happen on the CAN bus. It holds frame definitions (including signal definitions), the busname etc. See below.

framedefinitions

dict

The keys are the frame_id (int) and the items are the corresponding CanFrameDefinition objects.

busname

str or None

Which bus name in the configuration file to use when reading. Defaults to None (using first alphabetically).

ego_node_ids

set of strings Set of nodes that this program will enact. You can pass it a list (it will convert to a set).

get_descriptive_ascii_art()[source]

Display an overview of the Configuration object with frame definitions and signals.

Returns:A multi-line string.
add_framedefinition(framedef)[source]

Add a frame definition to the configutation.

Parameters:framedef (CanFrameDefinition object) – The frame definition to add.

This is a convenience function. These two alternatives are equal:

myconfig.add_framedefinition(framedef1)
myconfig.framedefinitions[framedef1.frame_id] = framedef1
set_throttle_times(inputdict)[source]

Set throttle_time for some of the framedefinitions in the configuration object.

Parameters:inputdict (dict) – The keys are the frame IDs (int) and the values are the throttle times (numerical or None) in milliseconds.

This is a convenience function. You can instead do like this for each frame:

myconfig.framedefinitions[myframe_id].throttle_time = mythrottletime
set_throttle_times_from_signalnames(inputdict)[source]

Set throttle_time for some of the framedefinitions in the configuration object (via signal names)

Parameters:inputdict (dict) – The keys are the signalnames (str) and the values are the throttle times (numerical or None) in milliseconds.

Note that the throttle_time is set on the framedefinition holding the signalname. It will also affect other signals on the same frame. Setting different throttle_times to signals on the same frame will give an undefined result.

This is a convenience function. You can instead do like this for each signalname:

(first find myframe_id for a given signalname)
myconfig.framedefinitions[myframe_id].throttle_time = mythrottletime
set_receive_on_change_only(inputlist)[source]

Set receive_on_change_only for some of the framedefinitions in the configuration object.

Parameters:inputlist (list of ints) – The frame IDs that should be received only when the data has changed.

This is a convenience function. You can instead do like this for each frame ID:

myconfig.framedefinitions[myframe_id].receive_on_change_only = True
set_receive_on_change_only_from_signalnames(inputlist)[source]

Set receive_on_change_only for some of the framedefinitions in the configuration object (via signal names).

Parameters:inputlist (list of str) – The signal names that should be received only when the data has changed.

Note that the receive_on_change_only is set on the framedefinition holding the signalname. It will also affect other signals on the same frame.

This is a convenience function. You can instead do like this for each signalname:

(first find myframe_id for a given signalname)
myconfig.framedefinitions[myframe_id].receive_on_change_only = True
find_frameid_from_signalname(input_signalname)[source]

Find which frame_id a specific signal name belongs.

Parameters:input_signalname (str) – signal name to search for.

Returns: The frame_id (int) in which the signal is located.

Raises:CanException when the given signal name not is found.
class can4python.FilehandlerKcd[source]

File handler for the KCD file format.

Note that only a subset of the KCD file format is implemented. These tags are read:

* Network definition: xmlns
  * Bus: name
    * Message: id, name, length, interval, format,
      * Producer:
        * NodeRef: id
      * Signal: endianness, length, name, offset
        * Value: type, slope, intercept, unit, min, max
        * Notes:

Further, there are is some configuration information that not can be stored in a KCD file, for example message throttling and to only receive frames at data change.

static read(filename, busname=None)[source]

Read configuration file in KCD format.

Parameters:
  • filename (str) – Full path to the KCD configuration file.
  • busname (str or None) – Which bus name in the configuration file to use when reading. Defaults to None (using first alphabetically).

Returns a Configuration object.

Raises:CanException – When failing to read and unpack the file. See CanException.
static write(config, filename)[source]

Write configuration file in KCD frame_format (a type of XML file).

Parameters:
  • config (Configuration object) – Configuration details.
  • filename (str) – Full path for output KCD file.

If the attribute ‘config.busname’ is None, then DEFAULT_BUSNAME will be used.

class can4python.CanFrameDefinition(frame_id, name='', dlc=8, cycletime=None, frame_format='standard')[source]

A class for describing a CAN frame definition.

This object defines how the signals are laid out etc, but it does not hold the value of the frame or the values of the signals.

To add a CanSignalDefinition object to this CanFrameDefinition object:

myframedef1.signaldefinitions.append(mysignal1)
name

str

Frame name

signaldefinitions

list of CanSignalDefinition objects

Defaults to an empty list. See CanSignalDefinition.

receive_on_change_only

bool

Receive this frame only for updated data value (a data bitmask will be calculated). Defaults to False.

frame_id

int Frame ID. Should be in the range 0 to 0x7FF for standard frame format, or in the range 0 to 0x1FFFFFFF for extended frames.

dlc

int Number of bytes that should appear in the frame. Should be in the range 0 to 8. Default: 8 bytes.

cycletime

numerical or None Shortest cycle time (in milliseconds) when sending. Defaults to None.

throttle_time

numerical or None Shortest update time (in milliseconds) for this frame when receiving. Defaults to None (no throttling).

frame_format

str Frame format. Should be 'standard' or 'extended'. Defaults to standard frame format.

producer_ids

set of strings Set of nodes (ECUs) that produce this frame. You can pass it a list (it will convert to a set).

get_descriptive_ascii_art()[source]

Display an overview of the frame definition with its signals.

Returns:A multi-line string.
get_signal_mask()[source]

Calculate signal mask.

Returns a bytes object (length 8 bytes). A 1 in a position indicates that there is an interesting signal.

is_outbound(ego_node_ids)[source]
Parameters:ego_node_ids (list/set of strings) – List of nodes that this program will enact.

The frames with producer IDs matching some in the ego_node_ids list are considered outgoing/outbound frames.

Defaults to inbound, for example if no producer_ids or ego_node_ids are given.

Returns True if this frame is outbound (ie will be sent). Otherwise it is inbound (will be received).

class can4python.CanSignalDefinition(signalname, startbit, numberofbits, scalingfactor=1, valueoffset=0, defaultvalue=None, unit='', comment='', minvalue=None, maxvalue=None, endianness='little', signaltype='unsigned')[source]

A class for describing a CAN signal definition (not the value of the signal).

signalname

str

Signal name

unit

str

Unit for the value. Defaults to ''.

comment

str

A human-readable comment. Defaults to ''.

Raises:CanException – For wrong startbit, endianness etc. See CanException.

Warning

When setting the numberofbits attribute, then the attributes endianness and startbit must already be correct. Otherwise the error-checking mechanism might raise an error.

Also, the minvalue, maxvalue and defaultvalue should be within the limits defined by numberofbits, scalingfactor, signaltype etc.

Note

The byte order in a CAN frame is 0 1 2 3 4 5 6 7 (left to right)

The byte 0 in the CAN frame is sent first.

Bit order (significance) is decreasing from left to right. So in a byte, the rightmost bit is least significant.

Bit numbering in the CAN frame (standard bit numbering):

  • In the first byte the least significant bit (rightmost, value 1) is named 0, and the most significant bit (leftmost, value 128) is named 7.
  • In next byte, the least significant bit is named 8 etc.

This results in this bit numbering for the CAN frame:

7,6,5,4,3,2,1,0  15,14,13,12,11,10,9,8  23,22,21,20,19,18,17,16  31,30,29,28,27,26,25,24 etc.
Byte0            Byte1                  Byte2                    Byte3

Note

The start bit is given for the least significant bit in the signal, in standard bit numbering.

When a signal spans several bytes in the frame, the CAN frame can be constructed in two ways:

  • In big-endian (Motorola, Network) byte order, the most significant byte is sent first.
  • In little-endian (Intel) byte order, the least significant byte is sent first.

For example, an integer 0x0102030405060708 can be transmitted as big-endian or little-endian:

  • Big-endian (most significant byte first): 01 02 03 04 05 06 07 08
  • Little-endian (least significant byte first): 08 07 06 05 04 03 02 01

Note

If the signal is fitting into a single byte (not crossing any byte borders), there is no difference between big and little endian.

There is an alternate overall bit numbering scheme, known as “backwards” bit numbering.

Other variants (not used in this software):

  • Startbit is sometimes given as the most significant bit.
endianness

str 'big' or 'little'. Defaults to using little endian (as the KCD file format defaults to little endian).

signaltype

str Should be 'unsigned', 'signed', 'single' or 'double'. (The last two are floats). Defaults to using unsigned signal type.

scalingfactor

numerical Scaling factor. Multiply with this value when extracting the signal from the CAN frame. Defaults to 1. Should be positive.

valueoffset

numerical Offset. Add this value when extracting the signal from the CAN frame. Defaults to 0.

startbit

int Position of least significant bit (in the standard bit numbering). Should be in the range 0 to 63 (inclusive).

defaultvalue

numerical or None Default value to send in frames if the signal value not is known. Defaults to None (Use the ‘valueoffset’ value).

minvalue

numerical or None Minimum allowed physical value. Defaults to None (no checking is done).

maxvalue

numerical or None Maximum allowed physical value. Defaults to None (no checking is done).

numberofbits

int Number of bits in the signal. Should be in the range 1 to 64 (inclusive).

get_descriptive_ascii_art()[source]

Create a visual indication how the signal is located in the frame_definition.

Returns:A multi-line string.
get_maximum_possible_value()[source]

Get the largest value that technically could be sent with this signal.

The largest integer we can store is 2**numberofbits - 1. Also the scalingfactor, valueoffset and the signaltype affect the result.

This method is used to calculate the allowed ranges for the attributes minvalue, ‘maxvalue and defaultvalue. When using the signal, you should respect the minvalue and maxvalue.

Returns:The largest possible value (numerical).

See the twos_complement functions for discussion of value ranges for signed integers.

get_minimum_possible_value()[source]

Get the smallest value that technically could be sent with this signal.

This method is used to calculate the allowed ranges for the attributes minvalue, ‘maxvalue and defaultvalue. When using the signal, you should respect the minvalue and maxvalue.

Returns:The smallest possible value (numerical).
get_minimum_dlc()[source]

Calculate the smallest number of bytes (DLC) that a frame must have, to be able to send this signal.

Returns:Minimum DLC (int)
exception can4python.CanException[source]

Base exception for CAN package

exception can4python.CanTimeoutException[source]

Timeout for CAN package