Setting SocketCAN bitrate programmatically

3.5k views Asked by At

I'm using SocketCAN on my system. Is there a way to set the CAN interface bitrate programmatically and not from the command line. An example would be helpful.

Thank you.

2

There are 2 answers

1
Fusho On

Yes it is possible. Use NETLINK sockets, it is what ip uses.

Unfortunately, I do not know of any avaiable-easy example, but you could check the source code of ip.

Alternatively, you could use libsocketcan, which is a nice wrapper around netlink sockets for CAN.

0
fblack23 On

A little example for Qt (C++). Bitrate is set via QProcess. The CAN-Service must be stopped, then the bitrate can be configured, than CAN-Service must be started agein:

#include <QProcess>
#include <QString>

CO_set_bitrate(char const *can_device) //can_device for example "can0"
{
  QProcess set_bitrate;
  QStringList bitrate_args;
  QStringList stop_args;
  QStringList start_args;

  char const *can_bitrate = "500000"; //Set Bitrate

  stop_args.clear();
  stop_args<<"stop"<<can_device<<".service";

  start_args.clear();
  start_args<<"start"<<can_device<<".service";

  bitrate_args.clear();
  bitrate_args<<"link"<<"set"<<can_device<<"up"<<"type"<<"can"<<"bitrate"<<can_bitrate;

//Stop the CAN-Service
  set_bitrate.start("systemctl", stop_args, QIODevice::WriteOnly);
  set_bitrate.waitForFinished(-1);

//Set Bitrate
  set_bitrate.start( "ip", bitrate_args, QIODevice::WriteOnly); //Starts execution of command
  set_bitrate.waitForFinished(-1);

//Restart CAN-Service
  set_bitrate.start("systemctl", start_args, QIODevice::WriteOnly);
  set_bitrate.waitForFinished(-1);
  }