The final version, in case someone was interested.
main.c
int local_socket;
int serial_fd;
int max_fd;
fd_set input;
fd_set tmp_input;
char *serial_output_buffer;
serial_output_buffer=malloc(11 * sizeof(char));
serial_fd=open_port();
local_socket=open_local_socket();
FD_ZERO(&input);
FD_SET(serial_fd, &input);
FD_SET(local_socket, &input);
max_fd = (local_socket > serial_fd ? local_socket : serial_fd) + 1;
si_processed=0;
serial_output_buffer[10]='\0';
while(TRUE) {
tmp_input=input;
n = select(max_fd,&tmp_input,NULL,NULL,NULL);
/* See if there was an error */
if (n<0)
perror("select failed");
else {
/* We have input */
if (FD_ISSET(serial_fd, &input)) {
if(process_serial(serial_fd,serial_output_buffer)) {
printf("read:%s\n",serial_output_buffer);
fflush(stdout);
}
}
if (FD_ISSET(local_socket, &input))
process_socket(local_socket);
}
usleep(20000);
}
return 0;
serial_port.h
#ifndef SERIAL_PORT
#define SERIAL_PORT
int open_port();
int process_serial(int serial_fd,char *output);
int si_processed;
#endif
serial_port.c
char serial_buffer[256];
int process_serial(int serial_fd,char *output) {
int bytes;
int n,i;
char tmp_buffer[256];
ioctl(serial_fd, FIONREAD, &bytes);
if(!bytes && si_processed<INPUT_BYTES_NUM) //proceed if data still in buffer
return 0;
n=read(serial_fd, tmp_buffer, sizeof(tmp_buffer));
for(i=0;i<n;i++) {
serial_buffer[si_processed+i]=tmp_buffer[i];
}
si_processed+=n;
if(si_processed>=INPUT_BYTES_NUM) {
for (i = 0; i < si_processed; ++i)
if (serial_buffer[i] == '1') // found start of packet
break;
if (i > 0) {
// start of packet is not start of buffer
// so discard bad bytes at the start of the buffer
memmove(serial_buffer, serial_buffer+i, si_processed - i);
si_processed -= i;
}
if(si_processed>=INPUT_BYTES_NUM) {
memmove(output, serial_buffer, 10);
//move what left to the beginning
memmove(serial_buffer,serial_buffer+10,si_processed-10);
si_processed -= 10;
return 1;
}
}
return 0;
}
int open_port(void) {
int fd; /* File descriptor for the port */
struct termios options;
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
/*
* Could not open the port.
*/
error_exit("open_port: Unable to open /dev/ttyS0");
}
else
fcntl(fd, F_SETFL, 0);
/*
* Get the current options for the port...
*/
tcgetattr(fd, &options);
/*
* Set the baud rates to 19200...
*/
cfsetispeed(&options, B38400);
cfsetospeed(&options, B38400);
/*
* Enable the receiver and set local mode...
*/
options.c_cflag |= (CLOCAL | CREAD);
//set 8N1
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
/*
* Set the new options for the port...
*/
tcsetattr(fd, TCSANOW, &options);
return (fd);
}