Sending CAN frame via UDP in Python

 ̄綄美尐妖づ 提交于 2021-02-05 08:46:07

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/63257492/sending-can-frame-via-udp-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!