Hi,
I'm trying to use Python code to read the UDP packets sent in Time Trial. Very confusing because my packet header seems to change size all the time.
Are there any coding examples to extract this data?
I am having a hard enough time just getting the header right.
Sometimes I get 13 numbers, sometimes 12, sometimes 14...
Here are some examples:
Error decoding packet header: unpack requires a buffer of 102 bytes
Received Packet with ID 2:
Header Data: (2023, 23, 1, 19, 1, 2, 1405940429, 5027233792161074819, 1.7819191532047239e-40, 127162, 1978793728, 3196583937, 54)
Error decoding packet header: unpack requires a buffer of 102 bytes
Received Packet with ID 0:
Header Data: (2023, 23, 1, 19, 1, 0, 1405940429, 5027233792161074819, 1.7819191532047239e-40, 127162, 45022976, 633455584, 246)
Error decoding packet header: unpack requires a buffer of 102 bytes
Received Packet with ID 13:
Header Data: (2023, 23, 1, 19, 1, 13, 1405940429, 5027233792161074819, 1.7819191532047239e-40, 127162, 977927936, 3282977332, 52)
The python code that produces this output is:
import socket
import struct
# Define the format of the PacketHeader using struct format string
packet_header_format = "<HB3BBIQfIIIB"
def receive_udp_packets(port):
# Create a UDP socket
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the socket to a specific address and port
udp_socket.bind(('0.0.0.0', port))
print(f"Listening for UDP packets on port {port}...")
try:
while True:
# Receive data from the socket
data, address = udp_socket.recvfrom(1024)
# Check if there is enough data for the header
if len(data) >= struct.calcsize(packet_header_format):
# Unpack the packet header
try:
header_data = struct.unpack(packet_header_format, data[:struct.calcsize(packet_header_format)])
packet_id = header_data[5]
print(f"Received Packet with ID {packet_id}:")
print(f"Header Data: {header_data}")
# Calculate the size of the entire packet
full_packet_size = struct.calcsize(packet_header_format) + struct.calcsize("f" * 6 + "h" * 9 + "f" * 6) # Adjust this based on your actual CarMotionData format
# Check if there is enough data for the full packet
if len(data) >= full_packet_size:
# Unpack the header and data
full_packet_data = struct.unpack(packet_header_format + "f" * 6 + "h" * 9 + "f" * 6, data[:full_packet_size])
print(f"Received Full Packet Data:")
print(full_packet_data)
except struct.error as e:
print(f"Error decoding packet header: {e}")
else:
print("Received data is too short for the PacketHeader.")
except KeyboardInterrupt:
print("Stopping the UDP listener.")
finally:
# Close the socket when done
udp_socket.close()
if __name__ == "__main__":
port_number = 20777
receive_udp_packets(port_number)
Thank you