When working in the Embedded field, one often encounters situation where the hardware will not be available and the software should be developed. Or let say the software development should happen independant of the hardware availability. There are many reasons why this happens but it defintely happens. Some use emulator to run the entire operating system, some use wrapper functions to cover the hardware calls and simulate rest of the code. There are many solutions depending on the problem. One of the problem what I recently encountered was with CAN bus. I was required to code an application which uses a CAN bus but without a real hardware which has a CAN bus in it. In this case you can use wrapper calls, or get a USB CAN dongle and use it instead. I was trying to find a different one. I often read lkml.org and once I simply brushed through lines talking about virtual CAN. But that was quite sometime back so I vaguely searched and I got the solution.And Yes its virtual CAN or VCAN like “Yes VCAN” Lol.
In Linux CAN interface is handled using SocketCAN where a CAN bus is viewed as a Berkeley socket. A CAN interface can be configured just like an Ethernet interface. If you have a CAN interface in your board and if Linux detects it, then you can view it like this
$ /sbin/ifconfig -a
In case you dont have any hardware CAN, then you can create a virtual CAN interface and use it exactly like standard CAN interface. This is how you create a virtual can. I tried these commands in a Debian LXDE Desktop which by default had CAN Driver installed as part of the kernel modules.
#ip link add dev can0 type vcan
#ip link set up can0
The modprobe command loads the kernel module by resolving dependency, the ip command is used to configure device, routes and policy of a network device. For CAN devices you can configure bitrate too but since Im using the virtual CAN these things dont matter much virtually.
Install CAN utilities as follows
#apt-get install can-utils
Dump the CAN traffic using candump. This tool prints everything that comes out of CAN bus which it is listening to.
Send some data using cansend
$cansend can0 5A1#18.104.22.168
Interestingly since CAN is a network interface you can also use Wireshark to sniff the packets. If you want to simulate a stream of CAN packets then checkout canplayer.