2

I'm trying to send a C++ struct over a UDP socket to a Python app.

This is the C++ code to send the struct:

// my struct
struct S_telemetryPacket  {
    // sensors
    float temperatureSensor1;
    float accelerometer1_x;
    float accelerometer1_y;
    float accelerometer1_z;
    float batteryVoltage1;
    float powerDraw1;

    // motors
    int motor1;
    int motor2;
    int motor3;
    int motor4;

} S_telemetryPacket;

// ... some other code populates the struct

// then the struct is sent over UDP
int res = sendto(relaySocket, (char *)&S_telemetryPacket, sizeof(S_telemetryPacket), NULL, (SOCKADDR *)&addrGroundstation, addrGroundstationSize);

And this is the raw data received in Python:

\x00P\x03E\x00\x00\xfaD\x00\x00\x00\x00\x00@\xfbD\x00`\xfbD\x00@\x03Ed\x00\x00\x00e\x00\x00\x00n\x00\x00\x00o\x00\x00\x00

When I try to unpack it using the struct library, I get an error.

print struct.unpack('eeeeeeiiii', raw_data)

This error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
struct.error: bad char in struct format

Can anyone shed some light? The data I receive looks weird, there are symbols I wouldn't expect like `, or @, or o, etc.

Could it be something wrong with how the struct is sent from the C++ side?

1
  • do you extract all the headers ( UDP ,...) ? Commented Jan 14, 2018 at 22:56

1 Answer 1

1

The error message says:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
struct.error: bad char in struct format

This states that format string is wrong.

You should try:

struct.unpack('ffffffiiii', raw_data)

The e format string is for a fairly esoteric 16 bit float, and is unlikely to be what you need. In addition it is not supported on Python 2.

Test Code:

import struct

raw_data = b'\x00P\x03E\x00\x00\xfaD\x00\x00\x00\x00\x00@\xfbD\x00`' \
           b'\xfbD\x00@\x03Ed\x00\x00\x00e\x00\x00\x00n\x00\x00\x00o' \
           b'\x00\x00\x00'
print(struct.unpack('ffffffiiii', raw_data))

Results:

(2101.0, 2000.0, 0.0, 2010.0, 2011.0, 2100.0, 100, 101, 110, 111)
Sign up to request clarification or add additional context in comments.

4 Comments

Ah, great that works. I misread the table and used e instead of f...For some reason, the third data element (0.0) is wrong though. It should be 2001. All the other values are correct. Any ideas why?
It looks like that 0 is in your data... Characters 8-11 are all \x00. At this point I would check the sender...
Every 4 characters is one float. The first 4 characters are \x00P\x03E and are 2101.0
Perfect. That was it. The sender had a typo and it was using the wrong value... Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.