Create a state machine to check a message in a custom protocol.
The message format is (one byte each) : 0xAA , OxBB, len , …. data …. , CS
use the following starter code:
#include <stdio.h> #include <stdlib.h> #define MAX_LEN 255 typedef enum { OK,CSERROR} Status; typedef enum { WAITFORAA,WAITFORBB,STORELEN,READDATA,CALCCS} State; Status CalculateCS(char *addr, int count,char cs) { register char sum = 0; unsigned char csres; while(count > 1) { sum = sum + *((short *) addr); addr+=2; count = count - 2; } if (count > 0) sum = sum + *((char *) addr); while (sum>>16) sum = (sum & 0xFFFF) + (sum >> 16); return ((~sum) == cs) ? OK : CSERROR; } void ProcessMsg(char *msg,int len) { puts("msg ok"); } void HandleByte(unsigned char nextb) { // TODO : implement // send a correct message to ProcessMsg() } int main(void) { int i; char msgtest[11] = { 0xAA, 0xBB, 7, 'a','b','c','d','e','q','r',128}; for(i = 0; i < 11; i++) { HandleByte(msgtest[i]); } return EXIT_SUCCESS; }
change the CS value and check the results
Extra:
Add support for 0xAA, 0xBB as part of the data