1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
// TComData.cpp
#include "TComData.h"
#include <stdlib.h>
#include <string.h>
void TComDataInit(TComData* comData,
char* header,
char* footer,
int maxDataChars,
TComDataReceivedHandler rxDataHandler
)
// initialisation
{
int size ;
size = strlen(header) ;
comData->HeaderLength = size ;
comData->Header = (char*)malloc(size+1) ;
strcpy(comData->Header,header) ;
size = strlen(footer) ;
comData->Footer = (char*)malloc(size+1) ;
strcpy(comData->Footer,footer) ;
comData->MaxDataLength = maxDataChars ;
// le buffer va inclure temporairement le footer
size = maxDataChars + strlen(footer) ;
comData->Buffer = (char*) malloc(size+1) ;
comData->BufferLength = size ;
TComDataReset(comData) ;
comData->RxDataHandler = rxDataHandler ;
}
void TComDataDone(TComData* comData)
// terminaison
{
free(comData->Header) ;
free(comData->Footer) ;
free(comData->Buffer) ;
}
void TComDataReset(TComData* comData)
// Appelée automatiquement après la réception d'une commande mais peut
// être appelée pour réinitialiser la lecture d'une nouvelle trame
{
comData->HeaderIn = false ;
comData->HeaderIndex = 0 ;
comData->BufferIndex = 0 ;
}
void TComDataTreatRxChar(TComData* comData, char car)
// Traitement car recu
{
int index ; // utilisé pour minimiser acces indirect
char* footerPtr ;
if (!comData->HeaderIn)
{ // le header n'a pas été ebcore recu
index = comData->HeaderIndex ;
if (car != comData->Header[index])
index = 0 ;
else
{ // caractre fait parti du header
index++ ;
comData->HeaderIn = (index == comData->HeaderLength) ;
}
comData->HeaderIndex = index ;
}
else
{ // le heaader a été recu
index = comData->BufferIndex ;
if (index >= comData->BufferLength)
{ // on vérifie overflow
strcpy(comData->Buffer,"overflow") ;
comData->RxDataHandler(comData->Buffer) ;
TComDataReset(comData) ;
}
else
{ // on ajoute caractere
comData->Buffer[index] = car ;
comData->Buffer[index+1] = NULL ;
footerPtr = strstr(comData->Buffer,comData->Footer) ;
if (footerPtr != NULL)
{ // le footer a été recu, on appelle la fonction de "callback"
index = footerPtr - comData->Buffer;
comData->Buffer[index] = NULL ;
comData->RxDataHandler(comData->Buffer) ;
TComDataReset(comData) ;
}
else
{ // footer non recu
comData->BufferIndex++ ;
}
}
}
} |
Partager