예제 #1
0
int main(int argc, char** argv)
{

	int i, n,
	    cport_nr=16,        // /dev/ttyS0 (COM1 on windows) 
	    bdrate=57600;       // 57600 baud 

	if(OpenComport(cport_nr, bdrate))
	{
		printf("Can not open comport\n");
	}

	glutInit(&argc, argv);
	glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
	glutInitWindowSize (500, 500); 
	glutInitWindowPosition (100, 100);
	glutCreateWindow (argv[0]);
	init ();
	glutDisplayFunc(display); 
	glutReshapeFunc(reshape);
	glutTimerFunc(0,kalmanFilterResults,0);
	glutMainLoop();

	return 0;
}
예제 #2
0
//设置并开启串口_wh
FREObject setupPort(FREContext ctx, void* funcData, uint32_t argc, FREObject argv[])
{
	FREObject result;
	int comPortError = 0;
	int useDtrControl;

	FREGetObjectAsInt32(argv[0], &comPort);//从as获取信息_wh
	FREGetObjectAsInt32(argv[1], &baud);
	FREGetObjectAsInt32(argv[2], &useDtrControl);

	bufferSize = 0;

	comPortError = OpenComport(comPort, baud, useDtrControl);
	if (comPortError == 0)
	{
		//pthread_cancel(ptrToThread);//杀掉该线程,以免重新开启串口时之前线程残留_wh
		multiplatformSleep(20);//从100ms减到20ms,与as呼应,避免响应不对应_wh
		pthread_create(&ptrToThread, NULL, pollForData, NULL);
		FRENewObjectFromBool(1, &result);
	}
	else
	{
		FRENewObjectFromBool(0, &result);
	}

	return result;
}
예제 #3
0
int main()
{
  int i, n, cport_nr=16, /* /dev/ttyS0 (COM1 on windows) */ bdrate=9600; /* 9600 baud */

  unsigned char buf[4096];
  unsigned char str[] = {'F','#','\0'};



   printf("I am here on 31\n");
   if(OpenComport(cport_nr, bdrate))
   {
    printf("Can not open comport\n");
    return(0);
   }

   i = 0 ;
   while(1)
   {

 	int n, j ,k;

	for(j = 0 ; str[j] != '\0' ; j ++)
	{	
		n = SendByte(cport_nr,str[j]);
//		delay_in_sec(1);
	}
//	delay_in_sec(5);
	i ++ ;
  }

  return(0);
}
bool RunRadarDataList() {
	const int c_PerComDataSize = 1024;
	unsigned char com_data[1024];
	int act_com_size;
	bool ok_com;
	char config_path[255];
	int port_num;
	int baud_rate;

	GetConfigPath(config_path, sizeof(config_path));
	GetPortNumOfSerialInterface(config_path, &port_num);
	GetBaudRateOfSerialInterface(config_path, &baud_rate);
	ok_com = OpenComport(port_num, baud_rate);
	if (false == ok_com) {
		LOG("OpenComport() error!\n");
		return false;
	}
	else {
		while (true) {
			act_com_size = ReadComport(com_data, c_PerComDataSize);
			if (0 == act_com_size)
				continue;
			else
				AnalyseComData(com_data, act_com_size);
		}
		CloseComport();
		return true;
	}
}
예제 #5
0
int main()
{
  int i, n,cport_nr=17, /* /dev/ttyS0 (COM1 on windows) */bdrate=9600; /* 9600 baud */

  unsigned char buf[4096];
  
  char temp ;
  

//  printf("I am here on 31\n");
  if(OpenComport(cport_nr, bdrate))
  {
    printf("Can not open comport\n");

    return(0);
  }

  char str[13];
  int count = 0 ;
  int j;
  while(1)
  {
    n = PollComport(cport_nr, buf, 1);

    if(n > 0)
    {
      str[count ++ ] = buf[0] ;

      if(str[count-1] == '#')	
      {
	for(j = 0 ; str[j] != '#'; j++)
		printf("%c",str[j]);
		printf("\n");
		count = 0;
      }


      buf[n] = 0;
      for(i=0; i < n; i++)
      {
        if(buf[i] < 32) /* replace unreadable control-codes by dots */
        {
          buf[i] = '.';
        }
      }

     // printf("received %i bytes: %c , %d \n", n, buf[0],strlen((char *)buf));

    }


  }

  return(0);
}
int CiCreateDef::ConnectToPort() {
    int pom = OpenComport();
    
    if (pom == 0) {
        // precitame co tam caka
        unsigned char *dataR;
        dataR = (unsigned char*) malloc(500);
        PollComport(dataR, 500);
    }
    
    return pom;
}
예제 #7
0
파일: serial.c 프로젝트: alvarop/pc
/*******************************************************************************
 * @fn     uint8_t serial_open( int32_t port_number, int32_t baud_rate,
 *                                     uint8_t (*callback)( uint8_t*, uint32_t) )
 * @brief  Open serial port
 * ****************************************************************************/
uint8_t serial_open( int32_t port_number, int32_t baud_rate,
                                       uint8_t (*callback)( uint8_t*, uint32_t) )
{
  serial_port_number = port_number;
  // Use RS232 library to open serial port
  if ( OpenComport( serial_port_number, baud_rate ) )
  {
    // Error opening serial port
    return 1;
  }

  // Set a callback function for receiving packets
  if( callback != NULL) {
    serial_read_callback = callback;
  }
  return 0;
}
예제 #8
0
int main()
{

	int i, n, cport_nr=0, bdrate=9600;

    unsigned char buf[4096];

    if(OpenComport(cport_nr, bdrate))
    {
        printf("Cannot open connection\n");
        return(0);
    }

    while(1)
    {
        n = PollComport(cport_nr, buf, 4095);

        if(n > 0)
        {
            buf[n] = 0; //Always put a "null" at the end of a string

            for(i=0; i < n; i++)
            {
                if(buf[i] < 32)
                {
                    buf[i] = '.';
                }
            }

            printf("received %i bytes: %s\n", n, (char *)buf);
        }

        usleep(100000);
    }

    return(0);
}
예제 #9
0
void init_com(GtkWidget *window)
{
	ready = OpenComport(com_no, BAUD_RATE);
}
예제 #10
0
/*
 * main program
 */
int main(int argc, char** argv) {
    //global var
    time_t sec0, sec1;
    unsigned int delayPixel= 120000, delayGyrodataSending = 25000;
    unsigned int idPayload = 303, useKeyboardCmd = 0, buffer_max_num = 64;
    unsigned char keyChar;
    int gpioOK = 0;
	dictionary *iniDict;	//ini dictionery  
	char strPathCfg[255];
	
	GPS_DATA last_posx;
	
	//init last gps pos
	last_posx.gps_status = last_posx.gps_loc.lat = last_posx.gps_loc.lon = 0;
	last_posx.gps_speed = last_posx.gps_altitude = last_posx.gps_time = 0;	
    
    //show titel
#if VERBOSE==1
    printf("%s", APP_TITEL);
#endif

	//init pin switch
	gpioOK = wiringPiSetup();
	
	if(gpioOK != -1)
	{
		pinMode(6, INPUT);
		pullUpDnControl(6, PUD_UP);
	}
	else
		printf("gpio init eror\r\n");
		
	//parsing argumen jika ada
	if(argc>2)
	{
		//default cfg file
		getcwd(strPathCfg, sizeof(strPathCfg));
		strcat(strPathCfg, "/");
		strcat(strPathCfg, CFG_NAME);
	
		int i;
		for(i=1;i<(argc-1);i++)
		{
			//delay pixel
			if(strcmp("-d",argv[i])==0)
				delayPixel = atoi(argv[++i]);
				
			//id payload
			if(strcmp("-i",argv[i])==0)
				idPayload = atoi(argv[++i]);
				
			//pake keyboard ato tidak
			if(strcmp("-k",argv[i])==0)
				useKeyboardCmd = atoi(argv[++i]);
				
			//gyro send
			if(strcmp("-g",argv[i])==0)
				delayGyrodataSending = atoi(argv[++i]);
				
			//buffer size
			if(strcmp("-b",argv[i])==0)
				buffer_max_num = atoi(argv[++i]);
		}
	}
	else //baca dari cfg file
	{				
		//load ini file
		//char strCfg[80];
		
		if(argc==2)
		{
			strcpy(strPathCfg, argv[1]);
		}
		else
		{		
			//get cwd
			if (getcwd(strPathCfg, sizeof(strPathCfg)) != NULL)
			   printf("Current working dir: %s\r\n", strPathCfg);
			else
			{
				strcpy(strPathCfg, argv[1]);			
			}
		}
		
		//check file exists
		strcat(strPathCfg, "/");
		strcat(strPathCfg, CFG_NAME);
		if(!file_exist(strPathCfg))
		{
			printf("Configuration file %s not found!!!\r\n", strPathCfg );
			return(EXIT_FAILURE);
		}
		
		//load from config file
		printf("Loading configuration file from %s\r\n", strPathCfg);
		
		//load ini parser
		iniDict = iniparser_load(strPathCfg);
		
		//read cfg value
		if(iniDict)
		{
			idPayload = iniparser_getint(iniDict,"payload:id",100);
			delayPixel = iniparser_getint(iniDict,"payload:cam_delay",120000);
			delayGyrodataSending = iniparser_getint(iniDict,"payload:g_delay",20000);
			buffer_max_num = iniparser_getint(iniDict,"payload:buffer",64);
		}
	}
	
	//show config setup
	printf("======================================\r\n");
	printf("Configuration :\r\n");
	printf("Delay Pixel = %d uS\r\n", delayPixel);
	printf("ID Payload = %d\r\n", idPayload);
	printf("Use Keyboard = %d\r\n", useKeyboardCmd);
	printf("Gyro Delay = %d uS\r\n", delayGyrodataSending);
	printf("Buffer = %d byte\r\n", buffer_max_num);
	printf("======================================\r\n");    
	
	//init bus i2c
	int i2c_hdl = I2C_Init_Bus(i2c_dev, &statusPeripheral);
	
	//init start adxl345
	ADXL345_Init_Start(i2c_hdl, adxl345_addr, &statusPeripheral);
	
	//init itg3200
	ITG3200_Init_Start(i2c_hdl, itg3200_addr, &statusPeripheral);
	
    //open port
    unsigned char buffRX[COM_BUFF_NUM];
    int buffNumRX;
    
    //make it as null string
    buffRX[COM_BUFF_NUM-1] = 0;

    if (OpenComport(COM_PORT, COM_SPEED)) {
        fprintf(stderr, "Open port %d failed : %s\r\n!!!", COM_PORT, strerror(errno));
        return errno;
    }

#if VERBOSE==1
    printf("communication port opened\r\n");
#endif   

	//tes port com
	//while(1){
		////ambil perintah dari comport
        //buffNumRX = PollComport(COM_PORT, buffRX, (COM_BUFF_NUM - 2));
        //if (buffNumRX > 0) {
			////printf("%d = %s\n", buffNumRX, buffRX);
			//int i;
			//for(i=0;i<buffNumRX;i++)
			//{
				//printf("%X %s", buffRX[i], (i<buffNumRX-1) ? "":"\n");
			//}
			
			//char ss[10];
			//snprintf(ss,6,"%d",(buffRX[1]<<8)+buffRX[2]);
			//printf("id = %s\n", ss);
		//}
	//}

	//open cam
	CvCapture *camHdl = cvCaptureFromCAM(CV_CAP_ANY);
	Cam_Init_Start(camHdl, &statusPeripheral);

    //main loop
    while (1) {
		if(useKeyboardCmd)
		{
			//dummy keyboard input
			printf("press command key\r\n");
			keyChar = getchar();

			//if (keyChar == cmdList[3][0])
				//opsState = STATE_EXIT;

			//if (keyChar == cmdList[2][0])
				//opsState = STATE_GET_CAM_DATA;
				
			//if (keyChar == cmdList[1][0])
				//opsState = STATE_GET_G_DATA;
				
			if (keyChar == cmdList[3])
				opsState = STATE_EXIT;

			if (keyChar == cmdList[2])
				opsState = STATE_GET_CAM_DATA;
				
			if (keyChar == cmdList[1])
				opsState = STATE_GET_G_DATA;
		}

        //ambil perintah dari comport
        buffNumRX = PollComport(COM_PORT, buffRX, (COM_BUFF_NUM - 2));

        //data diterima -> cek printah
        if (buffNumRX > 0) {
            //int i;
            //unsigned char *chrPos;

            ////make it null string
            //if (buffRX[buffNumRX] != 0)
                //buffRX[buffNumRX] = 0;
                
            ////default ops state = idle
            //opsState = STATE_IDLE;

			////add new state
            //for (i = 0; i < CMD_COUNTER; i++) {
                //chrPos = strstr(buffRX,cmdList[i]);

                //if ((chrPos != NULL) && ((chrPos - buffRX + 1) == 1)) { //got a match?
                    ////proses state
                    //opsState = i;

                    //break;
                //}
            //}
            
            opsState = CheckCommand(cmdList, buffNumRX, buffRX);
        }
        
        //cek tobmol
        if(gpioOK != -1)
        {
			//printf("%d\r\n", digitalRead(6));
			//SendByte(COM_PORT, digitalRead(6)+0x30);
			//usleep(1e5);
		if(digitalRead(6) == 0)
		{
			usleep(5e5);
			if(digitalRead(6) == 0)
				opsState = STATE_SHUTDOWN_OS;
		}
	}

        //lakukan proses seuai ops state
        if (opsState == STATE_EXIT) {
#if VERBOSE==1
            printf("exiting...\r\n");
            //fflush(stdout);   
#endif            
            break;
        }
        
        //shutdown os
        if (opsState == STATE_SHUTDOWN_OS)
        {
			printf("shutdown...\r\n");
			break;
		}
		
		//restart os
        if (opsState == STATE_RESTART_OS)
        {
			printf("restart...\r\n");
			break;
		}

		//other state
        switch (opsState) {
            case STATE_IDLE: //idle state
                //SendByte(COM_PORT, 's');
                break;

            case STATE_GET_G_DATA: //ambil data g
                //SendByte(COM_PORT, 'g');
                
                GetAndSendAccGyro(i2c_hdl, adxl345_addr, itg3200_addr, idPayload, delayGyrodataSending, &last_posx, buffer_max_num);
                break;

            case STATE_GET_CAM_DATA://ambil data cam
                //SendByte(COM_PORT, 'c');
#if VERBOSE==1
                printf("grab camera start\r\n");
                sec0 = time(NULL);
#endif                                

                GrabAndSendCameraData(camHdl, i2c_hdl, 5, delayPixel, idPayload, &last_posx, buffer_max_num);                
#if VERBOSE==1
                sec1 = time(NULL);
                printf("grab camera finish in %lds\r\n", (sec1 - sec0));
#endif                
				opsState = STATE_IDLE;
				
				//usleep(5e4);
				//ComportFlush(COM_PORT);
				//usleep(1.5e6);
                break;

            case STATE_GET_STATUS: //ambil status payload
                snprintf((char*)buffRX, 16, "s,%.3d,%d,%d\r", idPayload, 990, statusPeripheral);
                //SendBuf(COM_PORT, buffRX, 10);
                //snprintf((char*)buffRX, 16, "s,%.3d,%d\r", idPayload, 990);
                cprintf(COM_PORT, buffRX);
                opsState = STATE_IDLE; //go back to idle
                
                #if VERBOSE==1
                printf("sendstatus reply = %s\r\n", buffRX);
                #endif
                break;
                
            case STATE_REINIT_PERIPHERAL:	//reinit peripheral
				//init cam
				Cam_Init_Start(camHdl, &statusPeripheral);
				
				//init bus i2c
				i2c_hdl = I2C_Init_Bus(i2c_dev, &statusPeripheral);
				
				//init start adxl345
				ADXL345_Init_Start(i2c_hdl, adxl345_addr, &statusPeripheral);
				
				//init itg3200
				ITG3200_Init_Start(i2c_hdl, itg3200_addr, &statusPeripheral);
				
				opsState = STATE_IDLE; //go back to idle
				break;
				
			case STATE_READ_WRITE_CONFIGURATION: //read/write config file
				printf("Opening configuration file %s\r\n", strPathCfg);
				
				//load ini file
				iniDict = iniparser_load(strPathCfg);
				
				//write if neccessary
				if(buffRX[1]==1)	//write setting
				{
					char stmp[10];
					
					//id
					snprintf(stmp,10,"%d", (buffRX[2]<<8)+buffRX[3]);					
					iniparser_set(iniDict,"payload:id",stmp);
					
					//cam delay in ms
					snprintf(stmp,10,"%d", buffRX[4]*1000);					
					iniparser_set(iniDict,"payload:cam_delay",stmp);
					
					//g delay in ms
					snprintf(stmp,10,"%d", buffRX[5]*1000);					
					iniparser_set(iniDict,"payload:g_delay",stmp);
					
					//buffer max
					snprintf(stmp,10,"%d", buffRX[6]);					
					iniparser_set(iniDict,"payload:buffer",stmp);
					
					Save_INI_File(iniDict, strPathCfg);
				}	
				
				//reload ini file
				iniDict = iniparser_load(strPathCfg);
				
				//read cfg value
				if(iniDict)
				{
					idPayload = iniparser_getint(iniDict,"payload:id",100);
					delayPixel = iniparser_getint(iniDict,"payload:cam_delay",120000);
					delayGyrodataSending = iniparser_getint(iniDict,"payload:g_delay",20000);
					buffer_max_num = iniparser_getint(iniDict,"payload:buffer",64);
				}
				
				//send reply always
				snprintf((char*)buffRX, 25, "f,%d,%d,%d,%d\r", idPayload, delayPixel, delayGyrodataSending,buffer_max_num);
                cprintf(COM_PORT, buffRX);
                opsState = STATE_IDLE; //go back to idle
                
                #if VERBOSE==1
                printf("send config reply = %s\r\n", buffRX);
                #endif				
				break;

            default:
                break;
        }
    }

    //release cam
    cvReleaseCapture(&camHdl);

    //release port
    CloseComport(COM_PORT);
    
    //close bus
	closeBus(i2c_hdl);
	
	//free ini handler
	if(iniDict)
		iniparser_freedict(iniDict);
	
	//cek shutdown atau restart
	switch (opsState) 
	{
		case STATE_SHUTDOWN_OS:
			system("sudo shutdown now");
			break;
			
		case STATE_RESTART_OS:
			system("sudo shutdown -r now");
			break;
			
		default:
			break;
	}

    //return
    return (EXIT_SUCCESS);
}
예제 #11
0
int main(int argc, char *argv[] )
{
  int cport_nr=16,        /* /dev/ttyS0 (COM1 on windows) */
      bdrate=9600;       /* 9600 baud */
	int i, n;
	unsigned char buf[4096];
//  unsigned char message[] = "Hell of a world";
  char bufTest[] = "HALT!!";
  char fifoFilename[] = "/tmp/trafficLight.fifo";
  char shellFilename[] = "/usr/bin/trafficLightShutdown.sh";
  pid_t pidSystem = fork();
	pid_t pidArduino = fork();

  if(OpenComport(cport_nr, bdrate)) {
    printf("Can not open comport\n");
    return(0);
  }

//  mkfifo(fifoFilename, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH| S_IWOTH);
	
	switch(pidSystem) {
		case -1:
			/* error occured */
			break;
		case 0:
			/* child process listen to the file */
	    // read the fifo file and see if anything was sent to it.
			readSystemInput(fifoFilename);
			break;
		default:
			/* parent stuff work on */
			break;
	}
/*	
	switch(pidArduino) {
		case -1:
			// error occured
			break;
		case 0:
			// child process listen to the file 
	    // read the fifo file and see if anything was sent to it.
//			readArduinoInput(cport_nr, shellFilename, bufTest);
			break;
		default:
			// parent stuff work on 
			break;
	}
*/
/*
  while(sentinel == 1)
  {
    n = PollComport(cport_nr, buf, 4095);
    if(n > 0)
    {
      buf[n] = 0;   // always put a "null" at the end of a string! 
      for(i=0; i < n; i++)
      {
        if(buf[i] < 32)  // replace unreadable control-codes by dots
        {
          buf[i] = '.';
        }
      }
      int comp = strncmp((char *)buf, (char *)bufTest, 4);
      if(comp == 0) {
      	execv(shellFilename, argv);
      	sentinel = 0;
      }
      printf("received %i bytes: %s\n", n, (char *)buf);
    }
#ifdef _WIN32
    Sleep(100);  // it's ugly to use a sleeptimer, in a real program, change the while-loop into a (interrupt) timerroutine 
#else
    usleep(100000);  // sleep for 100 milliSeconds 
#endif
  }
	*/

/*
  int len = sizeof(message);
  printf("Size is reported as: %d\n", len);
  int sendData = SendBuf(cport_nr, message, sizeof(message));
//  int sendData = cprintf(int comport_number, const char *text)
  if(sendData < 0) {
  	printf("Data was not sent properly\n");
  } else {
  	printf("Bytes reported as: %d\n", sendData);
  	printf("It SAYS we sent the data right\n");
  }
*/

  // delete the FIFO file
  /*
  int reResult = remove(fifoFilename);
  if(reResult == 0) {
  	printf("File removed\n");
  }
  */
  printf("Exiting file\n");
  return(0);
}
예제 #12
0
int main(int argc, char *argv[])
{
    unsigned char buffer[4096] = {0};
    int bufferLen = 0;
    int bytesReceived = 0;
    int bytesWritten = 0;
    int timer = 0;
    unsigned int deviceId[3];
    Command command;
    int extra = -1;
    
    if (argc < 3)
    {
        print_error("Usage: insteon deviceId [on|off|status|temp_ambient]\n");
        return 1;
    }

    // Parse arguments
    parse_device(argv[1], deviceId);
    command = parse_command(argv[2]);
    if (argc > 3)
        extra = parse_extra(argv[3]);

    if (command < 0)
    {
        print_error("Invalid command name!\n");
        return 1;
    }

    print_debug("*****************\n");
    print_debug("Device: %s\n", argv[1]);
    print_debug("Command: %s\n", argv[2]);
    if (argc > 3)
        print_debug("Extra: %s\n", argv[3]);
    print_debug("*****************\n");

    if (acquire_lock())
    {
        print_error("Timeout while acquiring lock!\n");
        return 1;
    }
    
    print_debug("Opening comport\n");

    if(OpenComport(comport, 19200))
    {
        print_error("Can not open comport\n");
        release_lock();
        return 1;
    }
    
    // Send command
    bytesWritten = send_command(deviceId, command, extra);
    if (bytesWritten < 0)
    {
        print_error("Invalid command or internal error!\n");
        goto return_error;
    }

    // Wait for response
    while(1)
    {
        bytesReceived = PollComport(16, buffer + bufferLen, 4095);
        //print_debug("br=%d bl=%d  ", bytesReceived, bufferLen);
        bufferLen += bytesReceived;
        //print_debug("br=%d bl=%d\n", bytesReceived, bufferLen);
        if(bytesReceived > 0)
        {
            int i;
            timer = 0;
            print_debug("received %i bytes: (%i total)", bytesReceived, bufferLen);
            for(i=0; i < bufferLen; i++)
            {
                print_debug("%02X ", buffer[i]);
            }
            print_debug("\n");

            if (bufferLen > bytesWritten)
            {
                unsigned int ack = *(buffer + bytesWritten);
                unsigned char* message = buffer + bytesWritten + 1;
                int messageLen = bufferLen - bytesWritten - 1;
                
                if (ack != CMD_ACK)
                {
                    print_error("Message not acknowledged!\n");
                    goto return_error;
                }
                
                if (messageLen > 1)
                {
                    if (message[0] == CMD_PREFIX)
                    {
                        if (message[1] == CMD_INSTEON_STD_RECEIVED)
                        {
                            if (messageLen >= 11)
                            {
                                static int resultCounter = 0;
                                
                                print_debug("Insteon standard message received!\n");
                                if(parse_message(command, message))
                                {
                                    goto return_error;
                                }
                                
                                if(command == CMD_TEMP_GET_SETPOINT && resultCounter == 0 && extra == 3)
                                {
                                    resultCounter++;
                                    bufferLen -= 11;
                                }
                                else
                                {
                                    goto return_success;
                                }
                            }
                        }
                        else if (message[1] == CMD_INSTEON_EXT_RECEIVED)
                        {
                            if (messageLen >= 25)
                            {
                                print_debug("Insteon extended message received!\n");
                                if(parse_message(command, message))
                                {
                                    goto return_error;
                                }
                                goto return_success;
                            }
                        }
                        else if (message[1] == CMD_X10_RECEIVED)
                        {
                            if (messageLen >= 4)
                            {
                                print_debug("X10 message received!\n");
                                if(parse_message(command, message))
                                {
                                    goto return_error;
                                }
                                goto return_success;
                            }
                        }
                        else
                        {
                            print_error("Unexpected message received! '");
                            for(i=0; i < messageLen; i++)
                            {
                                print_error("%02X ", message[i]);
                            }
                            print_error("'\n");
                            goto return_error;
                        }
                    }
                    else
                    {
                        print_error("Unexpected message header received! '");
                        for(i=0; i < messageLen; i++)
                        {
                            print_error("%02X ", message[i]);
                        }
                        print_error("'\n");
                        goto return_error;
                    }
                }
            }
        }

        usleep(250);
        timer++;
        if (timer > 4000)
        {
            print_error("Timeout while waiting for bytes!\n");
            goto return_error;
        }
    }

return_success:
    CloseComport(16);
    release_lock();
    return 0;
return_error:
    CloseComport(16);
    release_lock();
    return 1;
}
int main()
{
	MYSQL* con ;
	MYSQL_RES * res ;
	MYSQL_ROW row ;

    con = mysql_init(NULL);
	
   char *server = "localhost";
   char *user = "******";
   char *password = "******"; /* set me first */

   char *database = "zandu";


	// initiate the com port 
  int i, n,cport_nr=16,/* /dev/ttyS0 (COM1 on windows) */  bdrate=9600;       /* 9600 baud */
  if(OpenComport(cport_nr, bdrate))
  {
    printf("Can not open comport\n");

    return(0);
  }

 // initiate the mysql connection
   if (!mysql_real_connect(con, server,user, password, database, 0, NULL, 0)) {
      fprintf(stderr, "%s\n", mysql_error(con));
      exit(1);
   }

    //start the main logic

	char query[100] ;
	char * storeTime  = (char *)malloc(100);
	char * timeFormat = (char *)malloc(100);
	timeFormat = "%Y-%m-%d %T";

	
	
	
	//sprintf(query,"select * from SendToBot order by timestampdiff(microsecond,time_stamp,current_timestamp) desc");
	sprintf(query,"select * from sendtobot");

	 /* send SQL query */
   if (mysql_query(con, query)) 
   {
      fprintf(stderr, "%s\n", mysql_error(con));
      exit(1);
   }
   i = 0 ;
   int j =  0;

	while(1)
    {
		res = mysql_use_result(con);
		while( (row = mysql_fetch_row(res) ) != NULL )
		{
			
			printf("%s\t %s\t %d \t %s\n",row[0],row[3],i,row[2]);

			int n , j ;
			
			int length = strlen(row[0]);
			
			for(j = 0 ; j < length  ; j ++)
			{
				n = SendByte(cport_nr,row[0][j]) ;
				
			}
			
			n = SendByte(cport_nr,':') ;	//To seperate ID from Command 
			
			length = strlen(row[3]);

			for(j = 0 ; j < length  ; j ++)
			{
				n = SendByte(cport_nr,row[3][j]) ;
				
			}
			
			//n = SendBuf(cport_nr,row[3],2) ;
            i ++ ;		
			strcpy(storeTime,row[2]) ;	
		}
		
		
		sprintf(query,"delete from sendtobot where time_stamp <= \"%s\"",storeTime);
		if (mysql_query(con,query)) 
		{
      		fprintf(stderr, "%s\n", mysql_error(con));
		    exit(1);
   		}
		
		mysql_free_result(res);
		
		sprintf(query,"select * from sendtobot order by timestampdiff(microsecond,time_stamp,str_to_date(\'%s\',\'%s\'))desc;",storeTime,timeFormat);
		//sprintf(query,"select * from sendtobot");
		if (mysql_query(con,query)) 
		{
      		fprintf(stderr, "%s\n", mysql_error(con));
		    exit(1);
   		}


   	}
  
}
int main(int argc, char *argv[])
{

	   MYSQL* con ;
	   MYSQL_RES * res ;
	   MYSQL_ROW row ;

	   con = mysql_init(NULL);
	
	   char *server = "localhost";
	   char *user = "******";
	   char *password = "******"; /* set me first */

	   char *database = "zandu";


	   int i, n,cport_nr=16,        /* /dev/ttyS0 (COM1 on windows) */bdrate=9600;       /* 9600 baud */

	   unsigned char buf[4096];
	   char sensorValueQuery[200], registerQuery[200];
	   char temp ;
	   char sensorValues[100];
	   int count  = 0 ;
	   int j;
	   int gotNewBot = 0, regNewBot = 0, botId = -1;
	   
	   if(argc == 2){
			cport_nr = atoi(argv[1]);
	   }

	   printf("I am here on  31\n");
	   if(OpenComport(cport_nr, bdrate))
	   {
		 printf("Can not open comport\n");
		 return(0);
	   }

	  // initiate the mysql connection
      if (!mysql_real_connect(con, server,user, password, database, 0, NULL, 0)) 
      {
        fprintf(stderr, "%s\n", mysql_error(con));
        exit(1);
      }

		/*queries for different works */
		
		
		
		/**/

		
	   while(1)
	  {
		n = PollComport(cport_nr, buf, 1);
		
	
		if(n > 0)
		{
		
			/* Registration logic */
			if(gotNewBot && n == 1){
				botId = (int) buf[0];
				regNewBot = 1;
			}
			else if(n == 2){
				if(buf[0] == '@'){
					botId = (int) buf[1];
					regNewBot = 1;
				}
			}
			else if(n == 1){
				if(buf[0] == '@'){
					gotNewBot = 1;
					continue;
				}
			}
			
			if(regNewBot){
				sprintf(registerQuery,"insert into bot values (\'%d\',CURRENT_TIMESTAMP,\'%d\')",botId,0);
			
				if (mysql_query(con,registerQuery)) 
				{
					fprintf(stderr, "%s\n", mysql_error(con));
					gotNewBot = 0;regNewBot = 0;
					continue;
					//exit(1);
				}
				//mysql_free_result(res);
			
				sprintf(registerQuery,"insert into sendtobot values (\'%d\',\'%s\',CURRENT_TIMESTAMP,\'%c\')",botId,"server",'Y');
			
				if (mysql_query(con,registerQuery)) 
				{
					fprintf(stderr, "%s\n", mysql_error(con));
					//exit(1);
				}
				
				sprintf(registerQuery,"insert into botinfo values (\'%d\',\'%d\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\')",botId,1101, "0:0:0:0:0:0:0:0:0", "0:0:0:0:0:0:0:0:0:0:0:0", "0","0", "0","10", "10", "0", "0");
			
				if (mysql_query(con,registerQuery)) 
				{
					fprintf(stderr, "%s\n", mysql_error(con));
					//exit(1);
				}
				
				gotNewBot = 0;regNewBot = 0;
				continue;
			}
				
				/* Registration logic ends*/
		  
		  /*sensor wala logic*/
		  sensorValues[count ++ ]  = buf[0] ;
		  
		  if(sensorValues[count-1] == '#')
		  {
				for(j =  0 ; sensorValues[j] != '#'; j++)
				{
					printf("%c",sensorValues[j]);
				}
				sensorValues[j] = '\0';		//else garbage values can go into a database
				
				if(sensorValues[2] == 'S'){
					sprintf(sensorValueQuery,"update botinfo set sensor=\'%s\' where bot_id = \'%d\' ;",sensorValues+4,sensorValues[0]);
					//puts(sensorValues);
				}
				else if(sensorValues[2] == 'P'){
					sprintf(sensorValueQuery,"update botinfo set port_io=\'%s\' where bot_id = \'%d\' ;",sensorValues+4,sensorValues[0]);
				}
			// 0 replaced by 2||sensorValues + 2 repalce by sensorValues + 4 || botID replaced by sensorValues[0] || %d replaced by %c
				if (mysql_query(con,sensorValueQuery)) 
				{
					printf("%s\n",sensorValueQuery);
			    	fprintf(stderr, "%s\n", mysql_error(con));
		    		//exit(1);
			   	}
				mysql_free_result(res);

				printf("\n");
				count = 0;
		  }

	
		  buf[n] = 0;   
		  for(i=0; i < n; i++)
		  {
		    if(buf[i] < 32)  /* replace unreadable control-codes by dots */
		    {
		      buf[i] = '.';
		    }
		  }

		 
		  
		}


		}


  return(0);
}
예제 #15
0
int main(int argc, char *argv[])
{
	an_decoder_t an_decoder;
	an_packet_t *an_packet;
	
	system_state_packet_t system_state_packet;
	raw_sensors_packet_t raw_sensors_packet;
	
	int bytes_received;

	if (argc != 3)
	{
		printf("Usage - program com_port baud_rate\nExample - packet_example.exe COM1 115200\n");
		exit(EXIT_FAILURE);
	}
	
	/* open the com port */
	if (OpenComport(argv[1], atoi(argv[2])))
	{
		exit(EXIT_FAILURE);
	}
	
	an_decoder_initialise(&an_decoder);

	while (1)
	{
		if ((bytes_received = PollComport(an_decoder_pointer(&an_decoder), an_decoder_size(&an_decoder))) > 0)
		{
			/* increment the decode buffer length by the number of bytes received */
			an_decoder_increment(&an_decoder, bytes_received);
			
			/* decode all the packets in the buffer */
			while ((an_packet = an_packet_decode(&an_decoder)) != NULL)
			{
				if (an_packet->id == packet_id_system_state) /* system state packet */
				{
					/* copy all the binary data into the typedef struct for the packet */
					/* this allows easy access to all the different values             */
					if(decode_system_state_packet(&system_state_packet, an_packet) == 0)
					{
						printf("System State Packet:\n");
						printf("\tLatitude = %f, Longitude = %f, Height = %f\n", system_state_packet.latitude * RADIANS_TO_DEGREES, system_state_packet.longitude * RADIANS_TO_DEGREES, system_state_packet.height);
						printf("\tRoll = %f, Pitch = %f, Heading = %f\n", system_state_packet.orientation[0] * RADIANS_TO_DEGREES, system_state_packet.orientation[1] * RADIANS_TO_DEGREES, system_state_packet.orientation[2] * RADIANS_TO_DEGREES);
					}
				}
				else if (an_packet->id == packet_id_raw_sensors) /* raw sensors packet */
				{
					/* copy all the binary data into the typedef struct for the packet */
					/* this allows easy access to all the different values             */
					if(decode_raw_sensors_packet(&raw_sensors_packet, an_packet) == 0)
					{
						printf("Raw Sensors Packet:\n");
						printf("\tAccelerometers X: %f Y: %f Z: %f\n", raw_sensors_packet.accelerometers[0], raw_sensors_packet.accelerometers[1], raw_sensors_packet.accelerometers[2]);
						printf("\tGyroscopes X: %f Y: %f Z: %f\n", raw_sensors_packet.gyroscopes[0] * RADIANS_TO_DEGREES, raw_sensors_packet.gyroscopes[1] * RADIANS_TO_DEGREES, raw_sensors_packet.gyroscopes[2] * RADIANS_TO_DEGREES);
					}
				}
				else
				{
					printf("Packet ID %u of Length %u\n", an_packet->id, an_packet->length);
				}
				
				/* Ensure that you free the an_packet when your done with it or you will leak memory */
				an_packet_free(&an_packet);
			}
		}
#ifdef _WIN32
    Sleep(10);
#else
    usleep(10000);
#endif
	}
}
예제 #16
0
파일: main.c 프로젝트: alvarop/cwRoute
int main( int argc, char *argv[] )
{   
  uint8_t serial_buffer[BUFFER_SIZE]; 
  uint8_t packet_buffer[BUFFER_SIZE];
  uint8_t final_buffer[BUFFER_SIZE];  
  //uint8_t adc_sample_buffer[ADC_MAX_SAMPLES];    
  uint16_t buffer_offset = 0;
  uint8_t new_packet = 0;
 
  uint16_t bytes_read = 0;  
  
  // Handle interrupt events to make sure files are closed before exiting
  (void) signal( SIGINT, sigint_handler );

  tx_power = dbm_to_watt(1l);
  target_rssi = dbm_to_watt(-60l);

  // Make sure input is correct
  if( argc < 2 )
  {
    printf("Usage: %s port baudrate\n", argv[0]);
    return 0;
  }  
  
  printf("Power control test\r\n");
  
  // Convert string serial number to integer
  serial_port_number = atoi( argv[1] );
  
 
  // Use RS232 library to open serial port  
  if ( OpenComport( serial_port_number, atoi(argv[2]) ) )
  {
    
    printf("Error opening serial port.\n");
    return 1;
  }
    
  // Flush the port
  while( PollComport( serial_port_number, serial_buffer, BUFFER_SIZE ) );
  
  memset( serial_buffer, 0x00, sizeof(serial_buffer) );
  
  
   
  // Run forever
  for(;;)
  {  
    // Read a buffer full of data (if available)
    bytes_read = PollComport( serial_port_number, serial_buffer, BUFFER_SIZE );
    if( bytes_read > 0 )
    {

      if( bytes_read >= BUFFER_SIZE )
      {
        printf("Uh oh!\n");
      }
      else
      {
        
        memcpy( packet_buffer + buffer_offset, serial_buffer, bytes_read );                        
       
        if ( packet_in_buffer( packet_buffer ) )
        {          
                             
          buffer_offset = 0;
          
          new_packet = 1;
          bytes_read = find_and_escape_packet( packet_buffer, final_buffer );          
          
        } 
        else
        {   
          
          buffer_offset += bytes_read;
          
          if( buffer_offset > BUFFER_SIZE )
          {
            printf("damn...\n");
            memset( packet_buffer, 0x00, sizeof(packet_buffer) );
            memset( serial_buffer, 0x00, sizeof(serial_buffer) );
            buffer_offset = 0;
          }
        }
        
        if( new_packet == 1 )
        {
          
          process_packet( final_buffer );
          
          new_packet = 0;
          memset( packet_buffer, 0x00, sizeof(packet_buffer) );
        }      

      }
    }
    memset( serial_buffer, 0x00, sizeof(serial_buffer) );
    
    // Don't take up all the processor time    
    usleep(20000);
    if( 0 == send_message-- )
    {
      SendByte( serial_port_number, next_power ); // Send initial packet
      send_message = 1;
      
      if(next_power == 0xff)
      {
        printf("*");
      }
      // If no message is received before the next round, use full power
      next_power = 0xff;
    }
  }  

  return 0;
}
예제 #17
0
// Open the communication (done when you create it)
void CCPCBooster::OpenPort()
{
	if (_currentState == PortOpened)
	{
		ClosePort();
	}

	_currentState = PortFailed;

/**
 * code specifique aux windows
 */
#if _WINDOWS

    _COMPortHandle = CreateFile(_COMPortNumber.c_str(),
						GENERIC_READ | GENERIC_WRITE,
						0,								// must be opened with exclusive-access
						NULL,							// no security attributes
						OPEN_EXISTING,					// must use OPEN_EXISTING
						0,								// not overlapped I/O
						NULL);							// hTemplate must be NULL for comm devices
	
	if (_COMPortHandle == INVALID_HANDLE_VALUE) 
	{
		_currentError = ErrInvalidHandle;
	}
	else
	{	
		// Build on the current configuration, and skip setting the size
		// of the input and output buffers with SetupComm.
		DCB dcb;
		BOOL fSuccess = GetCommState(_COMPortHandle, &dcb);
		
		if (fSuccess != TRUE) 
		{
			_currentError = ErrGetStateFailed;
		}
		else
		{
		// configure COM properties
			// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wcecoreos5/html/wce50conprogrammingserialconnections.asp
			dcb.BaudRate = CBR_115200;				// set the baud rate
			dcb.ByteSize = 8;						// data size, xmit, and rcv
			dcb.Parity = NOPARITY;					// no parity bit
			dcb.StopBits = ONESTOPBIT;				// one stop bit
			// additionnal properties to fix some USB crappy serial interface
			dcb.fBinary = TRUE;						// Binary mode; no EOF check
			dcb.fOutxCtsFlow = FALSE;				// No CTS output flow control
			dcb.fOutxDsrFlow = FALSE;				// No DSR output flow control 
			dcb.fDtrControl = DTR_CONTROL_DISABLE;
			dcb.fDsrSensitivity = FALSE;			// DSR sensitivity
			dcb.fTXContinueOnXoff = FALSE;			// XOFF continues Tx
			dcb.fOutX = FALSE;						// No XON/XOFF out flow control
			dcb.fInX = FALSE;						// No XON/XOFF in flow control 
			dcb.fNull = FALSE;						// Disable null stripping 
			dcb.fRtsControl = RTS_CONTROL_DISABLE;
			dcb.fAbortOnError = FALSE;				// Do not abort reads/writes on error

			fSuccess = SetCommState(_COMPortHandle, &dcb);
			
			if (fSuccess != TRUE) 
			{
				_currentError = ErrSetStateFailed;
			}
			else
			{
				_currentState = PortOpened;
			}
			
			COMMTIMEOUTS timeOut;
			GetCommTimeouts(_COMPortHandle, &timeOut);

			timeOut.ReadTotalTimeoutMultiplier = 10;

			SetCommTimeouts(_COMPortHandle, &timeOut);


			}
		}

/**
 * Code specifique aux unices
 */
#else
	if (OpenComport(_COMPortNumber.c_str(),115200) == 0)
	{
	    _currentState = PortOpened ;
	    _COMPortHandle = 0;
	}
#endif
	
}
예제 #18
0
int main(int argc,char** argv)
{

	ros::init(argc, argv, "servo");
	ros::param::get("/port", port);
	if(port == "/dev/ttyS0")
		Comport = 0;
	else if(port == "/dev/ttyS1")
			Comport = 1;
	else if(port == "/dev/ttyS2")
			Comport = 2;
	else if(port == "/dev/ttyS3")
			Comport = 3;
	else if(port == "/dev/ttyS4")
			Comport = 4;
	else if(port == "/dev/ttyS5")
			Comport = 5;
	else if(port == "/dev/ttyS6")
			Comport = 6;
	else if(port == "/dev/ttyS7")
			Comport = 7;
	else if(port == "/dev/ttyS8")
			Comport = 8;
	else if(port == "/dev/ttyS9")
			Comport = 9;
	else if(port == "/dev/ttyS10")
			Comport = 10;
	else if(port == "/dev/ttyS11")
			Comport = 11;
	else if(port == "/dev/ttyS12")
			Comport = 12;
	else if(port == "/dev/ttyS13")
			Comport = 13;
	else if(port == "/dev/ttyS14")
			Comport = 14;
	else if(port == "/dev/ttyS15")
			Comport = 15;
	else if(port == "/dev/ttyUSB0")
			Comport = 16;
	else if(port == "/dev/ttyUSB1")
			Comport = 17;
	else if(port == "/dev/ttyUSB2")
			Comport = 18;
	else if(port == "/dev/ttyUSB3")
			Comport = 19;
	else if(port == "/dev/ttyUSB4")
			Comport = 20;
	else if(port == "/dev/ttyUSB5")
			Comport = 21;
	ros::param::get("/baudrate", baudrate);
	ros::param::get("/servo_id", servo_id);
	ros::param::get("/servo_speed", servo_speed);	
	ros::param::get("/max_angle", max_angle);
	ros::param::get("/min_angle", min_angle);
	OpenComport(Comport, baudrate);
	servoAction servo(ros::this_node::getName());
	if (!ros::ok())
	{	
	CloseComport(Comport);
	}	
	ros::spin();
		
	return 0;
}
예제 #19
0
파일: serial.c 프로젝트: coolya/mbeddr.core
int 
initSerial() {
  return OpenComport(SERIAL_PORT, SERIAL_BAUD);
}