Farhan Kabir
Farhan Kabir

Reputation: 169

Sending CAN frame via UDP in Python

I made UDP socket connection between two Linux machines and can send for example b"Hello, World!" easily. But now I need to send the below CAN frame

from can import Message
send_msg = Message(data=[1, 2, 3, 4, 5])

So if I print send_msg it shows:

Timestamp:        0.000000    ID: 00000000    X                DLC:  5    01 02 03 04 05

I want to get this printed on the receiving end. The sending and receiving end codes I am using are below:

Sending:

import socket

UDP_IP = "10.140.189.249"
UDP_PORT = 5005
from can import Message
send_msg = Message(data=[1, 2, 3, 4, 5])

print(send_msg)
MESSAGE = send_msg

print("UDP target IP: %s" % UDP_IP)
print("UDP target port: %s" % UDP_PORT)
print("message: %s" % MESSAGE)

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))

Here I know MESSAGE = send_msg is wrong.

Receiving

import socket

UDP_IP = "0.0.0.0"
UDP_PORT = 5005

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

while True:
    rec_msg, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    print("received message: %s" % rec_msg)

Please advise

Upvotes: 1

Views: 1358

Answers (1)

mspiller
mspiller

Reputation: 3841

As the physical layer of an UDP connection and a CAN connection are substantially different, you cannot send the CAN frames over UDP. What is of course possible is to send the payload of the CAN frame and assemble the CAN message on the receiving side: I.e. on the sending side:

sock.sendto(b“12345“, (UDP_IP, UDP_PORT))

And on the receiving side:

msg = Message(data=bytearray(recv_msg))

Most likely you do not only want to transfer the data of the CAN frame, but also the ids and other fields.

Another possibility would be to pickle the Message object on the sending side and unpickle it on the receiving side using pickle.dumps and pickle.loads

All features of the CAN bus like arbitration, error-frames etc. cannot be mimicked on a UDP connection.

Upvotes: 1

Related Questions