linuxmultithreadingpython-multithreadingcan-buspython-can

Simple consumer producer example for sending and receiving CAN messages does not receive messages


I was just trying to use a virtual can device vcan0 under linux and the python-can module to get acquainted with programming and debugging over the CAN bus.

I devised a simple looking program with two threads, where one thread should produce can messages, that the other thread should consume. Unfortunately, not a single message is consumed by the consumer thread, and I'm a bit baffled of the reason.

import can
import time
import threading

bus=can.interface.Bus(bustype='socketcan', channel='vcan0')

def producer():
    for i in range(10):
       msgProduced=can.Message(0., 20, data=[0,1,2,3])
       bus.send(msgProduced)
 
def consumer():
    for i in range(10):
       msgRecv=bus.recv(timeout=0.1)
       print(msgRecv)

producerThread=threading.Thread(target=producer)
consumerThread=threading.Thread(target=consumer)
producerThread.start()
consumerThread.start()
producerThread.join()
consumerThread.join()

bus.shutdown()

Setting up the vcan0 interface is a easy after installing virtual can device drivers:

sudo modprobe vcan
sudo ip link add dev vcan0 type vcan
sudo ip link set up vcan0

Solution

  • By default, CAN frames sent by a SocketCAN bus are not received by that bus. To make this work, set the receive_own_messages parameter to True when creating the bus. See https://python-can.readthedocs.io/en/master/interfaces/socketcan.html#can.interfaces.socketcan.SocketcanBus.