Let's simulate CAN communication used for in-vehicle embedded applications in a PC. You can read more about CAN in the article below. https://qiita.com/fattolys/items/e8f8081d3cb42d7da0f6
The following is the network configuration of the system created this time. Throw a CAN packet from Nord2 to Nord1.
Create a virtual CAN interface with the following command.
$ modprobe vcan
$ sudo ip link add dev vcan0 type vcan
$ sudo ip link set up vcan0
If you hit ifconfig, you can see that vcan0 is added as shown below.
$ ifconfig
vcan0: flags=193<UP,RUNNING,NOARP> mtu 72
unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 txqueuelen 1000 (UNSPEC)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
Nord 1 will display the packets coming to vcan 0 sequentially.
vcan_nord_1.py
# ref: https://elinux.org/Python_Can
import socket
import struct
# CAN frame packing/unpacking (see `struct can_frame` in <linux/can.h>)
can_frame_fmt = "=IB3x8s"
def build_can_frame(can_id, data):
can_dlc = len(data)
data = data.ljust(8, b'\x00')
return struct.pack(can_frame_fmt, can_id, can_dlc, data)
def dissect_can_frame(frame):
can_id, can_dlc, data = struct.unpack(can_frame_fmt, frame)
return (can_id, can_dlc, data[:can_dlc])
# create a raw socket and bind it to the given CAN interface
s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
s.bind(("vcan0",))
while True:
cf, addr = s.recvfrom(16)
print('Received: can_id=%x, can_dlc=%x, data=%s' % dissect_can_frame(cf))
Nord2 throws a "hellowld" packet to vcan0.
vcan_nord_2.py
# ref: https://elinux.org/Python_Can
import socket
import struct
# CAN frame packing/unpacking (see `struct can_frame` in <linux/can.h>)
can_frame_fmt = "=IB3x8s"
def build_can_frame(can_id, data):
can_dlc = len(data)
data = data.ljust(8, b'\x00')
return struct.pack(can_frame_fmt, can_id, can_dlc, data)
# create a raw socket and bind it to the given CAN interface
s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
s.bind(("vcan0",))
try:
s.send(build_can_frame(0x01, b'hellowld'))
except socket.error:
print('Error sending CAN frame')
Start vcan_nord_1.py in the terminal and execute vcan_nord_2.py in another terminal. As shown below, the terminal on the vcan_nord_1.py side will show that the packet has arrived.
It might be interesting to make a car that runs within a 3DCG platform such as Unity using vcan communication.
https://elinux.org/Bringing_CAN_interface_up https://elinux.org/Python_Can