Advertisement
synthnassizer

readCmd

Jul 5th, 2013
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.79 KB | None | 0 0
  1. int read_com_buffer(const int toReadBytes, char *serInBuf, const int stream_status){
  2.  
  3.     unsigned int idx=0; //index of the serInBuf
  4.     char b1,b2; //receive 2 bytes in one swipe of this procedure
  5.     fd_set rfds;    // File pointer set for select
  6.     struct timeval serInWait;   // Time to wait for serial input
  7.     int stream=stream_status; //receiving 1st (START_STREAM), or following bytes (CONT_STREAM)
  8.     int selRetVal;  // Return value of select
  9.    
  10.     //inits
  11.     serInWait.tv_sec = SERIAL_TIMEOUT_SEC;
  12.     serInWait.tv_usec = SERIAL_TIMEOUT_USEC;
  13.     FD_ZERO(&rfds);
  14.     FD_SET(fd, &rfds);
  15.     DEBUG_SERIAL(printf("SERIAL: will read bytes %d\n",toReadBytes));
  16.  
  17.     //main fn
  18.     for(idx=0;idx<toReadBytes;idx++) {  
  19.         if (stream==CONT_STREAM){//add (or not) a timeout on the select()
  20.             selRetVal = select(fd+1, &rfds, NULL, NULL, &serInWait);
  21.         } else if (stream==START_STREAM) { //waiting for 1st byte
  22.             selRetVal = select(fd+1, &rfds, NULL, NULL, NULL);
  23.             pthread_mutex_lock(&serial_lock_mutex);
  24.             stream=CONT_STREAM;
  25.         }
  26.        
  27.         if (selRetVal==0){
  28.             return SERIAL_TIMEOUT;
  29.         } else if (selRetVal>0){
  30.             read(fd,&b1,1);
  31.             if((b1 == '#') || (b1 == '\n')) { // Skip comment lines
  32.                 while( b1 != '\n')
  33.                     read(fd,&b1,1);
  34.             } else if (b1==' '){    //Skip spaces
  35.             } else if (b1 == EOF) {
  36.                 return ERROR;   // Nothing else to read
  37.             } else { //go on to read 2nd byte
  38.                 selRetVal = select(fd+1, &rfds, NULL, NULL, &serInWait);
  39.        
  40.                 if (selRetVal==0){
  41.                     return SERIAL_TIMEOUT;
  42.                 } else if (selRetVal>0){
  43.                     read(fd,&b2,1);
  44.  
  45.                     //convert asciiHex to Hex
  46.                     if (asciiToHex(&b1)==ERROR) return ERROR;
  47.                     if (asciiToHex(&b2)==ERROR) return ERROR;
  48.                    
  49.                     //merge bytes b1 & b2
  50.                     b1 = b1 << 4;
  51.                     b1 = b1 | b2;
  52.  
  53.                     serInBuf[idx] = b1;
  54.                 }
  55.             }
  56.         }
  57.     }//end for [idx] loop
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement