Accessing Kvaser CANlib from Python (1 of 3)

  • April 1, 2015
  • Magnus Carlsson

This is an update of an older blog post and is now taking advantage of the Python canlib package v1.6.

This is the first post in a 3-part series about using Python with Kvaser products:

  1. Accessing Kvaser CANlib from Python
  2. Using Python to connect to your remote device
  3. A more object oriented approach on accessing your Kvaser device from Python

Did you know that you can access Kvaser CANlib from Python? There have been Python wrappers for CANlib included in the Kvaser CANlib SDK for a while now, but beginning with version 1.5 they have gotten an overhaul and can now be used in a more pythonic way. The latest released version of the Python canlib package can be found on www.kvaser.com/download/.

To get an idea of how to use the package, see the example below on how to go bus on (and off again). In this example we have a Kvaser Memorator Pro 5xHS connected locally to the computer’s USB port.

Example of using the Python CANlib wrapper.

# 01_canlib_buson_off.py
from canlib import canlib
from canlib.canlib import ChannelData

channel = 0
chd = canlib.ChannelData(channel)
print("CANlib version: v{}".format(chd.dll_product_version))
print("canlib dll version: v{}".format(chd.dll_file_version))
print("Using channel: {ch}, EAN: {ean}".
   format(ch=chd.device_name, ean=chd.card_upc_no))

ch1 = canlib.openChannel(channel, canlib.canOPEN_ACCEPT_VIRTUAL)
ch1.setBusOutputControl(canlib.canDRIVER_NORMAL)
ch1.setBusParams(canlib.canBITRATE_1M)
ch1.busOn()
ch1.busOff()

Running the above code results in the following printout.

CANlib version: v5.23
canlib dll version: v8.23.477
Using channel: Kvaser Memorator Pro 5xHS (channel 0), EAN: 73-30130-00778-9

As veteran users of CANlib knows, the version number of the canlib.dll, here shown as v8.23.477, is not identical to the version number of the CANlib package, which in our case is v5.23.

The Python wrapper uses ctypes to interface with Kvaser CANlib. ctypes is a foreign function library for Python that provides C compatible data types and allows calling functions in DLLs or shared libraries. This means that it is possible to use the same Python package on Linux.

Comments?  Contact us directly at [email protected]

Author Image

Magnus Carlsson

Magnus Carlsson is a Software Developer for Kvaser AB and has developed firmware and software for Kv...