在Python中通过UDP发送CAN帧 [英] Sending CAN frame via UDP in Python

查看:54
本文介绍了在Python中通过UDP发送CAN帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两台Linux机器之间建立了UDP套接字连接,并且可以轻松发送例如 b"Hello,World!" .但现在我需要发送以下 CAN 帧

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])

因此,如果我打印 send_msg ,则会显示:

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:

发送:

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))

在这里,我知道 MESSAGE = send_msg 是错误的.

Here I know MESSAGE = send_msg is wrong.

接收

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)

请告知

推荐答案

由于 UDP 连接和 CAN 连接的物理层有很大不同,因此您无法通过 UDP 发送 CAN 帧.当然可能的是发送 CAN 帧的有效载荷并在接收端组装 CAN 消息:即在发送方:

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))

在接收方:

msg = Message(data=bytearray(recv_msg))

您很可能不仅希望传输CAN帧的数据,而且还希望传输ID和其他字段.

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

另一种可能性是使用 pickle.dumps pickle.loads

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

不能在UDP连接上模仿CAN总线的所有功能,例如仲裁,错误帧等.

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

这篇关于在Python中通过UDP发送CAN帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆