我有一个系统设置,我的c程序以这种格式接收数据包:
struct HidPacket
{
byte packetCount;
byte index;
byte totalSize;
char dataId[4];
byte data[48];//max most likely 61 but using 48 for now
};
received packet: (total packets) 6 : (index) 0 : (total data bytes) 128 : eChF
received packet: 6 : 1 : 128 : eChF
received packet: 6 : 2 : 128 : eChF
received packet: 6 : 3 : 128 : eChF
received packet: 6 : 4 : 128 : eChF
received packet: 6 : 5 : 128 : eChF
received packet: 6 : 0 : 128 : gFjI
received packet: 6 : 1 : 128 : gFjI
received packet: 6 : 2 : 128 : gFjI
received packet: 6 : 3 : 128 : gFjI
received packet: 6 : 4 : 128 : gFjI
received packet: 6 : 5 : 128 : gFjI
我试图将这些数据包构建成一个完整大小的字节数组,一旦收到所有6个数据包但我不知道从哪里开始。我可以在c中使用什么来实现这一目标?
我正在研究使用队列,但那些不是c的原生,c中没有键值数组。我应该尝试找到某种队列库,或者只有在收到所有6个相同ID的数据包后才能运行我的组合数组代码。我还需要考虑从不接收部件的胭脂包。我想知道这是否可以在队列中处理。
更新
以下是我的工作:
bool didStart = false;
int packetSize = 0;
int dataPackets = 0;
struct HidPacket packets[6];
struct DataPacket constructPacket(struct HidPacket hPacket) {
if (hPacket.index == 0) {
didStart = true;
}
if (didStart) {
packets[hPacket.index] = hPacket;
if (hPacket.index + 1 >= hPacket.packetCount) {
char msg[6 * dataSize];
char* cur = msg;
for (int ii = 0; ii < 6; ii++) {
memcpy(cur, packets[ii].data, 48);
cur += 48;
}
Serial.print("first byte: ");
Serial.println((int)msg[0]);
}
}
}
答案 0 :(得分:0)
char msg[6*48];
char* cur = msg;
for (int ii = 0; ii < 6; ii++) {
memcpy(cur, packets[ii].data, 48);
cur += 48;
}
以上假设正好有6个数据包,每个数据包都已完全填充。如果消息少于6 * 48字节等,您可能希望提前停止
答案 1 :(得分:0)
#include <stdio.h>
#define MAX_HID_PACKET 6
struct HidPacket
{
char packetCount;
char index;
char totalSize;
char dataId[4];
char data[48];//max most likely 61 but using 48 for now
};
struct HidPacket * Hid;
int HidPacketIter = 0;
void resetConstructor(){
HidPacketIter = 0;
}
void constructPacket(struct HidPacket * hPacket) {
if( HidPacketIter = 0 || Hid[HidPacketIter].index == hPacket->index){
memcpy(&Hid[HidPacketIter],hPacket,MAX_HID_PACKET*sizeof(struct HidPacket));
HidPacketIter++;
if( MAX_HID_PACKET == HidPacketIter){
resetConstructor();
/*TODO: Put your funtion which process 6 packet here. */
}
}else{
resetConstructor();
}
}
int main(){
Hid = malloc(MAX_HID_PACKET*sizeof(struct HidPacket));
resetConstructor();
struct HidPacket * ReceivedPacketPtr;
/*TODO: Put your packet receiver function here and receive packets here then assign packets addresses to ReceivedPacketPtr*/
constructPacket(ReceivedPacketPtr);
return 0;
}
您可以根据历史缓冲区(Hid)检查接收到的数据包的索引值,如果未收到相同ID的连续数据包,则重置histort缓冲区索引。如果接收到6个数据包(MAX_HID_PACKET),则再次重置历史缓冲区hid。那时你可以把你的代码放到那里处理6个数据包。我还注意到TODO要完成或绑定您的代码或应用程序的部分。