Example #1
0
int serial_set_rate(int fd, int baudrate, int hwflow)
{
	struct termios term;
	int ret;

	ret = tcgetattr(fd, &term);
	if (ret < 0)
		goto err;

	cfmakeraw(&term);
	cfsetspeed(&term, get_rate_const(baudrate));

	if (hwflow)
		term.c_cflag |= CRTSCTS;
	else
		term.c_cflag &= ~CRTSCTS;

	ret = tcsetattr(fd, TCSAFLUSH, &term);
	if (ret < 0)
		goto err;

	return 0;
 err:
	perror("unable to configure serial port");
	return ret;
}
Example #2
0
File: serial.hpp Project: ARM9/bass
  bool open(const string& portname, unsigned rate, bool flowcontrol) {
    close();

    port = ::open(portname, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
    if(port == -1) return false;

    if(ioctl(port, TIOCEXCL) == -1) { close(); return false; }
    if(fcntl(port, F_SETFL, 0) == -1) { close(); return false; }
    if(tcgetattr(port, &original_attr) == -1) { close(); return false; }

    termios attr = original_attr;
    cfmakeraw(&attr);
    cfsetspeed(&attr, rate);

    attr.c_lflag &=~ (ECHO | ECHONL | ISIG | ICANON | IEXTEN);
    attr.c_iflag &=~ (BRKINT | PARMRK | INPCK | ISTRIP | INLCR | IGNCR | ICRNL | IXON | IXOFF | IXANY);
    attr.c_iflag |=  (IGNBRK | IGNPAR);
    attr.c_oflag &=~ (OPOST);
    attr.c_cflag &=~ (CSIZE | CSTOPB | PARENB | CLOCAL);
    attr.c_cflag |=  (CS8 | CREAD);
    if(flowcontrol == false) {
      attr.c_cflag &= ~CRTSCTS;
    } else {
      attr.c_cflag |=  CRTSCTS;
    }
    attr.c_cc[VTIME] = attr.c_cc[VMIN] = 0;

    if(tcsetattr(port, TCSANOW, &attr) == -1) { close(); return false; }
    return port_open = true;
  }
Example #3
0
int
sbus_init(const char *device, bool singlewire)
{
	int sbus_fd = open(device, O_RDWR | O_NONBLOCK);

	if (sbus_fd >= 0) {
		struct termios t;

		/* 100000bps, even parity, two stop bits */
		tcgetattr(sbus_fd, &t);
		cfsetspeed(&t, 100000);
		t.c_cflag |= (CSTOPB | PARENB);
		tcsetattr(sbus_fd, TCSANOW, &t);

		if (singlewire) {
			/* only defined in configs capable of IOCTL */
#ifdef SBUS_SERIAL_PORT
			//ioctl(uart, TIOCSSINGLEWIRE, SER_SINGLEWIRE_ENABLED);
#endif
		}

		/* initialise the decoder */
		partial_frame_count = 0;
		last_rx_time = hrt_absolute_time();
		last_frame_time = last_rx_time;
		sbus_frame_drops = 0;
	}

	return sbus_fd;
}
Example #4
0
int
sbus_init(const char *device)
{
	if (sbus_fd < 0) {
		sbus_fd = open(device, O_RDWR | O_NONBLOCK);
	}

	if (sbus_fd >= 0) {
		struct termios t;

		/* 100000bps, even parity, two stop bits */
		tcgetattr(sbus_fd, &t);
		cfsetspeed(&t, 100000);
		t.c_cflag |= (CSTOPB | PARENB);
		tcsetattr(sbus_fd, TCSANOW, &t);

		/* initialise the decoder */
		partial_frame_count = 0;
		last_rx_time = hrt_absolute_time();

		debug("S.Bus: ready");

	} else {
		debug("S.Bus: open failed");
	}

	return sbus_fd;
}
static int port_open(const char *device)
{
	int handle;
	struct termios options;

	/* open serial port */
	if((handle = open( device, O_RDONLY | O_NOCTTY | O_NDELAY)) == -1)
	{
		fprintf(stderr, "error: failed to open serial port (%s)\n", device);
		exit(10);
	}

	/* apply serial port settings */
	tcgetattr(handle, &options);
	cfmakeraw(&options);
	cfsetspeed(&options, TAG_UART_BAUD_RATE);

	if(tcsetattr(handle, TCSANOW, &options))
	{
		fprintf(stderr, "error: failed to set baud %i rate for '%s'\n", TAG_UART_BAUD_RATE, device);
		exit(11);		
	}

	tcflush(handle, TCIFLUSH);

	return handle;
}
Example #6
0
int Dude() {

  int fd = open("/dev/ttyAMA0", O_RDWR);
  
  if (fd == -1) {
    perror("/dev/ttyAMA0");
    return 1;
  }
  
  struct termios tios;
  tcgetattr(fd, &tios);
  // disable flow control and all that, and ignore break and parity errors
  tios.c_iflag = IGNBRK | IGNPAR;
  tios.c_oflag = 0;
  tios.c_lflag = 0;
  cfsetspeed(&tios, B9600);
  tcsetattr(fd, TCSAFLUSH, &tios);
  
  // the serial port has a brief glitch once we turn it on which generates a
  // start bit; sleep for 1ms to let it settle
  usleep(1000);    
  
  // output to serial port
  char msg[] = "hi there";
  write(fd, msg, strlen(msg));
  return 0;
}
Example #7
0
void SerialThrustMasterBase::open() {
    SerialDevice::open();

    struct termios settings;
    if (tcgetattr(handle, &settings) == -1) {
        throw IOException(name + " failed to get termios attributes: " + std::strerror(errno));
    }

    if (cfsetspeed(&settings, B9600) == -1) {
        throw IOException(name + " failed to set baud speed: " + std::strerror(errno));
    }

    // set the terminal to "raw" mode, see TERMIOS(3)
    settings.c_iflag &= ~(IGNBRK | BRKINT | IGNPAR | PARMRK | INPCK | ISTRIP | INLCR | IGNCR | ICRNL | IXON | IXOFF);
    settings.c_oflag &= ~OPOST;
    settings.c_cflag &= ~(CSIZE | PARENB | CSTOPB | HUPCL);
    settings.c_cflag |= CS8 | CLOCAL | CREAD;
    settings.c_lflag &= ~(ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHONL | IEXTEN);
    settings.c_cc[VTIME] = 0;
    settings.c_cc[VMIN] = 0;

    if (tcsetattr(handle, TCSANOW, &settings) == -1) {
        throw IOException(name + " failed to set termios attributes: " + std::strerror(errno));
    }

    // start getting data
    requestData();
}
Example #8
0
static int set_baudrate(int fd, int baudrate, int hwflow)
{
	int i;
	u_int32_t bd = 0;
	struct termios ti;

	for (i = 0; i < ARRAY_SIZE(bdrts); i++) {
		if (bdrts[i].bps == baudrate)
			bd = bdrts[i].b;
	}
	if (bd == 0)
		return -EINVAL;

	i = tcgetattr(fd, &ti);
	if (i < 0)
		return -errno;

	tcflush(fd, TCIOFLUSH);
	cfmakeraw(&ti);

	i = cfsetspeed (&ti, bd);
	if (i < 0)
		return -errno;

	if (hwflow)
		ti.c_cflag |= CRTSCTS;
	else
		ti.c_cflag &= ~CRTSCTS;

	return tcsetattr(fd, TCSANOW, &ti) ? -errno : 0;
}
Example #9
0
int openSerialDevice(const char * name, int baud, int parity, int databits, int stopbits) {
	/* open serial device; return file descriptor or -1 for error (see errno) */
	int fd, res;
	struct termios newSettings;
	
	if (strchr(name, ':')) 
		return openSerialSocket(name);
	
	if ((fd = open(name, O_RDWR | O_NOCTTY)) < 0) return fd;        // an error code
	
	bzero(&newSettings, sizeof(newSettings));
	// Control Modes
	newSettings.c_cflag = databits | CLOCAL | CREAD; // CRTSCTS stops it working on TS-SER1 & TS-SER4
	if (stopbits == 2)
		newSettings.c_cflag |= CSTOPB;
	// input modes
	cfsetspeed(&newSettings, baud);
	newSettings.c_iflag = IGNPAR;   //input modes
	newSettings.c_oflag = 0;                // output modes
	newSettings.c_lflag = 0;                // local flag
	newSettings.c_cc[VTIME] = 0; // intercharacter timer */
    newSettings.c_cc[VMIN] = 0;     // non-blocking read */
	tcflush(fd, TCIFLUSH);          // discard pending data
	//      cfsetospeed(&newSettings, baud);
	if((res = tcsetattr(fd, TCSANOW, &newSettings)) < 0) {
		close(fd);      // if there's an error setting values, return the error code
		return res;
	}
	return fd;
}
Example #10
0
int serial_handler::set_baud(const char *baud_name)
{
	struct termios port_setting;
	tcflag_t baud;
	int r;

	if (port_fd < 0) return -1;
	baud = baud_name_to_flags(baud_name);
	if (baud == B0) return -2;
	r = tcgetattr(port_fd, &port_setting);
	if (r != 0) return -3;
#ifdef __APPLE__
	cfsetspeed(&port_setting,baud);
	port_setting.c_iflag = IGNBRK | IGNPAR;
	port_setting.c_cflag =  CS8 | CREAD | HUPCL | CLOCAL;
#else
	port_setting.c_iflag = IGNBRK | IGNPAR;
	port_setting.c_cflag = baud | CS8 | CREAD | HUPCL | CLOCAL;
#endif

	port_setting.c_oflag = 0;
	port_setting.c_lflag = 0;
	r = tcsetattr(port_fd, TCSAFLUSH, &port_setting);
	if (r != 0) return -4;
	return 0;
}
Example #11
0
int rpi_comport_open(char *devpathname)
{
    struct termios newtio;
    
    /* If already opened, just return the fd */
    if (fd_comport > 0)
	return fd_comport;
    /* open the device to be non-blocking (read will return immediately) */
    fd_comport = open(devpathname, O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (fd_comport < 0) {
	perror(devpathname);
	return -1;
    }
    /* save current port settings */
    tcgetattr(fd_comport, &oldtio);
    /* set new port settings for raw & non-canonical input processing */
    cfmakeraw(&newtio);
    cfsetspeed(&newtio, B9600);
    /* minimum one character, or 1 character timeout */
    newtio.c_cc[VMIN] = 0;
    newtio.c_cc[VTIME] = 0;
    tcflush(fd_comport, TCIOFLUSH);
    tcsetattr(fd_comport, TCSANOW, &newtio);
    return 0;
}
Example #12
0
static int lua_stty_speed(lua_State *L) {
  int fd = lua_tofd(L, 1);
  int speed = luaL_checkint(L,2);

#ifdef __APPLE__
  if (ioctl(fd, IOSSIOSPEED, &speed) == -1)
    return luaL_error(L, "Could not set speed.");
#else
  // Default termios interface
  struct termios tio;
  if (tcgetattr(fd, &tio) != 0) {
    return luaL_error(L, "Could not get termios");
  }
  if (cfsetspeed(&tio, speed) != 0) {
    return luaL_error(L, "Could not set speed");
  }
  if (tcsetattr(fd, TCSANOW, &tio) != 0) {
    return luaL_error(L, "Could not set termios");
  }

  // For linux:
  struct serial_struct serinfo;
  if (ioctl(fd, TIOCGSERIAL, &serinfo) < 0)
    return luaL_error(L, "Could not get serial info.");
  serinfo.flags &= ~ASYNC_SPD_MASK;
  serinfo.flags |= ASYNC_SPD_CUST;
  serinfo.custom_divisor = serinfo.baud_base/((float)speed);
  if (ioctl(fd, TIOCSSERIAL, &serinfo) < 0)
    return luaL_error(L, "Could not set serial info.");

#endif

  return 0;
}
// Paramétrage du port série
int config_port_serie()
{
    int handle;

    char uart[20]= {"/dev/ttyUSB0"};

    //Ouverture du port série
    handle=open ( uart, O_RDWR | O_NOCTTY | O_NDELAY );

    if ( handle<0 )
    {
        perror ( "serial port fail to open\n" );
        exit(0);
    }
    else
    {
        if(fcntl ( handle, F_SETFL, FNDELAY)<0)
            perror("fcntl");
    }


    //settings for the uart
    tcgetattr ( handle, &option );
    cfmakeraw ( &option );
    cfsetspeed ( &option, B9600 );
    option.c_cflag |= ( CLOCAL | CREAD | CS8 );
    option.c_cflag &= ( ~PARENB & ~CSTOPB & ~CRTSCTS & ~CSIZE);

    tcsetattr ( handle, TCSANOW, &option );

    return handle;
}
Example #14
0
/*----------------------------------------------------------
 RS485Port.nativeSetRS485PortParams

   accept:     speed, data bits, stop bits, parity
   perform:    set the RS485 port parameters
   return:     void
   exceptions: UnsupportedCommOperationException
----------------------------------------------------------*/ 
JNIEXPORT void JNICALL Java_gnu_io_RS485Port_nativeSetRS485PortParams(
	JNIEnv *env, jobject jobj, jint speed, jint dataBits, jint stopBits,
	jint parity )
{
	struct termios ttyset;
	int fd = get_java_var( env, jobj,"fd","I" );
	int cspeed = translate_speed( env, speed );
	if( !cspeed ) return;
	if( tcgetattr( fd, &ttyset ) < 0 ) goto fail;
	if( !translate_data_bits( env, (int *)&(ttyset.c_cflag), dataBits ) ) return; /* dima c_cflag in darwin is unsigned long */
	if( !translate_stop_bits( env, (int *)&(ttyset.c_cflag), stopBits ) ) return; /* dima c_cflag in darwin is unsigned long */
	if( !translate_parity( env, (int *)&(ttyset.c_cflag), parity ) ) return;/* dima c_cflag in darwin is unsigned long */
#ifdef __FreeBSD__
	if( cfsetspeed( &ttyset, cspeed ) < 0 ) goto fail;
#else
	if( cfsetispeed( &ttyset, cspeed ) < 0 ) goto fail;
	if( cfsetospeed( &ttyset, cspeed ) < 0 ) goto fail;
#endif
	if( tcsetattr( fd, TCSANOW, &ttyset ) < 0 ) goto fail;
	/* dump_termios("set",*ttyset); */
	return;

fail:
	throw_java_exception( env, UNSUPPORTED_COMM_OPERATION,
		"nativeSetRS485PortParams", strerror( errno ) );
}
Example #15
0
int serial_port_set_baudrate(struct serial_port_t* _ctx,
                             unsigned int _baudrate) {
    if(_ctx) {
        struct termios tt;
        int r;
        speed_t speed;

        if((r = tcgetattr(_ctx->fd, &tt)))
            return r;

        speed = posix_serial_port_get_speedt_by_baudrate(_baudrate);

        if((r = cfsetspeed(&tt, speed)))
           return r;

        //cfsetispeed(&tt, speed);
        //cfsetospeed(&tt, speed);

        if((r = tcsetattr(_ctx->fd, TCSANOW, &tt)))
           return r;

        return 0;
    }
    else
        return -EINVAL;
}
Example #16
0
int main(int argc,char *argv[]) {
  int i,fd,slen;
  char *s;
  unsigned char c;
  struct iovec iov[5];
  speed_t br=DEFAULT_BAUDRATE;
  struct termios tios;

  if(argc<3) {
    printf("syntax: %s tty [baudrate (default=%d)] text\n", *argv, br2i(br));
    return 1;
  }

  if(-1==(fd=open(argv[1],O_RDWR))) {
    perror("open");
    return 1;
  }

  if(argc>3)
    br=str2br(argv[2]);

  if(-1==tcgetattr(fd,&tios)) {
    perror("tcgetattr");
    return 1;
  }
  cfmakeraw(&tios);
  printf("setting baudrate %d\n",br2i(br));
  if(-1==cfsetspeed(&tios,br)) {
    perror("cfsetspeed");
    return 1;
  }
  if(-1==tcsetattr(fd,TCSANOW,&tios)) {
    perror("tcgetattr");
    return 1;
  }

  i=0;
  iov_set(iov,i++,"\xff",1);
  iov_set(iov,i++,"\x06\xa2",2);

  s=argv[argc>3?3:2];
  slen=strlen(s);
  iov_set(iov,i++,s,slen);

  c=cksum(6+162,s,slen);
  iov_set(iov,i++,&c,1);

  iov_set(iov,i++,"\xff",1);

  printf("writing %d bytes\n",5+slen);
  xxdv(iov,i);
  if(-1==(i=writev(fd,iov,i)))
    perror("writev");
  else
    printf("%d bytes written\n",i);

  close(fd);
  return i!=5+slen;
}
Example #17
0
int main(int argc, const char *argv[])
{
	int serialFD;
	int x;
	int y;
	unsigned short color;
	struct termios serialopts;
	FILE *imageFile;
	
	imageFile = fopen(argv[1], "rb");
	if (imageFile == NULL)
	{
		perror("couldn't open file");
		return 1;
	}
	
	serialFD = open("/dev/cu.usbserial", O_RDWR | O_NOCTTY);
	if (serialFD < 0)
	{
		perror("couldn't open serial port");
		return 1;
	}
	
	if (tcgetattr(serialFD, &serialopts) != 0)
	{
		perror("Unable to get serial port options");
		return 1;
	}
	
	serialopts.c_cflag = CS8 | CLOCAL | CREAD;
	cfmakeraw(&serialopts);
	cfsetspeed(&serialopts, B115200);

	if (tcsetattr(serialFD, TCSANOW, &serialopts) != 0)
	{
		perror("Unable to initialize serial port");
		return 1;
	}
	
	for (x = 0; x < 640 * 480; x++)
	{
		unsigned char triple[4];
		if (fread(triple, 3, 1, imageFile) <= 0)
		{
			perror("error reading file");
			break;
		}

		triple[3] = 0xFF;
		if (write(serialFD, triple, 4) != 4)
		{
			perror("write");
			break;
		}
	}	
	
	close(serialFD);
	return 0;
}
Example #18
0
/*
 * Change the speed of the serial device.
 * RETURNS: Success
 */
gn_error serial_changespeed(int fd, int speed, struct gn_statemachine *state)
{
	gn_error retcode = GN_ERR_NONE;
#ifndef SGTTY
	struct termios t;
#else
	struct sgttyb t;
#endif
	int new_speed = B9600;

	switch (speed) {
	case 0:
		dprintf("Not setting port speed\n");
		return GN_ERR_NOTSUPPORTED;
	case 2400:
		new_speed = B2400;
		break;
	case 4600:
		new_speed = B4800;
		break;
	case 9600:
		new_speed = B9600;
		break;
	case 19200:
		new_speed = B19200;
		break;
	case 38400:
		new_speed = B38400;
		break;
	case 57600:
		new_speed = B57600;
		break;
	case 115200:
		new_speed = B115200;
		break;
	default:
		fprintf(stderr, _("Serial port speed %d not supported!\n"), speed);
		return GN_ERR_NOTSUPPORTED;
	}

#ifndef SGTTY
	if (tcgetattr(fd, &t)) retcode = GN_ERR_INTERNALERROR;

	if (cfsetspeed(&t, new_speed) == -1) {
		dprintf("Serial port speed setting failed\n");
		retcode = GN_ERR_INTERNALERROR;
	}

	tcsetattr(fd, TCSADRAIN, &t);
#else
	if (ioctl(fd, TIOCGETP, &t)) retcode = GN_ERR_INTERNALERROR;

	t.sg_ispeed = new_speed;
	t.sg_ospeed = new_speed;

	if (ioctl(fd, TIOCSETN, &t)) retcode = GN_ERR_INTERNALERROR;
#endif
	return retcode;
}
Example #19
0
void UARTDevice::set_speed(uint32_t baudrate)
{
    struct termios t;
    memset(&t, 0, sizeof(t));

    tcgetattr(_fd, &t);
    cfsetspeed(&t, baudrate);
    tcsetattr(_fd, TCSANOW, &t);
}
Example #20
0
int serial_open(int port, int initial_baud, int final_baud){
	int port_id;
	struct termios t_port;
    #ifdef USB
		char COM_PORT[16]="/dev/ttyUSB0";
    #else
	   char COM_PORT[16]="/dev/ttyS0";
    #endif
	int baud_rate[] = {B4800,B9600,B19200,B38400,B57600,B115200};

    #ifdef USB
	   printf("USB case");
	   COM_PORT[11] = COM_PORT[11] + port;
    #else
	   printf("Serial case");
	   COM_PORT[9] = COM_PORT[9] + port;
    #endif
	printf("Initializing communications port %s...", COM_PORT);

	/* open the device */
	if ((port_id = open(COM_PORT, O_RDWR)) == -1){
		printf("can not open device %s", COM_PORT);
		exit(1); }

	if (tcgetattr(port_id, &t_port) < 0){
		printf("error initiallizing %s", COM_PORT);
		exit(1); }

	t_port.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); // input mode
		/* no SIGINT on BREAK, CRNL off, parity off,8th bit strip off, output flow ctrl off */
	t_port.c_oflag &= ~(OPOST); // output mode
		/* output processing off */
	t_port.c_cflag &= ~(CSIZE | PARENB); // control mode
		/* clear size bits, parity off */
	t_port.c_cflag |=  baud_rate[final_baud] | CS8 | CREAD | CLOCAL ;
	t_port.c_cflag &= ~(CRTSCTS | CSTOPB);
		// 4800 9600 19200 38400 57600 115200
		/* 8 bits/char, enable receiver, close modem when exit */
	t_port.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
		/* echo off, canonical mode off,extended input processing off, signal chars off */

	t_port.c_cc[VMIN] = 0;//MIN_MSG_SIZE;		// wait for the amount of VMIN byte
	t_port.c_cc[VTIME] = 10;    /* waits 1/10ths of sec for reply */

	if (cfsetspeed(&t_port, baud_rate[final_baud]) < 0) {
		printf("error initiallizing %s", COM_PORT);
		exit(1); }
	if (tcsetattr(port_id, TCSANOW, &t_port) < 0){
		printf("error initiallizing %s", COM_PORT);
		exit(1); }
    //sleep(2);
	if (tcgetattr(port_id, &t_port) < 0){
		printf("error initiallizing %s", COM_PORT);
		exit(1); }

	return port_id; }
Example #21
0
int my_app_main(int argc, char *argv[])
{
	//uint8_t buf[100];
	//parameter receiver_arg;
	PX4_INFO("In my_test_app");
	int uart1 = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NONBLOCK);
	if (uart1 < 0) {
		printf("ERROR opening UART1, aborting..\n");
		return uart1;
	}
	struct termios uart1_config;
	int set = fcntl(uart1, F_SETFL, 0);
/*
	receiver_arg.fd = uart1;
	receiver_arg.buf = buf;
	receiver_arg.bytes_num = 1;
*/	

	//struct termios uart1_config_original;

	int termios_state = 0;

	int ret;

	if ((termios_state = tcgetattr(uart1, &uart1_config)) < 0) {
		printf("ERROR getting termios config for UART1: %d\n", termios_state);
		ret = termios_state;
		close(uart1);
		return ret;
	}

	if (cfsetspeed(&uart1_config, B115200) < 0) {
		printf("ERROR setting termios config for UART1: %d\n", termios_state);
		ret = ERROR;
		close(uart1);
		return ret;
	}

	if ((termios_state = tcsetattr(uart1, TCSANOW, &uart1_config)) < 0) {
		printf("ERROR setting termios config for UART1\n");
		ret = termios_state;
		close(uart1);
		return ret;
	}

	printf("c_iflag: %x, c_oflag: %x, c_cflag: %x, c_lflag: %x, speed: %d\n", uart1_config.c_iflag, uart1_config.c_oflag, uart1_config.c_cflag, uart1_config.c_lflag, uart1_config.c_speed);

	int r=0;

	wifi_init(uart1);
	//iniRD();
	r++;
	set++;
	close(uart1);
	return 0;
}
int set_interface_attribs (int fd, int speed, int parity)
{
        struct termios tty;
        
	memset (&tty, 0, sizeof(tty));

        if (tcgetattr (fd, &tty) != 0)
        {
                printf("error %d from tcgetattr", errno);
                return -1;
        }

	switch (speed)
	{
        case 1:
		cfsetospeed (&tty, B9600);
		cfsetispeed (&tty, B9600);
		break;
	case 2:
		cfsetospeed (&tty, B115200);
		cfsetispeed (&tty, B115200);
		break;
      	case 3:
		cfsetspeed(&tty, B230400);
		break;
    	}

        tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;     // 8-bit chars
        // disable IGNBRK for mismatched speed tests; otherwise receive break
        // as \000 chars
        tty.c_iflag &= ~IGNBRK;         // ignore break signal
        tty.c_lflag = 0;                // no signaling chars, no echo,
                                        // no canonical processing
  	tty.c_oflag = 0;                // no remapping, no delays
  
 	// kks :  this attributes will get overwrite by function set_blocking()
        //tty.c_cc[VMIN]  = 0;            // read doesn't block
        //tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl

        tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
                                        // enable reading
        tty.c_cflag &= ~(PARENB | PARODD);      // shut off parity
        tty.c_cflag |= parity;
        tty.c_cflag &= ~CSTOPB;
        tty.c_cflag &= ~CRTSCTS;

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
        {
                printf("error %d from tcsetattr", errno);
                return -1;
        }
        return 0;
}
Example #23
0
int configure_tty(char *tty_path, speed_t speed) {
  /*
   * TTY configuration inspired by:
   *   - Contiki/tunslip code
   *   - http://www.unixwiz.net/techtips/termios-vmin-vtime.html
   *   - termios manpage
   *   - http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/x115.html
   */
  int serial_fd;
  struct termios tty;
  memset(&tty, 0, sizeof(tty));
  
  serial_fd = open(tty_path, O_RDWR );
  if (serial_fd == -1) {
    printf("Could not open %s\n", tty_path);
    return -1;
  }

  if (tcflush(serial_fd, TCIOFLUSH) == -1) {
    printf("Error in tcflush: %s\n",
		strerror(errno));
    return -2;
  }

  if (tcgetattr(serial_fd, &tty)) {
    printf("Error in tcgetattr: %s\n",
		strerror(errno));
    return -3;
  }
  
  /*
   * Configure TTY
   */
  cfmakeraw(&tty);
  // blocking mode, should read at least 1 char and then can return
  tty.c_cc[VMIN]  = 1;
  tty.c_cc[VTIME] = 0;
  // Disable control characters and signals and all
  tty.c_cflag &= ~CRTSCTS; // Disable RTS/CTS (hardware) flow control
  tty.c_cflag &= ~HUPCL;   // No "hanging up" when closing
  tty.c_cflag |=  CLOCAL;  // ignore modem status line
  if (cfsetspeed(&tty, speed)) {
    printf("Error while setting terminal speed: %s\n",
		strerror(errno));
    return -4;
  }
  
  // Apply and discard characters that may have arrived
  if (tcsetattr(serial_fd, TCSAFLUSH, &tty) == -1) {
    printf("Error could not set attribute to tty: %s\n",
	   strerror(errno));
    return -5;
  }
  return serial_fd;
}
Example #24
0
int
crsf_config(int uart_fd)
{
	struct termios t;

	/* no parity, one stop bit */
	tcgetattr(uart_fd, &t);
	cfsetspeed(&t, CRSF_BAUDRATE);
	t.c_cflag &= ~(CSTOPB | PARENB);
	return tcsetattr(uart_fd, TCSANOW, &t);
}
Example #25
0
static gboolean
fu_altos_device_tty_open (FuAltosDevice *self, GError **error)
{
	struct termios termios;
	g_autoptr(GString) str = NULL;

	/* open device */
	self->io_channel = fu_io_channel_new_file (self->tty, error);
	if (self->io_channel == NULL)
		return FALSE;

	/* get the old termios settings so we can restore later */
	if (tcgetattr (fu_io_channel_unix_get_fd (self->io_channel), &termios) < 0) {
		g_set_error_literal (error,
				     FWUPD_ERROR,
				     FWUPD_ERROR_INTERNAL,
				     "failed to get attributes from fd");
		return FALSE;
	}
	self->tty_termios = termios;
	cfmakeraw (&termios);

	/* set speed */
	if (cfsetspeed (&termios, B9600) < 0) {
		g_set_error_literal (error,
				     FWUPD_ERROR,
				     FWUPD_ERROR_INTERNAL,
				     "failed to set terminal speed");
		return FALSE;
	}

	/* one input byte is enough to return
	 * inter-character timer off */
	termios.c_cc[VMIN]  = 1;
	termios.c_cc[VTIME] = 0;

	/* set all new data */
	if (tcsetattr (fu_io_channel_unix_get_fd (self->io_channel),
		       TCSAFLUSH, &termios) < 0) {
		g_set_error_literal (error,
				     FWUPD_ERROR,
				     FWUPD_ERROR_INTERNAL,
				     "failed to set attributes on fd");
		return FALSE;
	}

	/* dump any pending input */
	str = fu_altos_device_tty_read (self, 50, -1, NULL);
	if (str != NULL)
		g_debug ("dumping pending buffer: %s", str->str);

	return TRUE;
}
Example #26
0
static int OpenSerialDevice(const char *dev)
{
    int				fileDescriptor = -1;
    int				handshake;
    struct termios	options;
    
    fileDescriptor = open(dev, O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (fileDescriptor == -1){
        close(fileDescriptor);
    }
    
    if (ioctl(fileDescriptor, TIOCEXCL) == -1){
        close(fileDescriptor);
    }

    if (tcgetattr(fileDescriptor, &origOptions) == -1){
        close(fileDescriptor);
    }
    
    options = origOptions;
    
    cfmakeraw(&options);
    options.c_cc[VMIN] = 1;
    options.c_cc[VTIME] = 10; 
    cfsetspeed(&options, 115200);		// Set 115200 baud 
			

    
    if (tcsetattr(fileDescriptor, TCSANOW, &options) == -1){
        close(fileDescriptor);
    }
    
    if (ioctl(fileDescriptor, TIOCSDTR) == -1){
        close(fileDescriptor);
    }
    
    if (ioctl(fileDescriptor, TIOCCDTR) == -1) {
        close(fileDescriptor);
    }
    
    handshake = TIOCM_DTR | TIOCM_RTS | TIOCM_CTS | TIOCM_DSR;
    if (ioctl(fileDescriptor, TIOCMSET, &handshake) == -1){
        close(fileDescriptor);
    }
    
    if (ioctl(fileDescriptor, TIOCMGET, &handshake) == -1){
        close(fileDescriptor);
    }
    

    return fileDescriptor;
    return -1;
}
Example #27
0
int control_tty(const char *path, unsigned int speed)
{
	struct control_data *data;
	struct termios ti;
	int fd, err;

	fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK);
	if (fd < 0) {
		err = -errno;
		perror("Failed to open serial port");
		return err;
	}

	if (tcflush(fd, TCIOFLUSH) < 0) {
		err = -errno;
		perror("Failed to flush serial port");
		close(fd);
		return err;
	}

	memset(&ti, 0, sizeof(ti));
	/* Switch TTY to raw mode */
	cfmakeraw(&ti);

	ti.c_cflag |= (CLOCAL | CREAD);
	ti.c_cflag &= ~CRTSCTS;

	cfsetspeed(&ti, speed);

	if (tcsetattr(fd, TCSANOW, &ti) < 0) {
		err = -errno;
		perror("Failed to set serial port settings");
		close(fd);
		return err;
	}

	printf("--- %s opened ---\n", path);

	data = malloc(sizeof(*data));
	if (!data) {
		close(fd);
		return -ENOMEM;
	}

	memset(data, 0, sizeof(*data));
	data->channel = HCI_CHANNEL_MONITOR;
	data->fd = fd;

	mainloop_add_fd(data->fd, EPOLLIN, tty_callback, data, free_data);

	return 0;
}
Example #28
0
FILE* gl_term_run(GLTerminal* term, char* cmd) {
      int rc;
      if(fork()) {
         close(term->fd_slave);
         fcntl(term->fd_master, F_SETFL, FNDELAY);
         return fdopen(term->fd_master,"r+");
      } else {
         close(term->fd_master);
         struct termios slave_orig_term_settings;
         struct termios new_term_settings;

         rc                = tcgetattr(term->fd_slave, &slave_orig_term_settings);
         new_term_settings = slave_orig_term_settings;
         cfmakeraw(&new_term_settings);
         new_term_settings.c_iflag = ICRNL|IXON;
         new_term_settings.c_oflag = OPOST|ONLCR;
         new_term_settings.c_cflag = CS8|CREAD|OFILL;
         new_term_settings.c_lflag = ISIG|ICANON|IEXTEN|ECHO|ECHOE|ECHOK;
  new_term_settings.c_cc[VINTR]    = 0x1f & 'C';
  new_term_settings.c_cc[VQUIT]    = 0x1f & '\\';
  new_term_settings.c_cc[VERASE]   = 0x7f;
  new_term_settings.c_cc[VKILL]    = 0x1f & 'U';
  new_term_settings.c_cc[VEOF]     = 0x1f & 'D';
  new_term_settings.c_cc[VEOL]     = '\r';
  new_term_settings.c_cc[VEOL2]    = '\n';
  new_term_settings.c_cc[VSTART]   = 0x1f & 'Q';
  new_term_settings.c_cc[VSTOP]    = 0x1f & 'S';
  new_term_settings.c_cc[VSUSP]    = 0x1f & 'Z';
  new_term_settings.c_cc[VREPRINT] = 0x1f & 'R';
  new_term_settings.c_cc[VWERASE]  = 0x1f & 'W';
  new_term_settings.c_cc[VLNEXT]   = 0x1f & 'V';
  new_term_settings.c_cc[VMIN]     = 1;
  new_term_settings.c_cc[VTIME]    = 0;
         cfsetspeed(&new_term_settings, 38400);

         tcsetattr(term->fd_slave, TCSANOW, &new_term_settings);

         close(0);
         close(1);
         close(2);
         dup(term->fd_slave);
         dup(term->fd_slave);
         dup(term->fd_slave);
         close(term->fd_slave);
         setsid();
         ioctl(0, TIOCSCTTY, 1);
         char *argv[] = {"-l","-c",strdup(cmd),NULL};
         char *envp[] = {"TERM=xterm-256color",NULL};
         execve("/bin/sh",argv,envp);
      }
}
Example #29
0
int main(int argc, char *argv[])
{
  struct termios settings;

  const int fd = open(serport, O_RDWR);
  int modules;
  int i;

  if (fd < 0) {
    printf("Failed to open %s due to: %s\n", serport, strerror(errno));
    goto failed_open;
  }
  if (tcgetattr(fd, &settings) < 0) {
    perror("Failed to get attributes\n");
    goto failed_attr;
  }
  printf("before: c_lflag = %x, c_cflag = %x\n", settings.c_lflag, settings.c_cflag);
  if (cfsetspeed(&settings, B9600) < 0) {
    perror("Failed to set attributes\n");
    goto failed_attr;
  }
  settings.c_cflag |= CLOCAL;
  settings.c_cflag &= ~CSTOPB;
  settings.c_cflag &= ~CSIZE;
  settings.c_cflag |= CS8;
  printf("after: c_lflag = %x, c_cflag = %x\n", settings.c_lflag, settings.c_cflag);
  if (tcsetattr(fd, TCSANOW, &settings) < 0) {
    perror("Failed to set attributes\n");
    goto failed_attr;
  }

  modules = read_no_of_modules(fd);

  for (i=0; i < modules; i++) {
    const int attrs = read_no_of_attributes(fd, i);
    int j;

    for (j=0; j < attrs; j++) {
      struct dev_attr_info attr;

      read_attr_def(fd, i, j, &attr);
      read_attr_value(fd, i, j, 0xFF, attr.type);
    }
  }


 failed_attr:
  close(fd);
 failed_open:
  return 0;
}
// Given the path to a serial device, open the device and configure it for
// using given entryIndex. Answer 1 if the operation succeeds, 0 if it fails.
int OpenPortNamed(const char *bsdPath, int baudRate, int entryIndex) {
    int fDescr = -1;
    struct termios options;

    // open the serial port read/write with no controlling terminal; don't block
    fDescr = open(bsdPath, O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (fDescr == -1) {
        printf("Error opening serial port %s - %s(%d).\n", bsdPath, strerror(errno), errno);
        goto error;
    }

    // request exclusive access to the port
    if (ioctl(fDescr, TIOCEXCL) == -1) {
        printf("Error setting TIOCEXCL on %s - %s(%d).\n", bsdPath, strerror(errno), errno);
        goto error;
    }

    // save port settings so we can restore them later
    if (tcgetattr(fDescr, &gOrigTermios[entryIndex]) == -1) {
        printf("Error getting attributes %s - %s(%d).\n", bsdPath, strerror(errno), errno);
        goto error;
    }

    // port settings are made by modifying a copy of the termios struct
    // and then calling tcsetattr() to make those changes take effect.
    options = gOrigTermios[entryIndex];

    // set the baud rate
    if (cfsetspeed(&options, baudRate) == -1) {
        printf("Error setting speed %d %s - %s(%d).\n", baudRate, bsdPath, strerror(errno), errno);
        goto error;
    }

    // set raw input (non-canonical) mode, with writes not blocking.
    cfmakeraw(&options);
    options.c_cc[VMIN] = 0;
    options.c_cc[VTIME] = 0;

    // install the new port settings
    if (tcsetattr(fDescr, TCSANOW, &options) == -1) {
        printf("Error setting attributes %s - %s(%d).\n", bsdPath, strerror(errno), errno);
        goto error;
    }
    gFileDescr[entryIndex] = fDescr;
    return 1; // success!

error:
    if (fDescr != -1) close(fDescr);
    return 0;
}