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

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

问题描述

我在两台 Linux 机器之间建立了 UDP 套接字连接,可以轻松发送例如 bHello, 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 帧的数据,还要传输 ids 和其他字段.

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

另一种可能性是在发送端腌制 Message 对象并在接收端使用 pickle.dumpspickle.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

CAN 总线的所有功能(如仲裁、错误帧等)都无法在 UDP 连接上模仿.

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

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

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