Пример #1
0
ModCom::~ModCom(void) {
	if (fd >= 0) serialport_close(fd);
	if (dd == "" || devDescriptionList.size() == 0) return;
	vector<string>::iterator redodev;
	redodev = find(devDescriptionList.begin(), devDescriptionList.end(), dd);
	devDescriptionList.erase(redodev);
}
Пример #2
0
int main (int argc, char *argv[])
{
    optarg = (char *)malloc(100*sizeof(char));

    //fill optarg with the path to the serial transmitter
    find_serial_transmitter();

    FILE *log_file;
    char buf[1000];
    char *str_array[140]={"\0"};
    int i=0;

    //Open the FM stations log file that will become the device database
    log_file = fopen("log.txt","r");
    if (!log_file){
        printf("ERROR: Could not open FM Stations log file for reading.\n");
        return -1;
    }

    //create a connection over the virtual serial port
    open_port();

    //send the start sequence
    perror("START SEQUENCE:\n");
    send_string("$$$");
    printf("\n\n");

    //wait a while to make sure the device has detected the start sequence and is ready for data
    usleep(5000000);

    //parse the log file line by line
    while (fgets(buf,1000, log_file)!=NULL) 
    {
        //keep track of each line
        str_array[i] = buf;
        strip_newline( str_array[i], 210);

        //prepare, parse, and transmit the data within each line
        parse_line(line_prep(str_array[i]));
        i++;
    }

    //close the log file
    fclose(log_file);

    //make sure the device has had enough time to write all the data before sending end sequence
    usleep(4000000);

    //send the end sequence
    printf("END SEQUENCE:\n");
    send_string("^^^");
    printf("\n\n");

    //terminate the virtual serial port connection
    serialport_close(fd);
    return 0;
}
Пример #3
0
int open_port(void){
    if( fd!=-1 ) {
        serialport_close(fd);
        printf("closed port %s\n",serialport);
    }
    strcpy(serialport,optarg);
    fd = serialport_init(optarg, baudrate);
    if( fd==-1 ){
        printf("couldn't open port");
        return -1;
    } 
    printf("opened port %s\n",serialport);
    serialport_flush(fd);
    
    return 0;
}
Пример #4
0
int main (int argc, char *argv[])
{

    FILE *file_hndl;
    char buf[1000];
    char *str_array[140]={"\0"};
    int i;

    //Open log file
    file_hndl =fopen("log.txt","r");
    if (!file_hndl){
        printf("ERROR: Could not open file for reading.");
        return -1;
    }

    //Fetch each line into a string
    while (fgets(buf,1000, file_hndl)!=NULL){
        str_array[i] = buf;
        //printf("%s",str_array[i]);

        strip_newline( str_array[i], 210);

        parse_line(line_prep(str_array[i]));
        i++;
    }

    //Close File
    fclose(file_hndl);

    open_port();

    send_string("@");
    send_string("testing");
    send_string("#");

    serialport_close(fd);
    return 0;
}
Пример #5
0
gint disconnectSerial() {
	if (fd >= 0) {
		serialport_close(fd);
	}
	return -1;
}
void main(void)
{

    int fd, Error;
    int baud = 9600;
    char serialport[] = "/dev/ttyACM0";

    union uuFreq {
        char fBytes[4];
        float fFloat;
    } uFreq;
    uFreq.fFloat = 50.00;

    union uuTime {
        char tBytes[4];
        unsigned long tLong;
    } uTime;
    uTime.tLong = 5000;

    union uuChannel {
       char cBytes[2]; 
       unsigned int cInt;
    } uChannel;
    uChannel.cInt = 1;

    fd = serialport_init(serialport, baud);
    Error = serialport_flush(fd);


    // Loop through several times then send song over

    for (int i = 0; i < 71; i++)
    {
    if (i == 70) 
    {
        uFreq.fFloat = 0xFFFFFFFF;
        uTime.tLong = 0xFFFF;
        uChannel.cInt = 0xFF;
    }

    // Send Frequency - incremented by 20
    uFreq.fFloat = uFreq.fFloat + 20.0;
    Error = serialport_writebyte(fd, uFreq.fBytes[0]);
    tcdrain(fd);
    Error = serialport_writebyte(fd, uFreq.fBytes[1]);
    tcdrain(fd);
    Error = serialport_writebyte(fd, uFreq.fBytes[2]);
    tcdrain(fd);
    Error = serialport_writebyte(fd, uFreq.fBytes[3]);
    tcdrain(fd);

    // Send Time - incremented by 500 ms
    uTime.tLong = uTime.tLong + 500;
    Error = serialport_writebyte(fd, uTime.tBytes[0]);
    tcdrain(fd);
    Error = serialport_writebyte(fd, uTime.tBytes[1]);
    tcdrain(fd);
    Error = serialport_writebyte(fd, uTime.tBytes[2]);
    tcdrain(fd);
    Error = serialport_writebyte(fd, uTime.tBytes[3]);
    tcdrain(fd);

    // Send Channel
    Error = serialport_writebyte(fd, uChannel.cBytes[0]);
    tcdrain(fd);
    Error = serialport_writebyte(fd, uChannel.cBytes[1]);
    tcdrain(fd);

    // Send \0
    Error = serialport_writebyte(fd, '\0');
    
    usleep(50000);
    tcdrain(fd);
    }


    serialport_close(fd);


//return 0;
}
Пример #7
0
int main(int argc, char** argv){

   /*******************
    *  Base Drive Variables
    *
    * LOOP_RATE         defines how fast we send orders to the arduino
    * ORDER_TIMEOUT     is the maximum amount of time between recieving orders
    *                   before we shut the motors off
    *
    * BAUDRATE          baudrate to arduino
    * SERIAL_DEV        the defauly dev file pointing to the arduino
    * READ_CHAR_TIMEOUT the timeout to wait for the next character in a
    *                   message, in us
    * SERIAL_RESPONSE_TIMEOUT The timeout to wait for a response to our
    *                         query, in us
    */
   double LOOP_RATE = 10.0;
   double ORDER_TIMEOUT = 0.25;

   int BAUDRATE = B115200;
   char* SERIAL_DEV = "/dev/ttyUSB0";
   int READ_CHAR_TIMEOUT = 30;
   int SERIAL_RESPONSE_TIMEOUT = 100;
   char START_CHAR = '`';

   /********************
    * Set up ROS node
    */
   ros::init(argc, argv, "TableMotorToSerial");
   ros::NodeHandle n;

   ROS_INFO( "Starting Subscriber" );
   ros::Subscriber sub = n.subscribe("DriveTable", 2, callbackTableMotorToSerial ); 

   ros::Publisher pub = n.advertise<alfred_msg::TableEncoders>("TableEncoders", 2);

   /********************
    * Setup loop variables and start serial
    */
   char* serialDevice = SERIAL_DEV;
   if( argc > 1 )
      serialDevice = argv[1];

   int fd = serialport_init(serialDevice, BAUDRATE);
   if(fd < 0){
      ROS_ERROR( "Could not open serial device \'%s\'\n", serialDevice); 
      return -1;
   }
   usleep( 3000 * 1000 );
   
   ros::Rate rate(LOOP_RATE);
   int maxNumLoopsWithoutOrder = (int)( ORDER_TIMEOUT * LOOP_RATE );
   int numLoopsWithoutOrder(-1);
    
   
   while (n.ok()) {

      // If we haven't yet started
      if( numLoopsWithoutOrder == -1){
         tableOrder_serialArduino1 = 0.0;
         tableOrder_serialArduino2 = 0.0;
         tableOrder_serialArduino3 = 0.0;
         tableOrder_serialArduino4 = 0.0;
      }
      // Safety Check 1 : time without orders
      else if( numLoopsWithoutOrder >= maxNumLoopsWithoutOrder ){

         tableOrder_serialArduino1 = 0.0;
         tableOrder_serialArduino2 = 0.0;
         tableOrder_serialArduino3 = 0.0;
         tableOrder_serialArduino4 = 0.0;
         ROS_ERROR( "Base Motor to Serial hasn't received a new motor order in %f mS!", 1000 * ORDER_TIMEOUT );
      }
      // Safety check passed, send 
    
      if( numLoopsWithoutOrder >= 0 ) 
         numLoopsWithoutOrder++;
      if( receivedOrder_serialArduino == true ){
         numLoopsWithoutOrder = 0;
         receivedOrder_serialArduino = false;
      }

      ROS_INFO( "Sending output to table: [%f, %f, %f, %f]",
                  tableOrder_serialArduino1,
                  tableOrder_serialArduino2,
                  tableOrder_serialArduino3,
                  tableOrder_serialArduino4);
 
      //write
      std::stringstream ss;
      ss << "`" 
         << tableOrder_serialArduino1 << ";"
         << tableOrder_serialArduino2 << ";"
         << tableOrder_serialArduino3 << ";"
         << tableOrder_serialArduino4 << ";\0";
      std::string msg = ss.str();
   
      int isok = serialport_write(fd, msg.c_str() );

      // now read, and wait for the arduino to reply with the encoder values
      int encoders[4];
      char buf[10];

      // First, wait for a response      
      if( serialport_read_until(fd, buf, START_CHAR, SERIAL_RESPONSE_TIMEOUT) <= 0)
      {
         ROS_ERROR("ERROR: Timeout on serial response message start!");
         for( int i(0); i < 4; i++ )
            encoders[i]=-1;
      }
      else{
         for( int i(0); i < 4; i++ ){
            isok = serialport_read_until(fd, buf, ';',  READ_CHAR_TIMEOUT );
            if( isok <= 0 ){
               ROS_ERROR("ERROR: Timeout reading message");
               break;
            }
            encoders[i] = std::atoi(buf);
         }
         if( isok <= 0 )
            for( int i(0); i < 4; i++ )
               encoders[i]=-1;
      }

      ROS_INFO( "Publishing Encoder Vals: [%d, %d, %d, %d]",
                  encoders[0],
                  encoders[1],
                  encoders[2],
                  encoders[3]);

      alfred_msg::TableEncoders encTopic;
      encTopic.enc1 = encoders[0];
      encTopic.enc2 = encoders[1];
      encTopic.enc3 = encoders[2];
      encTopic.enc4 = encoders[3];

      pub.publish(encTopic);
   
      ROS_INFO("\n");
      rate.sleep();
      ros::spinOnce();
   }

   serialport_close(fd);
   return 0;
}
Пример #8
0
int main(int argc, char *argv[]) {
  if (eval_flag(argc,argv,"-h\0")) {
    printf("Usage: lold [-p PORT] [-D DELAY] [-d DEVICE]\n\n");
    return EXIT_FAILURE;
  }

  delay = int_arg(eval_arg(argc, argv, "-D\0", NULL), DEF_DELAY);
  port = int_arg(eval_arg(argc, argv, "-p\0", NULL), DEF_LOLD_PORT);
  device = eval_arg(argc, argv, "-d\0", NULL);
  to_stdout = eval_flag(argc, argv, "--stdout\0");

  if (!to_stdout && device==NULL) //no device provided?
    device = autodetect();
  if (!device && !to_stdout) //no device found by autodetect?
    fprintf(stderr, "No serial USB device found! (Try -d flag?) Output to stdout.\n");

  pthread_mutex_init(&imutex, NULL); //init mutex for interrupted flag
  pthread_mutex_init(&qmutex, NULL); //init mutex for queue

  //Start web server thread listening for clients sending stuff
  pthread_t serverThread;
  pthread_create(&serverThread, NULL, server_thread, NULL);
  pthread_detach(serverThread);

  //trap INT
  signal(SIGINT, sig_handler);

  LolTask *currtask = NULL; //task currently being executed

  //clean lolshield
  render_frame(device, EMPTY_FRAME);

  //loop outputting animation frames to device
  while (!shutting_down) {
    //do nothing if some client is streaming
    if (streaming) {
      sleep_ms(100);
      continue;
    }

    //New task arrived -> check stuff
    pthread_mutex_lock(&imutex);
    if (interrupted) {
      interrupted = 0;

      if (DEBUG) fprintf(stderr, "New task inserted!\n");

      if (queue==NULL)
        exit(EXIT_FAILURE); //can not happen!

      pthread_mutex_lock(&qmutex);
      LolTask *first = (LolTask*)(queue->value);
      pthread_mutex_unlock(&qmutex);

      //new arrived has higher priority? cancel current ani
      if (currtask != NULL && first->pri > currtask->pri) {
        loltask_free(currtask);
        currtask = NULL;

        if (DEBUG) fprintf(stderr, "Ani cancelled\n");
      }
    }
    pthread_mutex_unlock(&imutex);

    //load new task if neccessary
    if (currtask == NULL) {
      pthread_mutex_lock(&qmutex);
      currtask = lollist_shift(&queue);
      pthread_mutex_unlock(&qmutex);

      if (DEBUG) if (currtask != NULL) fprintf(stderr, "Ani start\n");
    }

    //nothing in queue -> just wait
    if (currtask == NULL) {
      sleep_ms(delay);
      continue;
    }

    //animation delay
    sleep_ms(currtask->delay);

    //get next frame
    char *frame = lollist_shift(&(currtask->frames));

    //current animation done?
    if (frame == NULL) {
      currtask = NULL;
      clean_tasks(); //remove aged tasks

      //render empty frame to clean lolshield -> breaks hardware text message
      //render_frame(device, EMPTY_FRAME);

      sleep_ms(delay);

      if (DEBUG) fprintf(stderr, "Ani done\n");
      continue;
    }

    //render next frame
    render_frame(device, frame);
    free(frame);
  }
  if (DEBUG) fprintf(stderr, "Shutting down\n");

  //shutting down
  render_frame(device, EMPTY_FRAME); //clean lolshield
  serialport_close(port); //close port
  pthread_cancel(serverThread); //kill server
  pthread_mutex_destroy(&qmutex); //uninit mutex
  pthread_mutex_destroy(&imutex); //uninit mutex

  close(svr_sock); //close server listening socket
  pthread_exit(NULL);
  return EXIT_SUCCESS;
}
Пример #9
0
int download_firmware(const char* download_port,const char* firmware_filename){
	int err=eDownloadErrCodeSuccess;
	unsigned char* inbuf,*outbuf;
	unsigned int inlen,outlen;
	handle_download_port = firmware_size = -1;
	threadhandle_timer = threadhandle_download = NULL;
	inbuf = outbuf = firmware_buffer = NULL;
	handle_download_port = serialport_open(download_port);
	if(handle_download_port<0){
		err = eDownloadErrCodePortError;goto failed;		
	}
	
	//now open file to buffer
	inlen = platform_readfile2buffer(firmware_filename,0,(char**)&inbuf);
	if(inlen<0){
		err = eDownloadErrCodeFileError;goto failed;
	}

	//allocate out buffer ,max size as half of inlen
	outlen = inlen;
	outbuf = (unsigned char* )malloc(outlen);
	if(!outbuf){
		err = eDownloadErrCodeUnknown;
		goto failed;
	}
	//convert to bin format
	err = mcu_hex2bin(inbuf,inlen,outbuf,&outlen);

	firmware_buffer = outbuf;	
	firmware_size = outlen;
	//only for demo
//	firmware_buffer = DEMO;
//	firmware_size=256;
	//now firmware buffer is ready;
	printf("firmware[%s] hex size[0x%x] bin size[0x%x] prepareokay!\n",firmware_filename,
		inlen,outlen);

        
	//create received thread
	threadhandle_download = platform_createthread(download_recv_thread,(void*)handle_download_port);
	if(!threadhandle_download){
		printf("create firmware download thread failed\n");
		err = eDownloadErrCodeUnknown;goto failed;
		
	}
	threadhandle_timer = platform_createthread(download_timer_thread,(void*)NULL);
	if(!threadhandle_timer){
		printf("create firmware timer thread failed\n");
		err = eDownloadErrCodeUnknown;goto failed;
	}
	
    err = Firmware_Download(firmware_buffer, firmware_size);
    if (eDownloadErrCodeSuccess==err)
    {
        printf("\n\n\n"
		"----Congratulations!Firmware download successful!----\n\n\n");
    }
    else
    {
        printf("\n\n\n"
		"----FAIL FAIL FAIL![E%d,%s]----\n\n\n",err,download_error_code2string(err));
    }
    
failed:
	if(threadhandle_timer)
		platform_terminatethread(threadhandle_timer);
	if(threadhandle_download)
		platform_terminatethread(threadhandle_download);
	if(inbuf)
		platform_releasebuffer(inbuf);
	if(outbuf)
		platform_releasebuffer(outbuf);	
	if(handle_download_port>0)
		serialport_close(handle_download_port);	
	return err;	
}
Пример #10
0
int main(int argc, char *argv[])
{
    /*accelerometer related declarations*/
    const int buf_max = 2048;

    int fd = -1;
    char serialport[buf_max];
    int baudrate = 9600;  // default
    char quiet=0;
    char eolchar = ' ';
    int timeout = 5000;
    char buf[buf_max];
    int rc,n,p;
    float xDat[103],yDat[103],zDat[103];
    float sumX=0,sumY=0,sumZ=0;
    float sum1=0,sum2=0,sum3=0;
    float stdX=0,stdY=0,stdZ=0,avgX=0,avgY=0,avgZ=0,varX=0,varY=0,varZ=0,recal=0;
    int total=1;
    int calibrate=0;
    /*---------------------------------*/

//    char stdbuffer[10];
    /*socket related declarations*/    
    int sockfd, portno, n2;
    struct sockaddr_in serv_addr;
    struct hostent *server;

    char buffer[256];
    int sendMessage=1;
   /*----------------------------*/

    if (argc==1) {
        usage();
    }

    /* parse options */
    int option_index = 0, opt;
    static struct option loptions[] = {
        {"help",       no_argument,       0, 'h'},
        {"port",       required_argument, 0, 'p'},
        {"baud",       required_argument, 0, 'b'},
        {"send",       required_argument, 0, 's'},
        {"setup",      no_argument,       0, 'S'},
        {"receive",    no_argument,       0, 'r'},
        {"flush",      no_argument,       0, 'F'},
        {"num",        required_argument, 0, 'n'},
        {"delay",      required_argument, 0, 'd'},
        {"eolchar",    required_argument, 0, 'e'},
        {"timeout",    required_argument, 0, 't'},
        {"quiet",      no_argument,       0, 'q'},
        {NULL,         0,                 0, 0}
    };

    while(1) {
        opt = getopt_long (argc, argv, "hp:b:s:rSFn:d:qe:t:",
                           loptions, &option_index);
        if (opt==-1) break;
        switch (opt) {
        case '0': break;
        case 'q':
            quiet = 1;
            break;
        case 'e':
            eolchar = optarg[0];
            if(!quiet) printf("eolchar set to '%c'\n",eolchar);
            break;
        case 't':
            timeout = strtol(optarg,NULL,10);
            if( !quiet ) printf("timeout set to %d millisecs\n",timeout);
            break;
        case 'd':
            n = strtol(optarg,NULL,10);
            if( !quiet ) printf("sleep %d millisecs\n",n);
            usleep(n * 1000 ); // sleep milliseconds
            break;
        case 'h':
            usage();
            break;
        case 'b':
            baudrate = strtol(optarg,NULL,10);
            break;
        case 'p':
            if( fd!=-1 ) {
                serialport_close(fd);
                if(!quiet) printf("closed port %s\n",serialport);
            }
            strcpy(serialport,optarg);
            fd = serialport_init(optarg, baudrate);
            if( fd==-1 ) error("couldn't open port");
            if(!quiet) printf("opened port %s\n",serialport);
            serialport_flush(fd);
            break;
        case 'n':
            if( fd == -1 ) error("serial port not opened");
            n = strtol(optarg, NULL, 10); // convert string to number
            rc = serialport_writebyte(fd, (uint8_t)n);
            if(rc==-1) error("error writing");
            break;
        case 'S':
	     portno = 52002;//atoi(argv[2]);
             /* Create a socket point*/ 
             sockfd = socket(AF_INET, SOCK_STREAM, 0);
             if (sockfd < 0) 
             {
                perror("ERROR opening socket");
                exit(1);
             }
             server = gethostbyname("192.168.2.103");//gethostbyname(argv[1]);
             if (server == NULL) {
                fprintf(stderr,"ERROR, no such host\n");
                exit(0);
             }

             bzero((char *) &serv_addr, sizeof(serv_addr));
             serv_addr.sin_family = AF_INET;
             bcopy((char *)server->h_addr, 
                   (char *)&serv_addr.sin_addr.s_addr,
                         server->h_length);
             serv_addr.sin_port = htons(portno);

             /* Now connect to the server */
             if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0) 
             {
                  perror("ERROR connecting");
                  exit(1);
              }
              while(1){
              int r;
              int a1, a2, a3;
	      char a4[sizeof(float)*3+3];
              memset (buf, 0, 256);
              r = serialport_read_until(fd, buf);
              //fprintf (stderr, "VAL: %s -->", buf);
              if (r >= 0)
              {
               sscanf (buf, "A1:%d\tA2:%d\tA3:%d", &a1, &a2, &a3);
              // fprintf (stderr, "(%d)(%d)(%d)\n", a1, a2, a3);
               if(calibrate==0){
                  sumX= sumX + a1; sumY= sumY + a2; sumZ= sumZ + a3;
                  xDat[total]=a1;yDat[total]=a2;zDat[total]=a3;
                  total++;
              if (total==100){ 
		  calibrate=1;
                  avgX = sumX/(float)total; avgY = sumY/(float)total; avgZ = sumZ/(float)total;
                  for(p = 1; p<total;p++){
                  sum1 = sum1 + pow((xDat[p]-avgX),2); sum2 = sum2 + pow((yDat[p]-avgY),2); sum3 = sum3 + pow((zDat[p]-avgZ),2);
                  }
		   varX= sum1/(float)total; varY=sum2/(float)total; varZ=sum3/(float)total;
                   stdX=sqrt(varX); stdY=sqrt(varY); stdZ=sqrt(varZ);
               }
	       }
               if(calibrate==1){snprintf(a4, sizeof a4*7, "%f %f %f %f %f %f %f %f %f", (float)a1, (float)a2,(float)a3,avgX,avgY,avgZ,stdX,stdY,stdZ);}
               while(sendMessage==1&&calibrate==1){
                /* Send message to the server*/ 
                //printf("here");
		n2 = write(sockfd,a4,strlen(a4));
                if (n2 < 0) 
                {
                        perror("ERROR writing to socket");
                        exit(1);
                }
                /* Now read server response */
                bzero(buffer,256);
                n2 = read(sockfd,buffer,255);
                    if (n2 < 0) 
                {
                        perror("ERROR reading from socket");
                        exit(1);
                }
//                printf("Received message: %s\n",buffer);
                 sendMessage=0;
                }
             sendMessage=1; 
	     }
              sendMessage=1;
              fflush (0);
              //sleep (5);
           }    
           break;
        case 's':
            if( fd == -1 ) error("serial port not opened");

            sprintf(buf, (opt=='S' ? "%s\n" : "%s"), optarg);

            if( !quiet ) printf("send string:%s\n", buf);
            rc = serialport_write(fd, buf);
            if(rc==-1) error("error writing");
            break;
        case 'r':
	  while (1)
	    {
	      int r;
	      int a1, a2, a3;

	      memset (buf, 0, 256);
	      r = serialport_read_until(fd, buf);
              fprintf (stderr, "VAL: %s -->", buf);
//              printf("%d",r);
	      if (r >= 0)
		{
		 sscanf (buf, "A1:%d\tA2:%d\tA3:%d", &a1, &a2, &a3);
		 fprintf (stderr, "(%d)(%d)(%d)\n", a1, a2, a3);
                 //fgets(stdbuffer,10,stdin);
	         //if(strcmp(stdbuffer,"getData")==0){
		 // printf("%d",a1);
                 // printf("%d",a2);
                 // printf("%d",a3);}
                //}
        /*       while(sendMessage==1){
    		/* Send message to the server 
    		n2 = write(sockfd,"measure",strlen("measure"));
    		if (n2 < 0) 
    		{
         		perror("ERROR writing to socket");
         		exit(1);
    		}
    		/* Now read server response 
    		bzero(buffer,256);
    		n2 = read(sockfd,buffer,255);
        	    if (n2 < 0) 
    		{
         		perror("ERROR reading from socket");
         		exit(1);
    		}
    		printf("Received message: %s\n",buffer);
                sendMessage=0;
   		}*/
              }
	      fflush (0);
	      usleep (10000);
	    }
            break;
        case 'F':
            if( fd == -1 ) error("serial port not opened");
            if( !quiet ) printf("flushing receive buffer\n");
            serialport_flush(fd);
            break;

        }
    }

    exit(EXIT_SUCCESS);
} // end main
Пример #11
0
ModCom::ModCom(void) {
	assigned = 0;
	dd = "";
	char ttyport[33];
	char *serial_name;
	vector<string>::iterator redodev;

	// Search ttyUSB_'N' serial devices
	for(int n = 0; n < 10; n++){
		sprintf(ttyport, "/dev/ttyUSB%d", n);   
		serial_name = strdup(ttyport);
		fd = serialport_init(serial_name, 9600);
		if (fd != -1){
			redodev = find(devDescriptionList.begin(), devDescriptionList.end(), string(ttyport));
			if (redodev == devDescriptionList.end() || devDescriptionList.size() == 0) {
				if (this->checkdev()){
					dd = string(ttyport);
					devDescriptionList.push_back(string(ttyport));
					assigned = 1;
					return;
				}
			}
		}
		serialport_close(fd);
	}

	// Search ttyACM_'N' arduino serial devices
	for(int n = 0; n < 10; n++){
		sprintf(ttyport, "/dev/ttyACM%d", n);  
		serial_name = strdup(ttyport);
		fd = serialport_init(serial_name, 9600);
		if (fd != -1){
			redodev = find(devDescriptionList.begin(), devDescriptionList.end(), string(ttyport));
			if (redodev == devDescriptionList.end() || devDescriptionList.size() == 0) {
				if (this->checkdev()){
					dd = string(ttyport);
					devDescriptionList.push_back(string(ttyport));
					assigned = 1;
					return;
				}
			}
		}
		serialport_close(fd);
	}

	// Search rfcomm_'N' arduino bluetooth devices
	for(int n = 0; n < 10; n++){
		sprintf(ttyport, "/dev/rfcomm%d", n);  
		serial_name = strdup(ttyport);
		fd = serialport_init(serial_name, 9600);
		if (fd != -1){
			redodev = find(devDescriptionList.begin(), devDescriptionList.end(), string(ttyport));
			if (redodev == devDescriptionList.end() || devDescriptionList.size() == 0) {
				if (this->checkdev()){
					dd = string(ttyport);
					devDescriptionList.push_back(string(ttyport));
					assigned = 1;
					return;
				}
			}
		}
		serialport_close(fd);
	}
}
Пример #12
0
int main(int argc, char *argv[])
{
	int sd = -1;
	char *conf_file = NULL;
	struct mosquitto *mosq;
	struct module *md;
	struct device *dev;
	int rc;
	int i;
	
	gbuf[0] = 0;

	if (!quiet) printf("Version: %s\n", version);

    signal(SIGINT, handle_signal);
    signal(SIGTERM, handle_signal);
	signal(SIGUSR1, handle_signal);
	signal(SIGUSR2, handle_signal);
	signal(SIGALRM, each_sec);
	
	for (i=1; i<argc; i++) {
		if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--config")){
			if(i==argc-1){
                fprintf(stderr, "Error: -c argument given but no file specified.\n\n");
				print_usage(argv[0]);
                return 1;
            }else{
				conf_file = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "--quiet")){
				quiet = true;
		}else{
				fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]);
				print_usage(argv[0]);
				return 1;
		}
	}
	
	if (!conf_file) {
		fprintf(stderr, "Error: No config file given.\n");
		return 1;
	}

	memset(&config, 0, sizeof(struct bridge_config));
	if (config_parse(conf_file, &config)) return 1;
	
	if (quiet) config.debug = 0;
	if (config.debug != 0) printf("Debug: %d\n", config.debug);

	rc = bridge_init(&bridge, config.id, MODULES_BRIDGE_ID);
	if (rc) {
		if (config.debug) printf("Error: Failed to initialize bridge: %d\n", rc);
		return 1;
	}

	mosquitto_lib_init();
	mosq = mosquitto_new(config.id, true, NULL);
	if(!mosq){
		fprintf(stderr, "Error creating mqtt instance.\n");
		switch(errno){
			case ENOMEM:
				fprintf(stderr, " out of memory.\n");
				break;
			case EINVAL:
				fprintf(stderr, " invalid id.\n");
				break;
		}
		return 1;
	}
	snprintf(gbuf, GBUF_SIZE, "%d", PROTOCOL_TIMEOUT);
	mosquitto_will_set(mosq, bridge.bridge_dev->status_topic, strlen(gbuf), gbuf, config.mqtt_qos, MQTT_RETAIN);

	mosquitto_connect_callback_set(mosq, on_mqtt_connect);
	mosquitto_disconnect_callback_set(mosq, on_mqtt_disconnect);
	mosquitto_message_callback_set(mosq, on_mqtt_message);
	mosquitto_user_data_set(mosq, &sd);

	md = bridge_add_module(bridge.bridge_dev, MODULES_MQTT_ID, true);
	if (!md) {
		fprintf(stderr, "Failed to add MQTT module.\n");
		return 1;
	}

	if (config.scripts_folder) {
		if (access(config.scripts_folder, R_OK )) {
			fprintf(stderr, "Couldn't open scripts folder: %s\n", config.scripts_folder);
			return 1;
		}
		md = bridge_add_module(bridge.bridge_dev, MODULES_SCRIPT_ID, true);
		if (!md) {
			fprintf(stderr, "Failed to add script module.\n");
			return 1;
		}
	}

	if (config.interface) {
		//TODO: check if interface exists
		if (access("/proc/net/dev", R_OK )) {
			fprintf(stderr, "Couldn't open /proc/net/dev\n");
			return 1;
		}
		md = bridge_add_module(bridge.bridge_dev, MODULES_BANDWIDTH_ID, true);
		if (!md) {
			fprintf(stderr, "Failed to add bandwidth module.\n");
			return 1;
		}
		bandwidth = true;
	}

	if (config.serial.port) {
		sd = serialport_init(config.serial.port, config.serial.baudrate);
		if( sd == -1 ) {
			fprintf(stderr, "Couldn't open serial port.\n");
			return 1;
		} else {
			md = bridge_add_module(bridge.bridge_dev, MODULES_SERIAL_ID, true);
			if (!md) {
				fprintf(stderr, "Failed to add serial module.\n");
				return 1;
			}
			serialport_flush(sd);
			bridge.serial_ready = true;

			if (config.debug) printf("Serial ready.\n");
		}
	}

	if (config.debug > 2) bridge_print_modules(bridge.bridge_dev);

	rc = mosquitto_connect(mosq, config.mqtt_host, config.mqtt_port, 60);
	if (rc) {
		fprintf(stderr, "ERROR: %s\n", mosquitto_strerror(rc));
		return -1;
	}

	alarm(1);

	while (run) {
		if (bridge.serial_ready) {
			rc = serial_in(sd, mosq, MODULES_SERIAL_ID);
			if (rc == -1) {
				serial_hang(mosq);
			} else if (rc > 0) {
				bridge.serial_alive = DEVICE_ALIVE_MAX;
			}
		}

		if (user_signal) {
			if (config.debug > 2) printf("Signal - SIGUSR: %d\n", user_signal);
			signal_usr(sd, mosq);
		}

		rc = mosquitto_loop(mosq, 100, 1);
		if (run && rc) {
			if (config.debug > 2) printf("MQTT loop: %s\n", mosquitto_strerror(rc));
			usleep(100000);	// wait 100 msec
			mosquitto_reconnect(mosq);
		}
		usleep(20);

		if (every1s) {
			every1s = false;

			for (dev = bridge.dev_list; dev != NULL; dev = dev->next) {
				if (dev->alive) {
					dev->alive--;
					if (!dev->alive) {
						if (connected) {
							snprintf(gbuf, GBUF_SIZE, "%d", PROTOCOL_TIMEOUT);
							mqtt_publish(mosq, dev->status_topic, gbuf);
							rc = mosquitto_unsubscribe(mosq, NULL, dev->config_topic);
							if (rc)
								fprintf(stderr, "Error: MQTT unsubscribe returned: %s\n", mosquitto_strerror(rc));
						}
						if (config.debug) printf("Device: %s - Timeout.\n", dev->id);
						bridge_remove_device(&bridge, dev->id);
					}
				}
			}
		}

		if (every30s) {
			every30s = false;

			if (connected) {
				send_alive(mosq);

				if (bandwidth) {
					md = bridge_get_module(bridge.bridge_dev, MODULES_BANDWIDTH_ID);
					if (md) {
						snprintf(gbuf, GBUF_SIZE, "%.0f,%.0f", upspeed, downspeed);
						mqtt_publish(mosq, md->topic, gbuf);
						if (config.debug > 2) printf("down: %f - up: %f\n", downspeed, upspeed);
					}
				}
			} else {
				if (config.debug) printf("MQTT Offline.\n");
			}

			if (bridge.serial_alive) {
				bridge.serial_alive--;
				if (!bridge.serial_alive) {
					if (config.debug > 1) printf("Serial timeout.\n");
					serial_hang(mosq);
				}
			} else {
				if (config.serial.port && !bridge.serial_ready) {
					if (config.debug > 1) printf("Trying to reconnect serial port.\n");
					serialport_close(sd);
					sd = serialport_init(config.serial.port, config.serial.baudrate);
					if( sd == -1 ) {
						fprintf(stderr, "Couldn't open serial port.\n");
					} else {
						serialport_flush(sd);
						bridge.serial_ready = true;
						snprintf(gbuf, GBUF_SIZE, "%d", MODULES_SERIAL_OPEN);
						mqtt_publish(mosq, md->topic, gbuf);
						if (config.debug) printf("Serial reopened.\n");
					}
				}
			}
		}
	}

	if (bridge.serial_ready) {
		serialport_close(sd);
	}

	mosquitto_destroy(mosq);

	mosquitto_lib_cleanup();
	config_cleanup(&config);

	printf("Exiting..\n\n");

	return 0;
}
Пример #13
0
int main(int argc, char *argv[])
{
	int sd = -1;
	char *conf_file = NULL;
	struct mosquitto *mosq;
	struct module *md;
	struct device *dev;
	int rc;
	int i;
	
	if (!quiet) printf("Version: %s\n", version);

    signal(SIGINT, handle_signal);
    signal(SIGTERM, handle_signal);
	signal(SIGUSR1, handle_signal);
	signal(SIGUSR2, handle_signal);
	signal(SIGALRM, each_sec);
	
	for (i=1; i<argc; i++) {
		if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--config")){
			if(i==argc-1){
                fprintf(stderr, "Error: -c argument given but no file specified.\n\n");
				print_usage(argv[0]);
                return 1;
            }else{
				conf_file = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "--quiet")){
				quiet = true;
		}else{
				fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]);
				print_usage(argv[0]);
				return 1;
		}
	}
	
	if(!conf_file) {
		fprintf(stderr, "Error: No config file given.\n");
		return 1;
	}

	memset(&config, 0, sizeof(struct bridge_config));
	if(config_parse(conf_file, &config)) return 1;
	
	if (quiet) config.debug = 0;
	if (config.debug != 0) printf("Debug: %d\n", config.debug);

	if (!device_isValid_id(config.id)) {
		fprintf(stderr, "Invalid id.\n");
		return -1;
	}
	if (device_init(&bridge, config.id) == -1)
		return 1;

	mosquitto_lib_init();
	mosq = mosquitto_new(config.id, true, NULL);
	if(!mosq){
		fprintf(stderr, "Error creating mqtt instance.\n");
		switch(errno){
			case ENOMEM:
				fprintf(stderr, " out of memory.\n");
				break;
			case EINVAL:
				fprintf(stderr, " invalid id.\n");
				break;
		}
		return 1;
	}
	snprintf(gbuf, GBUF_SIZE, "%d", PROTO_ST_TIMEOUT);
	mosquitto_will_set(mosq, bridge.status_topic, strlen(gbuf), gbuf, config.mqtt_qos, MQTT_RETAIN);
	mosquitto_connect_callback_set(mosq, on_mqtt_connect);
	mosquitto_disconnect_callback_set(mosq, on_mqtt_disconnect);
	mosquitto_message_callback_set(mosq, on_mqtt_message);
	mosquitto_user_data_set(mosq, &sd);

	if (config.debug > 1) printf("Subscribe topic: %s\n", bridge.config_topic);

	rc = device_add_module(&bridge, MODULE_MQTT_ID, bridge.id);				//TODO: autogen id?
	if (rc) {
		fprintf(stderr, "Failed to add mqtt module.\n");
		return 1;
	}

	if (config.scripts_folder) {
		if (access(config.scripts_folder, R_OK )) {
			fprintf(stderr, "Couldn't open scripts folder: %s\n", config.scripts_folder);
			return 1;
		}
		rc = device_add_module(&bridge, MODULE_SCRIPT_ID, bridge.id);		//TODO: autogen id?
		if (rc) {
			fprintf(stderr, "Failed to add script module.\n");
			return 1;
		}
	}
	if (config.interface) {
		//TODO: check if interface exists
		if (access("/proc/net/dev", R_OK )) {
			fprintf(stderr, "Couldn't open /proc/net/dev\n");
			return 1;
		}
		rc = device_add_module(&bridge, MODULE_BANDWIDTH_ID, bridge.id);		//TODO: autogen id?
		if (rc) {
			fprintf(stderr, "Failed to add bandwidth module.\n");
			return 1;
		}
		bandwidth = true;
	}
	if (config.serial.port) {
		sd = serialport_init(config.serial.port, config.serial.baudrate);
		if( sd == -1 ) {
			fprintf(stderr, "Couldn't open serial port.\n");
			return 1;
		} else {
			rc = device_add_module(&bridge, MODULE_SERIAL_ID, bridge.id);		//TODO: autogen id?
			if (rc) {
				fprintf(stderr, "Failed to add serial module.\n");
				return 1;
			}
			serialport_flush(sd);
			bridge.serial_ready = true;

			if (config.debug) printf("Serial ready.\n");
		}
	}

	rc = device_add_module(&bridge, MODULE_SIGUSR1_ID, bridge.id);			//TODO: autogen id?
	if (rc) {
		fprintf(stderr, "Failed to add sigusr1 module.\n");
		return 1;
	}

	rc = device_add_module(&bridge, MODULE_SIGUSR2_ID, bridge.id);			//TODO: autogen id?
	if (rc) {
		fprintf(stderr, "Failed to add sigusr2 module.\n");
		return 1;
	}

	device_print_modules(&bridge);

	rc = mosquitto_connect(mosq, config.mqtt_host, config.mqtt_port, 60);
	if (rc) {
		fprintf(stderr, "Wrong MQTT parameters. Check your config.\n");
		return -1;
	}

	alarm(1);

	while (run) {
		if (bridge.serial_ready) {
			rc = serial_in(sd, mosq, MODULE_SERIAL_ID);
			if (rc == -1) {
				serial_hang(mosq);
			} else if (rc > 0) {
				bridge.serial_alive = ALIVE_CNT;
			}
		}

		if (user_signal) {
			if (config.debug > 1) printf("Signal - SIGUSR: %d\n", user_signal);
			signal_usr(sd, mosq);
		}

		rc = mosquitto_loop(mosq, -1, 1);
		if (run && rc) {
			if (config.debug > 2) printf("MQTT loop: %s\n", mosquitto_strerror(rc));
			usleep(100000);	// wait 100 msec
			mosquitto_reconnect(mosq);
		}

		if (every30s) {
			every30s = false;

			bridge.controller = false;
			for (i = 0; i < bridge.devices_len; i++) {
				dev = &bridge.devices[i];
				if (dev->alive) {
					dev->alive--;
					if (!dev->alive) {
						snprintf(gbuf, GBUF_SIZE, "%d,%s", PROTO_ST_TIMEOUT, dev->id);
						mqtt_publish(mosq, bridge.status_topic, gbuf);

						if (dev->md_deps->type == MODULE_MQTT && dev->type == DEVICE_TYPE_NODE) {
							snprintf(gbuf, GBUF_SIZE, "status/%s", dev->id);
							rc = mosquitto_unsubscribe(mosq, NULL, gbuf);
							if (rc)
								fprintf(stderr, "Error: MQTT unsubscribe returned: %s\n", mosquitto_strerror(rc));
						}

						if (config.debug) printf("Device timeout - id: %s\n", dev->id);
					} else {
						if (dev->type == DEVICE_TYPE_CONTROLLER)
							bridge.controller = true;
					}
				}
			}

			if (!bridge.controller)
				bridge.modules_update = false;

			if (connected) {
				snprintf(gbuf, GBUF_SIZE, "%d,%d", PROTO_ST_ALIVE, bridge.modules_len);
				mqtt_publish(mosq, bridge.status_topic, gbuf);

				if (bridge.modules_update) {
					snprintf(gbuf, GBUF_SIZE, "%d", PROTO_ST_MODULES_UP);
					if (mqtt_publish(mosq, bridge.status_topic, gbuf))
						bridge.modules_update = false;
				}

				if (bandwidth) {
					md = device_get_module(&bridge, MODULE_BANDWIDTH_ID);
					if (md) {
						if (mqtt_publish_bandwidth(mosq, md->topic) == -1)
							break;
					}
				}
			} else {
				if (config.debug != 0) printf("MQTT Offline.\n");
			}

			if (bridge.serial_alive) {
				bridge.serial_alive--;
				if (!bridge.serial_alive) {
					if (config.debug > 1) printf("Serial timeout.\n");
					serial_hang(mosq);
				}
			} else {
				if (config.serial.port && !bridge.serial_ready) {
					if (config.debug > 1) printf("Trying to reconnect serial port.\n");
					serialport_close(sd);
					sd = serialport_init(config.serial.port, config.serial.baudrate);
					if( sd == -1 )
						fprintf(stderr, "Couldn't open serial port.\n");
					else {
						serialport_flush(sd);
						bridge.serial_ready = true;
						if (config.debug) printf("Serial reopened.\n");
					}
				}
			}
		}
		usleep(20);
	}

	if (bridge.serial_ready) {
		serialport_close(sd);
	}

	mosquitto_destroy(mosq);

	mosquitto_lib_cleanup();
	config_cleanup(&config);

	printf("Exiting..\n\n");

	return 0;
}