簡體   English   中英

用Python解釋F1 2012 UDP數據包

[英]Interpreting F1 2012 UDP packets in Python

我正在一個項目中,Python將解釋F1 2012中的游戲遙測數據,並將其發送到Arduino以顯示為物理儀表板。

F1 2012通過UDP數據包在地址127.0.0.1,端口20777發送數據。

我有一個簡單的python程序,可以讀取傳入的數據包:

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 20777

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

sock.bind((UDP_IP, UDP_PORT))

while True:
    data, addr = sock.recvfrom(1024)
    print ("Message:" data)

這將輸出如下消息:

b'\xce\xb3T@\x00\x00\x00\x001K\xa7E\xa0\xf1\xf0\xbc\xa1\xc6\x13\xc4OY\x0b\xc3\xd5\xbf.D\xca\xe2\xc2;\xb0\x9109\xf0\x19\xbd\xbb\xdd8\xbb:q\x19M\xbf\x81t.933\x19\xbf\x1e,\x19\xbf\xc2\x82\x9d\xbc\x9c\x0fM?\xa2#H\xbc\xd6\x16x\xbe\x92hr\xba:\xa8\x88=X\xd7&?q$\xc7>\x82w#><\xe9\x1d>w\xc9\xb8\xa7Bh\x010\x00\x00\x00\x00kr\xb7\xaf\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80?\x00\x00\x80?\x96z\x98\xb9!f\x849\x00\x00\x00\x00\x8d\x8b5C'

我知道這是一個相當長的輸出,但是它包含有關汽車的38個參數,每秒刷新60次。 這些是由從事類似項目的人員在本網站上概述的。

我已經在stackeoverflow上尋找了類似的問題,其中UDP的輸出與我的類似,我被告知必須使用合適的格式對數據進行解壓縮。

閱讀此網站 ,似乎數據包中的數據都是C語言中的浮點類型,因此我用Python修改了原始代碼。

import socket
import struct

UDP_IP = "127.0.0.1"
UDP_PORT = 20777

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

sock.bind((UDP_IP, UDP_PORT))

while True:
    data, addr = sock.recvfrom(1024)
    output = struct.unpack('f', data)
    print ("Message:", output)

根據此頁面上的信息,為拆包指定格式“ f”以分配傳入數據的格式: docs.python.org/3.2/library/struct.html#format-characters

現在會產生錯誤:

struct.error: unpack requires a bytes object of length 4

我相信現在我已經走到了盡頭,我也不知道該怎么辦。

請幫忙。

如錯誤消息所述: struct.error: unpack requires a bytes object of length 4 ,您需要一次傳遞4個字節。

修改您的代碼以一次發送4個字節

while True:
    data, addr = sock.recvfrom(1024)
    # data is 1024 length bytearray, break into 4 bytes and get the output
    output = struct.unpack('f', data[0:4]) # 4 bytes at a time
    print ("Message:", output)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM