Python Can
Python Can
Python Can
Release 2.0.0
1 Installation 3
1.1 GNU/Linux dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Windows dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Installing python-can in development mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2 Configuration 5
2.1 In Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Configuration File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3 Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4 Interface Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3 Library API 7
3.1 Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.3 Listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.4 Broadcast Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.5 Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.6 Notifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
5 Scripts 43
5.1 can.logger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
5.2 can.player . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
i
6 Developer’s Overview 45
6.1 Contributing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
6.2 Creating a Release . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
6.3 Code Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
8 Known Bugs 49
ii
python-can, Release 2.0.0
The python-can library provides Controller Area Network support for Python, providing common abstractions to
different hardware devices, and a suite of utilities for sending and receiving messages on a CAN bus.
python-can runs any where Python runs; from high powered computers with commercial CAN to usb devices right
down to low powered devices running linux such as a BeagleBone or RaspberryPi.
More concretely, some example uses of the library:
• Passively logging what occurs on a CAN bus. For example monitoring a commercial vehicle using its OBD-II
port.
• Testing of hardware that interacts via CAN. Modules found in modern cars, motocycles, boats, and even
wheelchairs have had components tested from Python using this library.
• Prototyping new hardware modules or software algorithms in-the-loop. Easily interact with an existing bus.
• Creating virtual modules to prototype CAN bus communication.
Brief example of the library in action: connecting to a CAN bus, creating and sending a message:
5 def send_one():
6 bus = can.interface.Bus()
7 msg = can.Message(arbitration_id=0xc0ffee,
8 data=[0, 25, 0, 1, 3, 1, 4, 1],
9 extended_id=True)
10 try:
11 bus.send(msg)
12 print("Message sent on {}".format(bus.channel_info))
13 except can.CanError:
14 print("Message NOT sent")
15
16 if __name__ == "__main__":
17 send_one()
Contents:
Contents 1
python-can, Release 2.0.0
2 Contents
CHAPTER 1
Installation
As most likely you will want to interface with some hardware, you may also have to install platform dependencies. Be
sure to check any other specifics for your hardware in CAN Interface Modules.
Reasonably modern Linux Kernels (2.6.25 or newer) have an implementation of socketcan. This version of python-
can will directly use socketcan if called with Python 3.3 or greater, otherwise that interface is used via ctypes.
1.2.1 Kvaser
1.2.2 PCAN
Download and install the latest driver for your interface from PEAK-System’s download page.
3
python-can, Release 2.0.0
Note that PCANBasic API timestamps count seconds from system startup. To convert these to epoch times, the uptime
library is used. If it is not available, the times are returned as number of seconds from system startup. To install the
uptime library, run pip install uptime.
This library can take advantage of the Python for Windows Extensions library if installed. It will be used to get notified
of new messages instead of the CPU intensive polling that will otherwise have be used.
1.2.3 IXXAT
1.2.4 NI-CAN
1.2.5 neoVI
A “development” install of this package allows you to make changes locally or pull updates from the Mercurial
repository and use them without having to reinstall. Download or clone the source repository then:
4 Chapter 1. Installation
CHAPTER 2
Configuration
Usually this library is used with a particular CAN interface, this can be specified in code, read from configuration files
or environment variables.
See can.util.load_config() for implementation.
2.1 In Code
The can object exposes an rc dictionary which can be used to set the interface and channel before importing from
can.interfaces.
import can
can.rc['interface'] = 'socketcan'
can.rc['channel'] = 'vcan0'
can.rc['bitrate'] = 500000
from can.interfaces.interface import Bus
bus = Bus()
You can also specify the interface and channel for each Bus instance:
import can
5
python-can, Release 2.0.0
3. $HOME/.can
4. $HOME/.canrc
On Windows systems the config file is searched in the following paths:
1. ~/can.conf 1. can.ini (current working directory) 2. $APPDATA/can.ini
The configuration file sets the default interface and channel:
[default]
interface = <the name of the interface to use>
channel = <the channel to use by default>
bitrate = <the bitrate in bits/s to use by default>
Name Documentation
"socketcan" Socketcan
"kvaser" Kvaser’s CANLIB
"serial" CAN over Serial
"slcan" CAN over Serial / SLCAN
"ixxat" IXXAT Virtual CAN Interface
"pcan" PCAN Basic API
"usb2can" USB2CAN Interface
"nican" NI-CAN
"iscan" isCAN
"neovi" neoVI Interface
"vector" Vector
"virtual" Virtual
6 Chapter 2. Configuration
CHAPTER 3
Library API
The main objects are the BusABC and the Message. A form of CAN interface is also required.
Hint: Check the backend specific documentation for any implementation specific details.
3.1 Bus
The Bus class, as the name suggests, provides an abstraction of a CAN bus. The bus provides a wrapper around a
physical or virtual CAN Bus.
3.1.1 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.
3.1.2 API
7
python-can, Release 2.0.0
channel_info = 'unknown'
a string describing the underlying bus channel
flush_tx_buffer()
Discard every message that may be queued in the output buffer(s).
recv(timeout=None)
Block waiting for a message from the Bus.
Parameters timeout (float) – Seconds to wait for a message.
Returns None on timeout or a can.Message object.
send(msg, timeout=None)
Transmit a message to CAN bus. Override this method to enable the transmit path.
Parameters
• msg (can.Message) – A message object.
• timeout (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.
Raise can.CanError if the message could not be written.
send_periodic(msg, period, duration=None)
Start sending a message at a given period on this bus.
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
Return type
can.CyclicSendTaskABC
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.
set_filters(can_filters=None)
Apply filtering to all messages received by this Bus.
Calling without passing any filters will reset the applied filters.
Parameters can_filters (list) – A list of dictionaries each containing a “can_id” and a
“can_mask”.
3.1.3 Transmitting
Writing to the bus is done by calling the send() method and passing a Message object.
3.1.4 Receiving
Reading from the bus is achieved by either calling the recv() method or by directly iterating over the bus:
Alternatively the Listener api can be used, which is a list of Listener subclasses that receive notifications when
new messages arrive.
3.2 Message
3.2. Message 9
python-can, Release 2.0.0
One can instantiate a Message defining data, and optional arguments for all attributes such as arbitration ID,
flags, and timestamp.
The arbitration_id field in a CAN message may be either 11 bits (standard addressing, CAN 2.0A)
or 29 bits (extended addressing, CAN 2.0B) in length, and python-can exposes this difference with the
is_extended_id attribute.
arbitration_id
Type int
The frame identifier used for arbitration on the bus.
The arbitration ID can take an int between 0 and the maximum value allowed depending on the
is_extended_id flag (either 211 - 1 for 11-bit IDs, or 229 - 1 for 29-bit identifiers).
data
Type bytearray
The data parameter of a CAN message is exposed as a bytearray with length between 0 and 8.
dlc
Type int
The DLC (Data Link Count) parameter of a CAN message is an integer between 0 and 8 representing the
frame payload length.
Note: The DLC value does not necessarily define the number of bytes of data in a message.
Its purpose varies depending on the frame type - for data frames it represents the amount of data contained
in the message, in remote frames it represents the amount of data being requested.
is_extended_id
Type bool
This flag controls the size of the arbitration_id field.
>>> print(Message(extended_id=False))
Timestamp: 0.000000 ID: 0000 S DLC: 0
>>> print(Message(extended_id=True))
Timestamp: 0.000000 ID: 00000000 X DLC: 0
is_remote_frame
Type boolean
This boolean attribute indicates if the message is a remote frame or a data frame, and modifies the bit in
the CAN message’s flags field indicating this.
>>> print(Message(is_remote_frame=True))
Timestamp: 0.000000 ID: 00000000 X R DLC: 0
timestamp
Type float
The timestamp field in a CAN message is a floating point number representing when the message was
received since the epoch in seconds. Where possible this will be timestamped in hardware.
__str__()
A string representation of a CAN message:
>>> from can import Message
>>> test = Message()
>>> print(test)
Timestamp: 0.000000 ID: 00000000 X DLC: 0
>>> test2 = Message(data=[1, 2, 3, 4, 5])
>>> print(test2)
Timestamp: 0.000000 ID: 00000000 X DLC: 5 01 02 03 04
˓→05
3.2. Message 11
python-can, Release 2.0.0
• and data.
The flags field is represented as one, two or three letters:
• X if the is_extended_id attribute is set, otherwise S,
• E if the is_error_frame attribute is set,
• R if the is_remote_frame attribute is set.
The arbitration ID field is represented as either a four or eight digit hexadecimal number depending on the
length of the arbitration ID (11-bit or 29-bit).
Each of the bytes in the data field (when present) are represented as two-digit hexadecimal numbers.
3.3 Listeners
3.3.1 Listener
The Listener class is an “abstract” base class for any objects which wish to register to receive notifications of new
messages on the bus. A Listener can be used in two ways; the default is to call the Listener with a new message, or by
calling the method on_message_received.
Listeners are registered with Notifier object(s) which ensure they are notified whenever a new message is received.
Subclasses of Listener that do not override on_message_received will cause NotImplementedError to be thrown when
a message is received on the CAN bus.
class can.Listener
Bases: object
stop()
Override to cleanup any open resources.
3.3.2 BufferedReader
class can.BufferedReader
Bases: can.listener.Listener
A BufferedReader is a subclass of Listener which implements a message buffer: that is, when the can.
BufferedReader instance is notified of a new message it pushes it into a queue of messages waiting to be
serviced.
get_message(timeout=0.5)
Attempts to retrieve the latest message received by the instance. If no message is available it blocks for
given timeout or until a message is received (whichever is shorter),
Parameters timeout (float) – The number of seconds to wait for a new message.
Returns the Message if there is one, or None if there is not.
3.3.3 Logger
The can.Logger uses the following can.Listener types to create .asc, .csv and .db files with the messages
received.
class can.Logger
Bases: object
Logs CAN messages to a file.
The format is determined from the file format which can be one of:
• .asc: can.ASCWriter
• .blf can.BLFWriter
• .csv: can.CSVWriter
• .db: can.SqliteWriter
• other: can.Printer
Note this class itself is just a dispatcher, an object that inherits from Listener will be created when instantiating
this class.
3.3.4 Printer
class can.Printer(output_file=None)
Bases: can.listener.Listener
The Printer class is a subclass of Listener which simply prints any messages it receives to the terminal.
Parameters output_file – An optional file to “print” to.
3.3.5 CSVWriter
class can.CSVWriter(filename)
Bases: can.listener.Listener
Writes a comma separated text file of timestamp, arbitration id, flags, dlc, data for each messages received.
3.3.6 SqliteWriter
class can.SqliteWriter(filename)
Bases: can.listener.BufferedReader
Logs received CAN data to a simple SQL database.
The sqlite database may already exist, otherwise it will be created when the first message arrives.
Messages are internally buffered and written to the SQL file in a background thread.
Note: When the listener’s stop() method is called the thread writing to the sql file will continue to receive
and internally buffer messages if they continue to arrive before the GET_MESSAGE_TIMEOUT.
If the GET_MESSAGE_TIMEOUT expires before a message is received, the internal buffer is written out to the
sql file.
However if the bus is still saturated with messages, the Listener will continue receiving until the
MAX_TIME_BETWEEN_WRITES timeout is reached.
GET_MESSAGE_TIMEOUT = 0.25
Number of seconds to wait for messages from internal queue
3.3. Listeners 13
python-can, Release 2.0.0
MAX_TIME_BETWEEN_WRITES = 5
Maximum number of seconds to wait between writes to the database
ASCWriter logs CAN data to an ASCII log file compatible with other CAN tools such as Vector CANalyzer/CANoe
and other. Since no official specification exists for the format, it has been reverse- engineered from existing log files.
One description of the format can be found here.
class can.ASCWriter(filename, channel=1)
Bases: can.listener.Listener
Logs CAN data to an ASCII log file (.asc)
log_event(message, timestamp=None)
Add an arbitrary message to the log file.
stop()
Stops logging and closes the file.
ASCReader reads CAN data from ASCII log files .asc as further references can-utils can be used: asc2log, log2asc.
class can.ASCReader(filename)
Bases: object
Iterator of CAN messages from a ASC Logging File.
CanutilsLogWriter logs CAN data to an ASCII log file compatible with can-utils <https://github.com/linux-can/can-
utils> As specification following references can-utils can be used: asc2log, log2asc.
class can.io.CanutilsLogWriter(filename, channel=’vcan0’)
Bases: can.listener.Listener
Logs CAN data to an ASCII log file (.log) compatible to candump -L
stop()
Stops logging and closes the file.
CanutilsLogReader reads CAN data from ASCII log files .log
class can.io.CanutilsLogReader(filename)
Bases: object
Iterator of CAN messages from a .log Logging File (candump -L).
.log-format looks like this: (0.0) vcan0 001#8d00100100820100
Implements support for BLF (Binary Logging Format) which is a proprietary CAN log format from Vector Informatik
GmbH.
The data is stored in a compressed format which makes it very compact.
class can.BLFWriter(filename, channel=1)
Bases: can.listener.Listener
Logs CAN data to a Binary Logging File compatible with Vector’s tools.
COMPRESSION_LEVEL = 9
ZLIB compression level
MAX_CACHE_SIZE = 131072
Max log container size of uncompressed data
log_event(text, timestamp=None)
Add an arbitrary message to the log file as a global marker.
Parameters
• text (str) – The group name of the marker.
• timestamp (float) – Absolute timestamp in Unix timestamp format. If not given, the
marker will be placed along the last message.
stop()
Stops logging and closes the file.
class can.BLFReader(filename)
Bases: object
Iterator of CAN messages from a Binary Logging File.
Only CAN messages and error frames are supported. Other object types are silently ignored.
The broadcast manager isn’t yet supported by all interfaces. Currently SockerCAN and IXXAT are supported at least
partially. It allows the user to setup periodic message jobs.
If periodic transmission is not supported natively, a software thread based scheduler is used as a fallback.
This example shows the ctypes socketcan using the broadcast manager:
1 #!/usr/bin/env python3
2 """
3 This example exercises the periodic sending capabilities.
4
7 python3 -m examples.cyclic
8
9 """
10
11 import logging
12 import time
13
14 import can
15 logging.basicConfig(level=logging.INFO)
16
17
18 def simple_periodic_send(bus):
19 """
20 Sends a message every 20ms with no explicit timeout
21 Sleeps for 2 seconds then stops the task.
22 """
23 print("Starting to send a message every 200ms for 2s")
24 msg = can.Message(arbitration_id=0x123, data=[1, 2, 3, 4, 5, 6], extended_
˓→id=False)
31
32 def limited_periodic_send(bus):
33 print("Starting to send a message every 200ms for 1s")
34 msg = can.Message(arbitration_id=0x12345678, data=[0, 0, 0, 0, 0, 0], extended_
˓→id=True)
41 time.sleep(1.5)
42 print("stopped cyclic send")
43
44
45 def test_periodic_send_with_modifying_data(bus):
46 print("Starting to send a message every 200ms. Initial data is ones")
47 msg = can.Message(arbitration_id=0x0cf02200, data=[1, 1, 1, 1])
48 task = bus.send_periodic(msg, 0.20)
49 if not isinstance(task, can.ModifiableCyclicTaskABC):
50 print("This interface doesn't seem to support modification")
51 task.stop()
52 return
53 time.sleep(2)
54 print("Changing data of running task to begin with 99")
55 msg.data[0] = 0x99
56 task.modify_data(msg)
57 time.sleep(2)
58
59 task.stop()
60 print("stopped cyclic send")
61 print("Changing data of stopped task to single ff byte")
62 msg.data = bytearray([0xff])
63 msg.dlc = 1
64 task.modify_data(msg)
65 time.sleep(1)
66 print("starting again")
67 task.start()
68 time.sleep(1)
69 task.stop()
70 print("done")
71
72
73 # Will have to consider how to expose items like this. The socketcan
74 # interfaces will continue to support it... but the top level api won't.
75 # def test_dual_rate_periodic_send():
76 # """Send a message 10 times at 1ms intervals, then continue to send every 500ms""
˓→"
81 #
82 # print("Changing data[0] = 0x42")
83 # msg.data[0] = 0x42
84 # task.modify_data(msg)
85 # time.sleep(2)
86 #
87 # task.stop()
88 # print("stopped cyclic send")
89 #
90 # time.sleep(2)
91 #
92 # task.start()
93 # print("starting again")
94 # time.sleep(2)
95 # task.stop()
96 # print("done")
97
98
99 if __name__ == "__main__":
100
103
114 simple_periodic_send(bus)
115
116 bus.send(reset_msg)
117
118 limited_periodic_send(bus)
119
120 test_periodic_send_with_modifying_data(bus)
121
126 bus.shutdown()
127
128
129 time.sleep(2)
3.5 Utilities
Note: If you pass "socketcan" this automatically selects between the native and ctypes version.
Parameters
• path – Optional path to config file.
• config – A dict which may set the ‘interface’, and/or the ‘channel’, or neither.
Returns
A config dictionary that should contain ‘interface’ & ‘channel’:
{
'interface': 'python-can backend interface to use',
'channel': 'default channel to use',
}
Note None will be used if all the options are exhausted without finding a value.
can.util.load_environment_config()
Loads config dict from environmental variables (if set):
• CAN_INTERFACE
• CAN_CHANNEL
• CAN_BITRATE
can.util.load_file_config(path=None)
Loads configuration from file with following content:
[default]
interface = socketcan
channel = can0
Parameters path – path to config file. If not specified, several sensible default locations are tried
depending on platform.
can.util.set_logging_level(level_name=None)
Set the logging level for the “can” logger. Expects one of: ‘critical’, ‘error’, ‘warning’, ‘info’, ‘debug’, ‘subde-
bug’
3.6 Notifier
3.6. Notifier 19
python-can, Release 2.0.0
python-can hides the low-level, device-specific interfaces to controller area network adapters in interface dependant
modules. However as each hardware device is different, you should carefully go through your interface’s documenta-
tion.
The available interfaces are:
4.1 Socketcan
There are two implementations of socketcan backends. One written with ctypes to be compatible with Python 2 and
3, and one written for future versions of Python3 which feature native support.
socketcan_ctypes.py is a ctypes wrapper class around libc. It contains replications of constants and structures found in
various linux header files. With Python 3.3, much of the functionality of this library is likely to be available natively
in the Python socket module.
Bus
21
python-can, Release 2.0.0
Calling without passing any filters will reset the applied filters.
Parameters can_filters (list) – A list of dictionaries each containing a “can_id” and a
“can_mask”.
Broadcast-Manager
The socketcan_ctypes interface implements thin wrappers to the linux broadcast manager socket api. This
allows the cyclic transmission of CAN messages at given intervals. The overhead for periodic message sending is
extremely low as all the heavy lifting occurs within the linux kernel.
send_periodic()
Internals
createSocket
can.interfaces.socketcan.socketcan_ctypes.createSocket(protocol=1)
This function creates a RAW CAN socket.
The socket returned needs to be bound to an interface by calling bindSocket().
Parameters protocol (int) – The type of the socket to be bound. Valid values include
CAN_RAW and CAN_BCM
Returns
0 protocol invalid
-1 socket creation unsuccessful
socketID successful creation
bindSocket
can.interfaces.socketcan.socketcan_ctypes.bindSocket(socketID, channel_name)
Binds the given socket to the given interface.
Parameters
• socketID (int) – The ID of the socket to be bound
• channel_name (str) – The interface name to find and bind.
Returns
The error code from the bind call.
0 protocol invalid
-1 socket creation unsuccessful
connectSocket
can.interfaces.socketcan.socketcan_ctypes.connectSocket(socketID, channel_name)
Connects the given socket to the given interface.
Parameters
• socketID (int) – The ID of the socket to be bound
• channel_name (str) – The interface name to find and bind.
Returns The error code from the bind call.
capturePacket
can.interfaces.socketcan.socketcan_ctypes.capturePacket(socketID)
Captures a packet of data from the given socket.
Parameters socketID (int) – The socket to read from
Returns
A dictionary with the following keys:
• ”CAN ID” (int)
• ”DLC” (int)
• ”Data” (list)
• ”Timestamp” (float)
4.1. Socketcan 23
python-can, Release 2.0.0
Bus
Internals
createSocket
can.interfaces.socketcan.socketcan_native.createSocket(can_protocol=None)
Creates a CAN socket. The socket can be BCM or RAW. The socket will be returned unbound to any interface.
Parameters can_protocol (int) –
The protocol to use for the CAN socket, either:
• socket.CAN_RAW
• socket.CAN_BCM.
Returns
• -1 if socket creation unsuccessful
• socketID - successful creation
bindSocket
can.interfaces.socketcan.socketcan_native.bindSocket(sock, channel=’can0’)
Binds the given socket to the given interface.
Parameters socketID (Socket) – The ID of the socket to be bound
Raise OSError if the specified interface isn’t found.
captureMessage
can.interfaces.socketcan.socketcan_native.captureMessage(sock)
Captures a message from given socket.
Parameters sock (socket) – The socket to read a message from.
Returns The received message, or None on failure.
Unless you’re running Python3.3 or lower the recommended backend is socketcan_native. For Python2.7 and Python3
<3.4, the available backend is socketcan_ctypes.
The full documentation for socketcan can be found in the kernel docs at networking/can.txt. The CAN network driver
provides a generic interface to setup, configure and monitor CAN devices. To configure bit-timing parameters use the
program ip.
The virtual CAN interfaces allow the transmission and reception of CAN frames without real CAN controller hard-
ware. Virtual CAN network devices are usually named ‘vcanX’, like vcan0 vcan1 vcan2.
To create a virtual can interface using socketcan run the following:
Real Device
vcan should be substituted for can and vcan0 should be substituted for can0 if you are using real hardware. Setting
the bitrate can also be done at the same time, for example to enable an existing can0 interface with a bitrate of 1MB:
The can-utils library for linux includes a script cansend which is useful to send known payloads. For example to send
a message on vcan0:
4.1. Socketcan 25
python-can, Release 2.0.0
CAN Errors
A device may enter the “bus-off” state if too many errors occurred on the CAN bus. Then no more messages are
received or sent. An automatic bus-off recovery can be enabled by setting the “restart-ms” to a non-zero value, e.g.:
Alternatively, the application may realize the “bus-off” condition by monitoring CAN error frames and do a restart
when appropriate with the command:
ifconfig
4.1.4 Wireshark
Wireshark supports socketcan and can be used to debug python-can messages. Fire it up and watch your new interface.
To spam a bus:
import time
import can
bustype = 'socketcan_native'
channel = 'vcan0'
def producer(id):
""":param id: Spam the bus with messages including the data id."""
bus = can.interface.Bus(channel=channel, bustype=bustype)
for i in range(10):
msg = can.Message(arbitration_id=0xc0ffee, data=[id, i, 0, 1, 3, 1, 4, 1],
˓→extended_id=False)
bus.send(msg)
# Issue #3: Need to keep running to ensure the writing threads stay alive. ?
time.sleep(1)
producer(10)
Reading a single CAN message off of the bus is simple with the bus.recv() function:
import can
can_interface = 'vcan0'
bus = can.interface.Bus(can_interface, bustype='socketcan_native')
message = bus.recv()
By default, this performs a blocking read, which means bus.recv() won’t return until a CAN message shows up
on the socket. You can optionally perform a blocking read with a timeout like this:
if message is None:
print('Timeout occurred, no message.')
4.1. Socketcan 27
python-can, Release 2.0.0
If you set the timeout to 0.0, the read will be executed as non-blocking, which means bus.recv(0.0) will return
immediately, either with a Message object or None, depending on whether data was available on the socket.
4.2.1 Bus
Backend Configuration
Parameters
• bitrate (int) – Bitrate of channel in bit/s
• tseg1 (int) – Time segment 1, that is, the number of quanta from (but not including) the
Sync Segment to the sampling point. If this parameter is not given, the Kvaser driver will
try to choose all bit timing parameters from a set of defaults.
• tseg2 (int) – Time segment 2, that is, the number of quanta from the sampling point to
the end of the bit.
• sjw (int) – The Synchronisation Jump Width. Decides the maximum number of time
quanta that the controller can resynchronise every bit.
• no_samp (int) – Either 1 or 3. Some CAN controllers can also sample each bit three
times. In this case, the bit will be sampled three quanta in a row, with the last sample being
taken in the edge between TSEG1 and TSEG2. Three samples should only be used for
relatively slow baudrates.
• driver_mode (bool) – Silent or normal.
• single_handle (bool) – Use one Kvaser CANLIB bus handle for both reading and
writing. This can be set if reading and/or writing is done from one thread.
• receive_own_messages (bool) – If messages transmitted should also be received
back. Only works if single_handle is also False. If you want to receive messages from other
applications on the same computer, set this to True or set single_handle to True.
flash(flash=True)
Turn on or off flashing of the device’s LED for physical identification purposes.
flush_tx_buffer()
Wipeout the transmit buffer on the Kvaser.
recv(timeout=None)
Read a message from kvaser device.
set_filters(can_filters=None)
Apply filtering to all messages received by this Bus.
Calling without passing any filters will reset the applied filters.
Since Kvaser only supports setting one filter per handle, the filtering will be disabled if more than one filter
is requested.
Parameters can_filters (list) – A list of dictionaries each containing a “can_id”,
“can_mask” and “extended”.
4.2.2 Internals
The Kvaser Bus object with a physical CAN Bus can be operated in two modes; single_handle mode with one
shared bus handle used for both reading and writing to the CAN bus, or with two separate bus handles. Two separate
handles are needed if receiving and sending messages are done in different threads (see Kvaser documentation).
Warning: Any objects inheriting from Bus should not directly use the interface handle(/s).
Message filtering
The Kvaser driver and hardware only supports setting one filter per handle. If one filter is requested, this is will be
handled by the Kvaser driver. If more than one filter is needed, these will be handled in Python code in the recv
method. If a message does not match any of the filters, recv() will return None.
A text based interface. For example use over serial ports like /dev/ttyS1 or /dev/ttyUSB0 on Linux machines
or COM1 on Windows. The interface is a simple implementation that has been used for recording CAN traces.
Note: The properties extended_id, is_remote_frame and is_error_frame from the class can.Message are not in use.
These interface will not send or receive flags for this properties.
4.3.1 Bus
• channel (str) – The serial device to open. For example “/dev/ttyS1” or “/dev/ttyUSB0”
on Linux or “COM1” on Windows systems.
• baudrate (int) – Baud rate of the serial device in bit/s (default 115200).
Note: Some serial port implementations don’t care about the baud rate.
• timeout (float) – Timeout for the serial device in seconds (default 0.1).
recv(timeout=None)
Read a message from the serial device.
Parameters timeout – This parameter will be ignored. The timeout value of the channel is
used.
Returns
Received message.
Note: Flags like extended_id, is_remote_frame and is_error_frame will not be set over this
function, the flags in the return message are the default values.
• timeout – This parameter will be ignored. The timeout value of the channel is used.
shutdown()
Close the serial interface.
4.3.2 Internals
The frames that will be sent and received over the serial interface consist of six parts. The start and the stop byte for
the frame, the timestamp, DLC, arbitration ID and the payload. The payload has a variable length of between 0 and
8 bytes, the other parts are fixed. Both, the timestamp and the arbitration ID will be interpreted as 4 byte unsigned
integers. The DLC is also an unsigned integer with a length of 1 byte.
CAN message
Arbitration ID Payload
1 0x11 0x22 0x33 0x44 0x55 0x66 0x77 0x88
Serial frame
Start of Timestamp DLC Arbitration ID Payload End of
frame frame
0xAA 0x66 0x73 0x00 0x08 0x01 0x00 0x00 0x11 0x22 0x33 0x44 0x55 0x66 0xBB
0x00 0x00 0x77 0x88
CAN message
Arbitration ID Payload
1 0x11
Serial frame
Start of frame Timestamp DLC Arbitration ID Payload End of frame
0xAA 0x66 0x73 0x00 0x00 0x01 0x01 0x00 0x00 0x00 0x11 0xBB
CAN message
Arbitration ID Payload
1 None
Serial frame
Start of frame Timestamp DLC Arbitration ID End of frame
0xAA 0x66 0x73 0x00 0x00 0x00 0x01 0x00 0x00 0x00 0xBBS
A text based interface: compatible to slcan-interfaces (slcan ASCII protocol) should also support LAWICEL direct.
These interfaces can also be used with socketcan and slcand with Linux. This driver directly uses the serial port, it
makes slcan-compatible interfaces usable with Windows also. Hint: Arduino-Interface could easyly be build https:
//github.com/latonita/arduino-canbus-monitor
Usage: use port[@baurate] to open the device. For example use /dev/ttyUSB0@115200 or COM4@9600
4.4.1 Bus
4.4.2 Internals
Note: The Linux ECI SDK is currently unsupported, however on Linux some devices are supported with Socketcan.
The send_periodic() method is supported natively through the on-board cyclic transmit list. Modifying cyclic
messages is not possible. You will need to stop it, then start a new periodic message.
4.5.1 Bus
[default]
interface = ixxat
channel = 0
Python-can will search for the first IXXAT device available and open the first channel. interface and channel
parameters are interpreted by frontend can.interfaces.interface module, while the following parameters
are optional and are interpreted by IXXAT implementation.
• bitrate (default 500000) Channel bitrate
• UniqueHardwareId (default first device) Unique hardware ID of the IXXAT device
4.5.3 Internals
The IXXAT BusABC object is a farly straightforward interface to the IXXAT VCI library. It can open a specific device
ID or use the first one found.
The frame exchange do not involve threads in the background but is explicitly instantiated by the caller.
• recv() is a blocking call with optional timeout.
• send() is not blocking but may raise a VCIError if the TX FIFO is full
RX and TX FIFO sizes are configurable with rxFifoSize and txFifoSize options, defaulting at 16 for both.
The CAN filters act as a “whitelist” in IXXAT implementation, that is if you supply a non-empty filter list you must
explicitly state EVERY frame you want to receive (including RTR field). The can_id/mask must be specified according
to IXXAT behaviour, that is bit 0 of can_id/mask parameters represents the RTR field in CAN frame. See IXXAT VCI
documentation, section “Message filters” for more info.
Hint: Module uses can.ixxat logger and at DEBUG level logs every frame sent or received. It may be too verbose
for your purposes.
Warning: This PCAN documentation is a work in progress. Feedback and revisions are most welcome!
4.6.1 Configuration
[default]
interface = pcan
channel = PCAN_USBBUS1
4.6.2 Bus
4.7.1 OVERVIEW
The USB2CAN is a cheap CAN interface based on an ARM7 chip (STR750FV2). There is support for this device on
Linux through the Socketcan interface and for Windows using this usb2can interface.
Support though windows is achieved through a DLL very similar to the way the PCAN functions. The API is called
CANAL (CAN Abstraction Layer) which is a separate project designed to be used with VSCP which is a socket like
messaging system that is not only cross platform but also supports other types of devices. This device can be used
through one of three ways 1)Through python-can 2)CANAL API either using the DLL and C/C++ or through the
python wrapper that has been added to this project 3)VSCP Using python-can is strongly suggested as with little extra
work the same interface can be used on both Windows and Linux.
1. To install on Windows download the USB2CAN Windows driver. It is compatible with XP, Vista, Win7,
Win8/8.1. (Written against driver version v1.0.2.1)
2. Install the appropriate version of pywin32 (win32com)
3. Download the USB2CAN CANAL DLL from the USB2CAN website. Place this in either the same directory you are runni
(Written against CANAL DLL version v1.0.6)
• usb2canabstractionlayer.py This file is only a wrapper for the CANAL API that the interface ex-
pects. There are also a couple of constants here to try and make dealing with the bitwise operations for
flag setting a little easier. Other than that this is only the CANAL API. If a programmer wanted to work
with the API directly this is the file that allows you to do this. The CANAL project does not provide this
wrapper and normally must be accessed with C.
• usb2canInterface.py This file provides the translation to and from the python-can library to the CANAL
API. This is where all the logic is and setup code is. Most issues if they are found will be either found here
or within the DLL that is provided
• serial_selector.py See the section below for the reason for adding this as it is a little odd. What
program does is if a serial number is not provided to the usb2canInterface file this program does WMI
(Windows Management Instrumentation) calls to try and figure out what device to connect to. It then
returns the serial number of the device. Currently it is not really smart enough to figure out what to do if
there are multiple devices. This needs to be changed if people are using more than one interface.
There are a few things that are kinda strange about this device and are not overly obvious about the code or things that
are not done being implemented in the DLL.
1. You need the Serial Number to connect to the device under Windows. This is part of the “setup string” that configures the
Warning: Currently message filtering is not implemented. Contributions are most welcome!
4.7.6 Bus
shutdown()
Shut down the device safely
4.7.7 Internals
class can.interfaces.usb2can.Usb2CanAbstractionLayer
A low level wrapper around the usb2can library.
Documentation: http://www.8devices.com/media/products/usb2can/downloads/CANAL_API.pdf
blocking_receive(handle, msg, timeout)
blocking_send(handle, msg, timeout)
close(handle)
get_library_version()
get_statistics(handle, CanalStatistics)
get_status(handle, CanalStatus)
get_vendor_string()
get_version()
open(pConfigureStr, flags)
receive(handle, msg)
send(handle, msg)
4.8 NI-CAN
Warning: NI-CAN only seems to support 32-bit architectures so if the driver can’t be loaded on a 64-bit Python,
try using a 32-bit version instead.
Warning: CAN filtering has not been tested throughly and may not work as expected.
4.8.1 Bus
4.8. NI-CAN 37
python-can, Release 2.0.0
• log_errors (bool) – If True, communication errors will appear as CAN messages with
is_error_frame set to True and arbitration_id will identify the error (default
True)
Raises can.interfaces.nican.NicanError – If starting communication fails
flush_tx_buffer()
Resets the CAN chip which includes clearing receive and transmit queues.
recv(timeout=None)
Read a message from NI-CAN.
Parameters timeout (float) – Max time to wait in seconds or None if infinite
Returns The CAN message or None if timeout
Return type can.Message
Raises can.interfaces.nican.NicanError – If reception fails
send(msg, timeout=None)
Send a message to NI-CAN.
Parameters msg (can.Message) – Message to send
Raises can.interfaces.nican.NicanError – If writing to transmit buffer fails. It
does not wait for message to be ACKed currently.
shutdown()
Close object.
exception can.interfaces.nican.NicanError(function, error_code, arguments)
Bases: can.CanError
Error from NI-CAN driver.
arguments = None
Arguments passed to function
error_code = None
Status code
function = None
Function that failed
4.9 isCAN
Interface for isCAN from Thorsis Technologies GmbH, former ifak system GmbH.
4.9.1 Bus
isCAN interface
Parameters
• channel (int) – Device number
• bitrate (int) – Bitrate in bits/s
• poll_interval (float) – Poll interval in seconds when reading messages
exception can.interfaces.iscan.IscanError(function, error_code, arguments)
Bases: can.CanError
arguments = None
Arguments passed to function
error_code = None
Status code
function = None
Function that failed
Warning: This neoVI documentation is a work in progress. Feedback and revisions are most welcome!
Interface to Intrepid Control Systems neoVI API range of devices via pyneovi wrapper on Windows.
Note: This interface is not supported on Linux, however on Linux neoVI devices are supported via Socketcan with
ICS Kernel-mode SocketCAN module for Intrepid devices and icsscand
4.10.1 Installation
This neoVI interface requires the installation of the ICS neoVI DLL and pyneovi package.
• Download and install the Intrepid Product Drivers Intrepid Product Drivers
• Install pyneovi using pip and the pyneovi bitbucket repo:
4.10.2 Configuration
[default]
interface = neovi
channel = 1
4.10.3 Bus
4.11 Vector
4.11.1 Bus
4.12 Virtual
The virtual interface can be used as a way to write OS and driver independent tests.
A virtual CAN bus that can be used for automatic tests. Any Bus instances connecting to the same channel (in the
same python program) will get each others messages.
import can
4.12. Virtual 41
python-can, Release 2.0.0
Scripts
5.1 can.logger
optional arguments:
-h, --help show this help message and exit
-f LOG_FILE, --file_name LOG_FILE
Path and base log filename, extension can be .txt,
.asc, .csv, .db, .npz
-v How much information do you want to see at the command
line? You can add several of these e.g., -vv is DEBUG
-c CHANNEL, --channel CHANNEL
Most backend interfaces require some sort of channel.
For example with the serial interface the channel
might be a rfcomm device: "/dev/rfcomm0" With the
socketcan interfaces valid channel examples include:
"can0", "vcan0"
-i {iscan,slcan,virtual,socketcan_ctypes,usb2can,ixxat,socketcan_native,kvaser,
˓→neovi,vector,nican,pcan,serial,remote,socketcan}, --interface {iscan,slcan,virtual,
˓→socketcan_ctypes,usb2can,ixxat,socketcan_native,kvaser,neovi,vector,nican,pcan,
˓→serial,remote,socketcan}
43
python-can, Release 2.0.0
5.2 can.player
positional arguments:
input-file The file to replay. Supported types: .db, .blf
optional arguments:
-h, --help show this help message and exit
-f LOG_FILE, --file_name LOG_FILE
Path and base log filename, extension can be .txt,
.asc, .csv, .db, .npz
-v Also print can frames to stdout. You can add several
of these to enable debugging
-c CHANNEL, --channel CHANNEL
Most backend interfaces require some sort of channel.
For example with the serial interface the channel
might be a rfcomm device: "/dev/rfcomm0" With the
socketcan interfaces valid channel examples include:
"can0", "vcan0"
-i {kvaser,virtual,slcan,nican,neovi,ixxat,serial,usb2can,socketcan_ctypes,remote,
˓→socketcan_native,iscan,vector,pcan,socketcan}, --interface {kvaser,virtual,slcan,
˓→nican,neovi,ixxat,serial,usb2can,socketcan_ctypes,remote,socketcan_native,iscan,
˓→vector,pcan,socketcan}
44 Chapter 5. Scripts
CHAPTER 6
Developer’s Overview
6.1 Contributing
45
python-can, Release 2.0.0
Module Description
interfaces Contains interface dependent code.
bus Contains the interface independent Bus object.
CAN Contains modules to emulate a CAN system, such as a time stamps, read/write streams and
listeners.
message Contains the interface independent Message object.
notifier An object which can be used to notify listeners.
broadcastman- Contains interface independent broadcast manager code.
ager
7.1 Background
Originally written at Dynamic Controls for internal use testing and prototyping wheelchair components.
Maintenance was taken over and the project was open sourced by Brian Thorne in 2010.
7.2 Acknowledgements
Originally written by Ben Powell as a thin wrapper around the Kvaser SDK to support the leaf device.
Support for linux socketcan was added by Rose Lu as a summer coding project in 2011. The socketcan interface was
helped immensely by Phil Dixon who wrote a leaf-socketcan driver for Linux.
The pcan interface was contributed by Albert Bloomfield in 2013.
The usb2can interface was contributed by Joshua Villyard in 2015
The IXXAT VCI interface was contributed by Giuseppe Corbelli and funded by Weightpack in 2016
The NI-CAN and virtual interfaces plus the ASCII and BLF loggers were contributed by Christian Sandberg in 2016
and 2017. The BLF format is based on a C++ library by Toby Lorenz.
The slcan interface, ASCII listener and log logger and listener were contributed by Eduard Bröcker in 2017.
The ‘socket’ module contains support for SocketCAN from Python 3.3.
From Python 3.4 broadcast management commands are natively supported.
47
python-can, Release 2.0.0
Known Bugs
See the project bug tracker on github. Patches and pull requests very welcome!
Documentation generated
Jan 16, 2018
49
python-can, Release 2.0.0
c
can, 9
can.util, 18
51
python-can, Release 2.0.0
C F
can (module), 9 flash() (can.interfaces.kvaser.canlib.KvaserBus method),
can.util (module), 18 28
CanutilsLogReader (class in can.io), 14 flash() (can.interfaces.pcan.PcanBus method), 35
CanutilsLogWriter (class in can.io), 14 flush_tx_buffer() (can.BusABC method), 8
captureMessage() (in module flush_tx_buffer() (can.interfaces.ixxat.IXXATBus
can.interfaces.socketcan.socketcan_native), method), 33
25 flush_tx_buffer() (can.interfaces.kvaser.canlib.KvaserBus
capturePacket() (in module method), 28
can.interfaces.socketcan.socketcan_ctypes), 23 flush_tx_buffer() (can.interfaces.nican.NicanBus
channel_info (can.BusABC attribute), 8 method), 38
function (can.interfaces.iscan.IscanError attribute), 39
53
python-can, Release 2.0.0
54 Index
python-can, Release 2.0.0
T
timestamp (can.Message attribute), 11
U
Usb2CanAbstractionLayer (class in
can.interfaces.usb2can), 37
Usb2canBus (class in can.interfaces.usb2can), 36
V
VectorBus (class in can.interfaces.vector), 40
VectorError, 40
Index 55