示例#1
0
void TelemetryStream::do_checksum( void )
{
    // initialize check sum variable
    unsigned short checksum;
    checksum = 0xffff;
    
    // calculate the checksum but leave out the last value as it contains the checksum
    for(int i = 0; i < sizeof(payload)-2; i++){
            checksum = update_crc_16( checksum, (char) payload[i] );}
    payload[PAYLOAD_SIZE-1] = checksum;
    printf("checksum is %x\n", checksum); 
}
示例#2
0
bool TelemetryStream::test_checksum( void )
{
    // initialize check sum variable
    unsigned short checksum;
    checksum = 0xffff;
  
    char test[] = "123456789";
    for(int i = 0; i < sizeof(test)-1; i++){
            checksum = update_crc_16( checksum, (char) test[i] );}
    printf("4b37 vs calculated %x\n", checksum); 
    if (checksum == 0x4b37) return 1; else return 0;
}
示例#3
0
	// -------------------------------------------------------------------
	// !!!!!!!!!!!   FONCTION DEBUG  A RETRAVAILLER...
	// -------------------------------------------------------------------
	int algo_putMessage(char *topic, char *data, unsigned short lenght){
    	short j;
    	int rc;
    	unsigned short crc16=0;

		// Generation du CRC du message
		for(j=0;j < lenght;j++){
			crc16=update_crc_16(crc16, data[j]);
		}

		// Ajout du CRC dans la trame
		data[lenght++]=(crc16&0xFF00)>>8;
		data[lenght++]=(crc16&0x00FF);

		// Publication du message
		//printf("\n PUBLICATION: ");
		//for(i=0;i<lenght; i++) printf(" %x", data[i]);

		MQTTClient_publish(client, topic, lenght, data, QOS, 0, &token);
		rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);

		return (rc);
}
示例#4
0
// -------------------------------------------------------------------
// Construction message algoid, controle CRC algo message, empilage des messages dans variable type ALGOID
// -------------------------------------------------------------------
void processMqttMsg(char *mqttMsg, unsigned int msgLen, char *topicName, ALGOID *destMsgStack){

    unsigned short crc_calc=0;						// crc calculé
    unsigned short crc_msg, i;					// crc message

	unsigned char ptrParam=0, ptrInstruction =0;	// pointeur de param dans linstruction, pointeur d'instruction
	static unsigned char algoMsgStackPtr;		// Pointeur du message algoid dans la pile
	unsigned char algo_command[MAXINSTRUCTION][100];

    //--------- DECODAGE DU MESSAGE RECU
    unsigned short ptrMQTTbyte;					// Pointeur d'octet de la trame MQTT
    unsigned short nbInstruction;				// pointeur sur l'instruction en cours
    unsigned short instructionLenght;			// Taille de la trame MQTT
    unsigned short ptrInstrByte;			    // Pointeur d'octet contenue dans l'instrruction


 //printf("\n Topic: %s", topicName);

 // RECUPERE LE CRC DE LA TRAME (= 2 derniers octet)
    crc_msg=(mqttMsg[msgLen-2]<<8)+(mqttMsg[msgLen-1]);

 // CALCULE DU CRC DE LA TRAME MQTT (Exclus 2 dernier byte (=crc))
    for(ptrMQTTbyte=0;ptrMQTTbyte < msgLen-2;ptrMQTTbyte++){
    	crc_calc=update_crc_16(crc_calc, mqttMsg[ptrMQTTbyte]);
    	//printf("%x ",mqttMsg[ptrMQTTbyte]);
    }


// CONTROLE LA CORRESPONDANCE DU CRC MESSAGE ET CRC CALCULE
    if(crc_calc==crc_msg){
    	nbInstruction=0;

        printf("\n\n -------------------------------------");
        printf("\n NOUVEAU MESSAGE ALGOID RECU");
        printf("\n -------------------------------------");

      // printf("\n CRC MESSAGE: %d, CRC CALC: %d  \n",msg_crc ,crc16);

       for(ptrMQTTbyte=0;ptrMQTTbyte < msgLen-2;){

    	// Calcule de la longueur des donnees de l'instruction
    	   instructionLenght=(mqttMsg[ptrMQTTbyte+1]<<8)+mqttMsg[ptrMQTTbyte+2];

        	printf("\n ALGOID MESSAGE: -> ");

        	// Recuperation de l'ensemble des instructions contenu contenue dans la trame MQTT
        	for(ptrInstrByte=0;ptrInstrByte < instructionLenght+3;ptrInstrByte++){
        		algo_command[nbInstruction][ptrInstrByte] = mqttMsg[ptrMQTTbyte];
        		printf(" %x ",algo_command[nbInstruction][ptrInstrByte]);
        		ptrMQTTbyte++;
        	}
        	nbInstruction++;
    }

       printf("\n");
       // Recherche un emplacement libre dans la pile de messages
       for(algoMsgStackPtr=0;(destMsgStack[algoMsgStackPtr].msg_id!=0) && algoMsgStackPtr<RXTXSTACK_SIZE;algoMsgStackPtr++);

       if(algoMsgStackPtr>=RXTXSTACK_SIZE){
    	   printf("\n!!! ALGO MESSAGES STACK OVERFLOW !!!");
       }
       else{
    	   strcpy(destMsgStack[algoMsgStackPtr].topic,topicName);

		   for(ptrInstruction=0;ptrInstruction<nbInstruction;ptrInstruction++){
			   switch(algo_command[ptrInstruction][0]){
					case T_NEGOC :  destMsgStack[algoMsgStackPtr].msg_type=T_NEGOC;
									destMsgStack[algoMsgStackPtr].msg_type_value=algo_GetValue(algo_command[ptrInstruction], 1);
									break;

					case PS_1 : destMsgStack[algoMsgStackPtr].msg_param[ptrParam]=PS_1;
								destMsgStack[algoMsgStackPtr].msg_param_value[ptrParam]=algo_GetValue(algo_command[ptrInstruction], 4);
								ptrParam++;
								break;

					case PSA_1:	destMsgStack[algoMsgStackPtr].msg_param[ptrParam]=PSA_1;
								destMsgStack[algoMsgStackPtr].msg_param_count[ptrParam]=((algo_command[ptrInstruction][1]<<8)+algo_command[ptrInstruction][2])/2;
								for(i=0;i<destMsgStack[algoMsgStackPtr].msg_param_count[ptrParam];i++)
									destMsgStack[algoMsgStackPtr].msg_param_array[ptrParam][i]=((algo_command[ptrInstruction][(i*2)+3])<<8)|(algo_command[ptrInstruction][(i*2)+4]) ;
								ptrParam++;
								break;

					case PCA_1:	destMsgStack[algoMsgStackPtr].msg_param[ptrParam]=PCA_1;
								destMsgStack[algoMsgStackPtr].msg_param_count[ptrParam]=((algo_command[ptrInstruction][1]<<8)+algo_command[ptrInstruction][2]);
								for(i=0;i<destMsgStack[algoMsgStackPtr].msg_param_count[ptrParam];i++)
									destMsgStack[algoMsgStackPtr].msg_string_array[ptrParam][i]=algo_command[ptrInstruction][i+3];
								ptrParam++;
								break;
					default : break;
			   }
		   }
       }
    }else{

    	printf("\n\n ----------------------------------------------------------------");
    	printf("\n ! MESSAGE ALGOID INVALID, CRC MESSAGE: %d, CRC CALC: %d ! \n",crc_msg ,crc_calc);
    	printf("\n ***** NUMBER OF DATA W/O CRC: %d",ptrMQTTbyte);
    	printf("\n ***** DATA WITH CRC:  ");
    	for(i=0;i<ptrMQTTbyte+2;i++) printf("%x ",mqttMsg[i]);
    	printf("\n ----------------------------------------------------------------");
    }
}
示例#5
0
void main( int argc, char *argv[] ) {

    char input_string[MAX_STRING_SIZE];
    char *ptr, *dest, hex_val, prev_byte;
    unsigned short crc_16, crc_16_modbus, crc_ccitt_ffff, crc_ccitt_0000, crc_ccitt_1d0f, crc_dnp, crc_sick, low_byte, high_byte;
    unsigned long crc_32;
    int a, ch, do_ascii, do_hex;
    FILE *fp;

    do_ascii = FALSE;
    do_hex   = FALSE;

    printf( "\nCRC algorithm sample program\nLammert Bies,  Version " CRC_VERSION "\n\n" );

    if ( argc < 2 ) {

        printf( "Usage: tst_crc [-a|-x] file1 ...\n\n" );
        printf( "    -a Program asks for ASCII input. Following parameters ignored.\n" );
        printf( "    -x Program asks for hexadecimal input. Following parameters ignored.\n" );
        printf( "       All other parameters are treated like filenames. The CRC values\n" );
        printf( "       for each separate file will be calculated.\n" );

        exit( 0 );
    }

    if ( ! strcmp( argv[1], "-a" )  ||  ! strcmp( argv[1], "-A" ) ) do_ascii = TRUE;
    if ( ! strcmp( argv[1], "-x" )  ||  ! strcmp( argv[1], "-X" ) ) do_hex   = TRUE;

    if ( do_ascii  ||  do_hex ) {

        printf( "Input: " );
        fgets( input_string, MAX_STRING_SIZE-1, stdin );
    }

    if ( do_ascii ) {

        ptr = input_string;
        while ( *ptr  &&  *ptr != '\r'  &&  *ptr != '\n' ) ptr++;
        *ptr = 0;
    }

    if ( do_hex ) {

        ptr  = input_string;
        dest = input_string;

        while( *ptr  &&  *ptr != '\r'  &&  *ptr != '\n' ) {

            if ( *ptr >= '0'  &&  *ptr <= '9' ) *dest++ = (char) ( (*ptr) - '0'      );
            if ( *ptr >= 'A'  &&  *ptr <= 'F' ) *dest++ = (char) ( (*ptr) - 'A' + 10 );
            if ( *ptr >= 'a'  &&  *ptr <= 'f' ) *dest++ = (char) ( (*ptr) - 'a' + 10 );

            ptr++;
	}

        * dest    = '\x80';
        *(dest+1) = '\x80';
    }



    a = 1;

    do {

        crc_16         = 0;
        crc_16_modbus  = 0xffff;
        crc_dnp        = 0;
        crc_sick       = 0;
        crc_ccitt_0000 = 0;
        crc_ccitt_ffff = 0xffff;
        crc_ccitt_1d0f = 0x1d0f;
        crc_32         = 0xffffffffL;



        if ( do_ascii ) {

            prev_byte = 0;
            ptr       = input_string;

            while ( *ptr ) {

                crc_16         = update_crc_16(    crc_16,         *ptr            );
                crc_16_modbus  = update_crc_16(    crc_16_modbus,  *ptr            );
                crc_dnp        = update_crc_dnp(   crc_dnp,        *ptr            );
                crc_sick       = update_crc_sick(  crc_sick,       *ptr, prev_byte );
                crc_ccitt_0000 = update_crc_ccitt( crc_ccitt_0000, *ptr            );
                crc_ccitt_ffff = update_crc_ccitt( crc_ccitt_ffff, *ptr            );
                crc_ccitt_1d0f = update_crc_ccitt( crc_ccitt_1d0f, *ptr            );
                crc_32         = update_crc_32(    crc_32,         *ptr            );

                prev_byte = *ptr;
                ptr++;
            }
        }



        else if ( do_hex ) {

            prev_byte = 0;
            ptr       = input_string;

            while ( *ptr != '\x80' ) {

                hex_val  = (char) ( ( * ptr     &  '\x0f' ) << 4 );
                hex_val |= (char) ( ( *(ptr+1)  &  '\x0f' )      );

                crc_16         = update_crc_16(    crc_16,         hex_val            );
                crc_16_modbus  = update_crc_16(    crc_16_modbus,  hex_val            );
                crc_dnp        = update_crc_dnp(   crc_dnp,        hex_val            );
                crc_sick       = update_crc_sick(  crc_sick,       hex_val, prev_byte );
                crc_ccitt_0000 = update_crc_ccitt( crc_ccitt_0000, hex_val            );
                crc_ccitt_ffff = update_crc_ccitt( crc_ccitt_ffff, hex_val            );
                crc_ccitt_1d0f = update_crc_ccitt( crc_ccitt_1d0f, hex_val            );
                crc_32         = update_crc_32(    crc_32,         hex_val            );

                prev_byte = hex_val;
                ptr      += 2;
            }

            input_string[0] = 0;
        }



        else {

            prev_byte = 0;
            fp        = fopen( argv[a], "rb" );

            if ( fp != NULL ) {

                while( ( ch=fgetc( fp ) ) != EOF ) {

                    crc_16         = update_crc_16(    crc_16,         (char) ch            );
                    crc_16_modbus  = update_crc_16(    crc_16_modbus,  (char) ch            );
                    crc_dnp        = update_crc_dnp(   crc_dnp,        (char) ch            );
                    crc_sick       = update_crc_sick(  crc_sick,       (char) ch, prev_byte );
                    crc_ccitt_0000 = update_crc_ccitt( crc_ccitt_0000, (char) ch            );
                    crc_ccitt_ffff = update_crc_ccitt( crc_ccitt_ffff, (char) ch            );
                    crc_ccitt_1d0f = update_crc_ccitt( crc_ccitt_1d0f, (char) ch            );
                    crc_32         = update_crc_32(    crc_32,         (char) ch            );

                    prev_byte = (char) ch;
                }

                fclose( fp );
            }

            else printf( "%s : cannot open file\n", argv[a] );
        }



        crc_32 ^= 0xffffffffL;

        crc_dnp   = ~crc_dnp;
        low_byte  = (crc_dnp & 0xff00) >> 8;
        high_byte = (crc_dnp & 0x00ff) << 8;
        crc_dnp   = low_byte | high_byte;

        low_byte  = (crc_sick & 0xff00) >> 8;
        high_byte = (crc_sick & 0x00ff) << 8;
        crc_sick  = low_byte | high_byte;

        printf( "%s%s%s :\nCRC16              = 0x%04X      /  %u\n"
                          "CRC16 (Modbus)     = 0x%04X      /  %u\n"
                          "CRC16 (Sick)       = 0x%04X      /  %u\n"
                          "CRC-CCITT (0x0000) = 0x%04X      /  %u\n"
                          "CRC-CCITT (0xffff) = 0x%04X      /  %u\n"
                          "CRC-CCITT (0x1d0f) = 0x%04X      /  %u\n"
                          "CRC-DNP            = 0x%04X      /  %u\n"
                          "CRC32              = 0x%08lX  /  %lu\n"
                    , (   do_ascii  ||    do_hex ) ? "\""    : ""
                    , ( ! do_ascii  &&  ! do_hex ) ? argv[a] : input_string
                    , (   do_ascii  ||    do_hex ) ? "\""    : ""
                    , crc_16,         crc_16
                    , crc_16_modbus,  crc_16_modbus
                    , crc_sick,       crc_sick
                    , crc_ccitt_0000, crc_ccitt_0000
                    , crc_ccitt_ffff, crc_ccitt_ffff
                    , crc_ccitt_1d0f, crc_ccitt_1d0f
                    , crc_dnp,        crc_dnp
                    , crc_32,         crc_32     );

        a++;

    } while ( a < argc );

}  /* main (tst_crc.c) */
示例#6
0
int main(int argc, char *argv[]) 
{
	int print;
	printf("%d %s\n",argc, argv[0]);
	if(argc >1 && strcmp("-p", argv[1]) == 0) print=1;
	
	time_t nosso_tempo;
	
//************************************************/
	CircularBuffer cb;
    ElemType elem = {0};
    int testBufferSize = 11264; // 176 blocos de 64 palavras
    cbInit(&cb, testBufferSize);
//************************************************/

	FILE *arquivo;
	
	int fd;
	
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"	
	int res;
#pragma GCC diagnostic pop
	
	unsigned short crc16;
	int i,j=0;
	int detected= 0, pronto = 0;
	char *ptr;
	uint16_t crc;
	uint16_t n_mesg, msg_num = 0;
	int offset;
	struct termios oldtio,newtio;
	char buf[BUFFER_SIZE];
	fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY );
	if (fd < 0) {
		perror(MODEMDEVICE); 
		cbFree(&cb);
		exit(-1); 
	}
	tcgetattr(fd,&oldtio); /* save current port settings */
	bzero(&newtio, sizeof(newtio));
	newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
	newtio.c_iflag = IGNPAR;
	newtio.c_oflag = 0;

	/* set input mode (non-canonical, no echo,...) */
	newtio.c_lflag = 0;

	newtio.c_cc[VTIME]    = 0;   /* inter-character timer unused */
	newtio.c_cc[VMIN]     = 132;   /* blocking read until 132 chars received */

	tcflush(fd, TCIFLUSH);
	tcsetattr(fd,TCSANOW,&newtio);

	arquivo = fopen("raios_detetados.bin", "wb");
	if (arquivo == NULL) {
		perror("Nao foi possível abrir o arquivo!");
		cbFree(&cb);
		close(fd);
		exit(30);
	}
	
	while (1) {     /* loop until we have a terminating condition */
		/* read blocks program execution until a line terminating character is 
			input, even if more than 255 chars are input. If the number
			of characters read is smaller than the number of chars available,
			subsequent reads will return the remaining chars. res will be set
			to the actual number of characters actually read */
		res=read(fd,buf,BUFFER_SIZE);
// 		printf("%d chars - ",res);

	crc=((uint16_t) (0xFF00 & (buf[MSG_SIZE+1]<<8)) + (uint16_t) (0x00FF & buf[MSG_SIZE]));
	n_mesg=((uint16_t) (0xFF00 & (buf[1]<<8)) + (uint16_t) (0x00FF & buf[0]));
// 		char test[]="CRC16 stream simulation.";
		ptr=buf;
		crc16= 0;
		for (i = 0; i < MSG_SIZE; i++) {
			crc16 = update_crc_16(crc16, *ptr);
			ptr++;
		}
		if(crc==crc16){
// 			printf(" CRC OK! -  %4X %4X %d\n", crc, crc16, n_mesg);

			for(i=1;i<65;i++){
				elem.value=((int16_t) (0xFF00 & (buf[2*(i)+1]<<8)) + (int16_t) (0x00FF & buf[2*i]));
				if (detected == 1) {
//					if (n_mesg != msg_num) {
					if (j < 13632) { 
						vetor_disco[j] = elem.value;
						j++;
// 						printf("j = %d\n", j);
					}
					else {
						pronto = 1;
						detected = 0;
						cbWrite(&cb, &elem);
					}
				}
				else {
					cbWrite(&cb, &elem);
				}
				if(print==1){
					printf("%4d ",elem.value);
					if (((i+2) % 32) ==1)
					printf("\n");
				}
			}
		} else {
			clearScreen();
// 			printf("not OK!  %X %X\n", crc, crc16);
			tcflush(fd, TCIFLUSH);
		}
		if (pronto == 1) {
			fwrite(vetor_disco, sizeof(vetor_disco), 1, arquivo);
			printf("Write!!!!!");
			j = 0;
			pronto = 0;
		}
// 		if(j>=testBufferSize){
// 			while (!cbIsEmpty(&cb)) {
	// 					elem = cbRead(&cb);i
// 				for (offset=0;offset<(cb.end-cb.start);offset++){
// 					elem = cbPeek(&cb,offset);
// 					printf("%d\t%d\t%d\t%d\n", elem.value, cb.start, cb.end, cb.size);
// 				}
		if (detected == 0) {
			offset = r_change(&cb,n_mesg); // TODO: o que acontece quando n_mesg retorna a zero?
			if(offset){
				nosso_tempo = time(&nosso_tempo);
				fwrite(&nosso_tempo, sizeof(time_t),1, arquivo);
//				for (i = offset - 2263, j = 0; i < cb.end; i++, j++){ // TODO :: fazer a conta do offset levando em consideração o wrap around.
				for (i = (offset%64 - 37)*64, j = 0; i < (offset%64 +1)*64; i++, j++){
					ElemType temp_elem;
 					temp_elem = cbPeek(&cb, i);
					vetor_disco[j] = temp_elem.value;
				}
				cb.end = cb.start; // Esvazia o buffer circular	
				detected = 1;
				msg_num = n_mesg + 176;
				printf("Detected: %ld %d %d\n",nosso_tempo, n_mesg,msg_num);
			}	
	
		}
// 			}
// 		break;
// 		}
// 			for(i=0;i<64;i++){
// 				printf("%4d ",((uint16_t) (0xFF00 & (buf[2*(i)+1]<<8)) + (uint16_t) (0x00FF & buf[2*i])));
// 				if (((i+2) % 32) ==1)           printf("\n");
// 				}
		}
		tcsetattr(fd,TCSANOW,&oldtio);
		return(0);
}