0
votes

I have some trouble to implement an existing protocol in C, escpecially with creating the data packets.

The Packet looks like this:

HeaderData 1(1Byte) | HeaderData 2(1 Byte) | Length_Data (2 Byte) | Data (Length variable)

I get some data via serial port and it is saved in returnMessage:

int getMessage(char * returnMessage){
int length = 0;
//static char replay[REPLAY_MAX_SIZE];
memset(replay, 0x00, REPLAY_MAX_SIZE);
// goes into the while-loop, if some data comes in
// after a timeout of 20 seconds the program will be terminated
if(select(fd +1 , &set, NULL, NULL, &timeout )){
    length = read(fd, returnMessage, REPLAY_MAX_SIZE);
    //reinitialize fd_set values
    FD_ZERO(&set);
    FD_SET(fd, &set);
    return length;
    }
    //printf("[%s] ERROR CANNOT GET MESSAGE\n", __FUNCTION__);
return -1;
}

This data in returnMessage I will enhance to my packet to send it further. But I dont know how.

Maybe there is a way with structs?

struct Packet{
   char header1[1];
   char header2[2];
   char lengthData[20];
   char data[MAX_DATA_LENGTH];
};

struct Packet packet;

But how can I copy the data in returnMessage to packet.data[]? And how can I concatenate the data in the struct in order to send the packet.

Have someone an introduction of creating/parsing packets for simple protocols?

Thanks a lot,

Florian

1
memcpy()? this has really nothing to do with "protocols" and stuff.The Paramagnetic Croissant

1 Answers

0
votes

Assuming you get the full packet in your char buffer (*), it is then simple :

struct Packet{
   char header1[1];
   char header2[2];
   short lengthData;
   char data[MAX_DATA_LENGTH];
};

void buftopacket(char *buffer, Packet *pkt) {
    pkt->header1 = buffer[0];
    pkt->header2 = buffer[1];
    pkt->lengthData = buffer[2] << 8 + buffer[3]; /* assuming network order */
    memcpy(pkt->data, buffer + 4, (pkt->lengthData <= MAX_DATA_LENGTH)
        ? pkt->lengthData : MAX_DATA_LENGTH); /* do not write pass buffer end*/
}

(*) but nothing ensures that you get full packet in one single read ...