简体   繁体   中英

How to parse UDP datagram to a Dart Class

I am developing a Dart application. This app receives UDP packages from a socket. Here is an example of a datagram struct(sent from a C application):

struct DataLoggerMessage
{
   uint16_t loggerFlag;
   uint16_t eventOnOff;
   uint16_t generatedEventNumber;
   uint16_t systemPausedFlag;
   mainInput input;
   mainOutput output;
};

struct mainInput{
   float p1;
   int p2;
   double p3;
   ....
}

struct mainOutput{
   float p1;
   int p2;
   double p3;
   ....
}

I want to parse these comming struct to a Dart class like below:

class DataLoggerMessage {
   int? loggerFlag;
   int? eventOnOff;
   int? generatedEventNumber;
   int? systemPausedFlag;
   MainInput? mainInput;
   MainOutput? mainOutput;
}

My main problem is to determine right bytes. For example; first 2 bytes of the datagram is 'loggerFlag', but in the dart class 'loggerFlag' is 4 byte integer. Of course I can store 2 byte in an int. But I need a proper parser for whole struct. For example in C we can simply do this:

memcpy(ioStruct, value,  sizeof(DataLoggerMessage));

Is there a method in dart like above? Thanks.

Assuming you get a ByteBuffer , you can simply have:

var short_int_list = byte_buffer.asInt!6List(0, 4)
data_logger_message.loggerFlag = short_int_list[0]
data_logger_message.eventOnOff = short_int_list[1]
...

similarly for a ByteData object, then you have things like

var byte_length = 2
data_logger_message.loggerFlag = byte_data.getInt16(0*byte_length)
data_logger_message.eventOnOff = byte_data.getInt16(1*byte_length)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM