snoop.c

来自「tinyos最新版」· C语言 代码 · 共 118 行

C
118
字号
/* snoop.c                                         tab:4 * * To be used with apps/snooper/SNOOPER.c * Similar to listen.c but support different length of packet. * The first byte is packet length * * Author: Wei Ye (based on code listen.c) * */#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <termios.h>#include <stdio.h>#include <string.h>#include <unistd.h>#include <sys/time.h>#define MAX_LENGTH 250#define BAUDRATE_MICA B19200 // baudrate for Mica#define BAUDRATE_MICA2 B57600 // baudrate for Mica2#define SERIAL_DEVICE "/dev/ttyS0" //the port to use.int input_stream;char input_buffer[MAX_LENGTH];unsigned char pktLen = 0; // packet lengthvoid print_usage(void);void print_packet(void);void read_packet(void);int main(int argc, char ** argv) {   char *platform[2] = {"mica", "mica2"};   struct termios newtio;   if (argc != 2) {      print_usage();      exit(1);   }   /* open input_stream for read/write */    input_stream = open(SERIAL_DEVICE, O_RDWR|O_NOCTTY);   if (input_stream == -1) {      printf("Input_stream open failed!\n");      printf("Make sure the user has permission to open device.\n");      exit(1);   }   /* Serial port setting */   bzero(&newtio, sizeof(newtio));   if (strcmp(argv[1], platform[0]) == 0) {      newtio.c_cflag = BAUDRATE_MICA | CS8 | CLOCAL | CREAD;   } else if (strcmp(argv[1], platform[1]) == 0) {      newtio.c_cflag = BAUDRATE_MICA2 | CS8 | CLOCAL | CREAD;   } else {      perror("Unknown platform!\n");      exit(1);   }    newtio.c_iflag = IGNPAR;   /* Raw output_file */   newtio.c_oflag = 0;   tcflush(input_stream, TCIFLUSH);   tcsetattr(input_stream, TCSANOW, &newtio);   printf("input_stream opens ok\n");   while(1){      read_packet();      print_packet();   }}void print_usage(){    //usage...	printf("Usage: snoop platform\n");	printf("Valid platforms: mica, mica2\n");	printf("This program reads in data from");	printf(SERIAL_DEVICE);	printf(" and prints it to the screen.\n");	printf("\n");}void read_packet(){	int i, count = 0;	bzero(input_buffer, MAX_LENGTH);	//search through to find 0x7e signifing the start of a packet	while(input_buffer[0] != (char)0x7e){		while(1 != read(input_stream, input_buffer, 1)){};	} 	// have start symbol now, read in rest of packet	input_buffer[0] = 0;		while(1 != read(input_stream, input_buffer, 1)){	}	pktLen = input_buffer[0];	if (pktLen == 0 || pktLen > MAX_LENGTH)	return;	count = 1;	while(count < pktLen) {		count += read(input_stream, input_buffer + count, pktLen - count); 		}}void print_packet(){	//now print out the packet	int i;	printf("data:");	if (pktLen == 0 || pktLen > MAX_LENGTH) {		printf(" length error!");	} else {		for(i = 0; i < pktLen; i ++){			printf("%x,", input_buffer[i] & 0xff);		}	}	printf("\n");} 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?