can4python package

Submodules

can4python.canbus module

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

Bases: object

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.

can4python.canframe module

class can4python.canframe.CanFrame(frame_id, frame_data, frame_format='standard')[source]

Bases: object

CAN frame with data. Does not know how the signals are laid out etc.

Raises:CanException – For wrong frame ID. See CanException.

To find the DLC, use one of:

len(myframe)
len(myframe.frame_data)
classmethod from_empty_bytes(frame_id, number_of_bytes, frame_format='standard')[source]

Create a CanFrame with empty bytes.

Parameters:
  • frame_id (int) – CAN frame ID number
  • number_of_bytes (int) – number of empty data bytes to initialize the frame with.
  • frame_format (str) – Frame format. Should be 'standard' or 'extended'. Defaults to standard frame format.
classmethod from_rawframe(rawframe)[source]

Create a CanFrame from a raw frame from the SocketCAN interface.

Parameters:rawframe (bytes) – 16 bytes long, includes frame ID, frame format etc
frame_id

int CAN frame ID number

frame_data

bytes object 0-8 bytes of CAN data

frame_format

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

get_signalvalue(signaldefinition)[source]

Extract a signal value from the frame.

Parameters:signaldefinition (CanSignalDefinition object) – The definition of the signal
Returns:The extracted signal physical value (numerical).
set_signalvalue(signaldefinition, physical_value=None)[source]

Set a signal physical_value in the frame.

Parameters:
  • signaldefinition (CanSignalDefinition object) – The definition of the signal
  • physical_value – The physical_value (numerical) of the signal.
Raises:

CanException – For wrong startbit or values. See CanException.

unpack(frame_definitions)[source]

Unpack the CAN frame, and return all signal values.

Parameters:frame_definitions (dict) – The keys are frame_id (int) and the items are CanFrameDefinition objects.
Raises:CanException – For wrong DLC. See CanException.
Returns:A dictionary of signal values. The keys are the signalname (str) and the items are the values (numerical).

If the frame not is described in the ‘frame_definitions’, an empty dictionary is returned.

get_rawframe()[source]

Returns a 16 bytes long ‘bytes’ object.

get_descriptive_ascii_art()[source]

Create a visual indication of the frame data

Returns:A multi-line string.

can4python.canframe_definition module

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

Bases: object

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

can4python.caninterface_bcm module

class can4python.caninterface_bcm.SocketCanBcmInterface(interfacename, timeout=None)[source]

Bases: object

A Linux SocketCAN interface, using the Broadcast Manager (BCM) in the Linux kernel.

Parameters:
  • interfacename (str) – For example ‘vcan0’ or ‘can1’
  • timeout (numerical or None) – Timeout value in seconds receiving BCM messages from the kernel. Defaults to None (blocking).
Raises:
interfacename

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

close()[source]

Close the socket

recv_next_frame()[source]

Receive one CAN frame.

Returns a CanFrame object.

send_frame(input_frame)[source]

Send a single CAN frame (a CanFrame object)

setup_periodic_send(input_frame, interval=None, restart_timer=True)[source]

Setup periodic transmission for a frame ID.

Parameters:
  • input_frame (CanFrame object) – The frame (including data and frame ID) to send periodically.
  • interval (float or None) – Interval between consecutive transmissions (in milliseconds). Defaults to None (do not update the timing information).
  • restart_timer (bool) – Start or restart the transmission timer. Defaults to True. Set this to false if you just would like to update the data to be sent, but not force reset of the transmission timer.
stop_periodic_send(frame_id, frame_format='standard')[source]

Stop the periodic transmission for this frame_id.

Parameters:
  • frame_id (int) – Frame ID
  • frame_format (str) – Frame format. Should be 'standard' or 'extended'. Defaults to standard frame format.
setup_reception(frame_id, frame_format='standard', min_interval=None, data_mask=None)[source]

Setup reception for this frame_id (pretty much subscribe).

Parameters:
  • frame_id (int) – Frame ID
  • frame_format (str) – Frame format. Should be 'standard' or 'extended'. Defaults to standard frame format.
  • min_interval (float or None) – Minimum interval between received frames (in milliseconds). Useful for throttling rapid data streams. Defaults to None (no throttling). A min_interval of 0 corresponds to no throttling.
  • data_mask (bytes or None) – Enable filtering on data changes. The mask is bytes object (length 8 bytes). Set the corresponding bits to 1 to detect data change in that location. Defaults to None (data is not studied for changes, all incoming frames are given to the user).
stop_reception(frame_id, frame_format='standard')[source]

Disable the reception for this frame_id.

Parameters:
  • frame_id (int) – Frame ID
  • frame_format (str) – Frame format. Should be 'standard' or 'extended'. Defaults to standard frame format.
_send_via_socket(input_bytes)[source]

Send data on the object’s socket. Handles OSError.

Parameters:input_bytes (byte) – Data to send
can4python.caninterface_bcm._build_bcm_header(opcode, flags, interval, frame_id, frame_format, number_of_bcm_frames)[source]

Build a BCM message header.

Parameters:
  • opcode (int) – Command to the BCM
  • flags (int) – Flags to the BCM
  • interval (float) – Timing interval in milliseconds
  • frame_id (int) – Frame ID.
  • frame_format (str) – Frame format. Should be 'standard' or 'extended'
  • number_of_bcm_frames (int) – Number of attached raw frames to the header.

Returns the header as bytes (length 56 bytes)

Note that ‘interval’ is the ival2 in Linux kernel documentation.

can4python.caninterface_bcm._parse_bcm_header(header)[source]

Parse a BCM message header.

Parameters:header (bytes) – BCM header. Should have a length of 56 bytes.

Returns the tuple (opcode, flags, ival1_count, ival1, ival2, frame_id, frame_format, number_of_bcm_frames)

can4python.caninterface_raw module

class can4python.caninterface_raw.SocketCanRawInterface(interfacename, timeout=None)[source]

Bases: object

A Linux Socket-CAN interface, using the RAW protocol to the Linux kernel.

Parameters:
  • interfacename (str) – For example ‘vcan0’ or ‘can1’
  • timeout (numerical) – Timeout value in seconds for recv_next_signals(). Defaults to None (blocking recv_next_signals).
Raises:
interfacename

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

close()[source]

Close the socket

recv_next_frame()[source]

Receive one CAN frame. Returns a CanFrame object.

send_frame(input_frame)[source]

Send a can frame (a CanFrame object)

set_receive_filters(framenumbers)[source]

Set the receive filters of the CAN interface (in the Linux kernel).

Parameters:framenumbers (list of int) – The CAN IDs to listen for.

Uses one CAN receive filter per CAN ID. It is used only if listening to fewer than MAX_NUMBER_OF_RAW_RECEIVE_FILTERS CAN IDs, otherwise it is silently ignoring kernel CAN ID filering.

To see the filters that are applied (in Ubuntu):

cat /proc/net/can/rcv*

can4python.cansignal module

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

Bases: object

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)
_check_signal_value_range(attributename, value)[source]
_get_overview_string()[source]

Generate an overview string, of length 64 bits.

Returns the tuple (outputstring, stopbit).

can4python.configuration module

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

Bases: object

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.

can4python.constants module

can4python.exceptions module

exception can4python.exceptions.CanException[source]

Bases: Exception

Base exception for CAN package

exception can4python.exceptions.CanTimeoutException[source]

Bases: can4python.exceptions.CanException

Timeout for CAN package

exception can4python.exceptions.CanNotFoundByKernelException[source]

Bases: can4python.exceptions.CanException

SocketCan in Linux kernel could probably not find the specified frame.

can4python.filehandler_kcd module

class can4python.filehandler_kcd.FilehandlerKcd[source]

Bases: object

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.

can4python.utilities module

can4python.utilities.calculate_backward_bitnumber(normal_bitnumber)[source]

Calculate the bit position in the “backward” numbering format.

Parameters:normal_bitnumber (int) – bit position in the standard format.
Raises:CanException – For wrong bitnumber. See CanException.
Returns:The bit position (int) in the “backward” numbering format.

The “backward” is a numbering scheme where the bits are numbered:

63,62 61,60,59,58,57,56  55,54,53,52,51,50,49,48  47,46 etc
Byte0                    Byte1                    Byte2

In full detail:

66665555 55555544 44444444 33333333 33222222 22221111 111111
32109876 54321098 76543210 98765432 10987654 32109876 54321098 76543210
Byte0    Byte1    Byte2    Byte3    Byte4    Byte5    Byte6    Byte7

For reference, the standard bit numbering is:

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

In full detail:

         111111   22221111 33222222 33333333 44444444 55555544 66665555
76543210 54321098 32109876 10987654 98765432 76543210 54321098 32109876
Byte0    Byte1    Byte2    Byte3    Byte4    Byte5    Byte6    Byte7
can4python.utilities.calculate_normal_bitnumber(backward_bitnumber)[source]

Calculate the bitnumber, from the bitnumber in backwards numbering scheme.

This is the inverse of calculate_backward_bitnumber().

Parameters:backward_bitnumber (int) – The bitnumber (in backwards numbering scheme)
Raises:CanException – For wrong bitnumber. See CanException.
Returns:The bit position (int) in the standard format.
can4python.utilities.generate_bit_byte_overview(inputstring, number_of_indent_spaces=4, show_reverse_bitnumbering=False)[source]

Generate a nice overview of a CAN frame.

Parameters:
  • inputstring (str) – String that should be printed. Should be 64 characters long.
  • number_of_indent_spaces (int) – Size of indentation
Raises:

ValueError when inputstring has wrong length.

Returns:

A multi-line string.

can4python.utilities.generate_can_integer_overview(value)[source]

Generate a nice overview of an integer, interpreted as a CAN frame/fr_def.

Parameters:value (int) – Integer representing the data of a CAN frame
Returns:A multi-line string.
can4python.utilities.can_bytes_to_int(input_bytes)[source]

Convert bytes to an integer (after padding the bytes).

Parameters:input_bytes (bytes object) – holds 0-8 bytes of data. Will be padded with empty bytes on right side.
Returns:An integer corresponding to 8 bytes of data.

Note: An input of b”” will be padded to b””. This corresponds to an integer of 72057594037927936.

can4python.utilities.int_to_can_bytes(dlc, dataint)[source]

Convert an integer to 8 bytes, and cut it from the left according to the dlc.

Parameters:
  • dlc (int) – how many bytes it should be encoded into
  • dataint (int) – holds 8 bytes of data

Returns a bytes object: 0-8 bytes of CAN data

For example a dataint value of 1 is converted to b’’. If the dlc is given as 1, then the return value will be b’‘.

can4python.utilities.twos_complement(value, bits)[source]

Calculate two’s complement for a value.

Parameters:
  • value (int) – input value (positive or negative)
  • bits (int) – field size

Returns a positive integer. If in the upper part of the range, it should be interpreted as negative.

The allowed input value range is -2**(bits-1) to +2**(bits-1)-1. For example, 8 bits gives a range of -128 to +127.

can4python.utilities.from_twos_complement(value, bits)[source]

Calculate the inverse (?) of two’s complement for a value.

Parameters:
  • value (int) – input value (positive)
  • bits (int) – field size

Returns a positive or negative integer, in the range range is -2**(bits-1) to +2**(bits-1)-1. For example, 8 bits gives an output range of -128 to +127.

can4python.utilities.split_seconds_to_full_and_part(seconds_float)[source]

Split a time value into full and fractional parts.

Parameters:seconds_float (float) – Number of seconds
Returns (seconds_full, useconds) which both are integers. They represent the time in
full seconds and microseconds respectively.
can4python.utilities.check_frame_id_and_format(frame_id, frame_format)[source]

Check the validity of frame_id.

Parameters:
  • frame_id (int) – frame_id to be checked
  • frame_format (str) – Frame format. Should be 'standard' or 'extended'.
can4python.utilities.get_busvalue_from_bytes(input_bytes, endianness, numberofbits, startbit)[source]

Get the busvalue from bytes.

Parameters:
  • input_bytes (bytes object) – up to 8 bytes of data
  • endianness (str) – ‘big’ or ‘little’
  • numberofbits (int) – Number of bits in the signal
  • startbit (int) – LSB in normal bit numbering

Returns the bus value, which is the bits interpreted as an unsigned integer. For example ‘0110’ is interpreted as the unsigned integer 6. Later, it will then be converted to whatever (maybe signed or unsigned integer).

can4python.utilities.get_shiftedvalue_from_busvalue(input_value, endianness, numberofbits, startbit)[source]

Get the shifted value from the bus value.

Parameters:
  • input_value (int) – Integer corresponding to the bus value.
  • endianness (str) – ‘big’ or ‘little’
  • numberofbits (int) – Number of bits in the signal
  • startbit (int) – LSB in normal bit numbering

Returns the shifted value, which later will be put into the frame using AND/OR operations together with a mask.

Earlier the physical value has been converted to a shifted value and then to a bus value. For example, a bus value input_value ‘0110’ is interpreted as the unsigned integer 6.

can4python.version module

Module contents