summaryrefslogtreecommitdiff
path: root/util/tty.c
blob: be56b4410b19fef7ec74a021692e7d244a1dfc90 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <stdlib.h>

#include <fcntl.h>
#include <termios.h>
#include <unistd.h>

int tty_open(char *tty_fn) {
    struct termios tty;
    int tty_fd;
    int rv;

    tty_fd = open(tty_fn, O_RDWR);
    if (tty_fd < 0) return tty_fd;

    rv = tcgetattr(tty_fd, &tty);
    if (rv) return -1;

    tty.c_cflag &= ~PARENB;   // No parity
    tty.c_cflag &= ~CSTOPB;   // One stop bit
    tty.c_cflag &= ~CSIZE;    // Clear all bits that set the data size
    tty.c_cflag |=  CS8;      // 8 bits per byte
    tty.c_cflag &= ~CRTSCTS;  // Disable RTS/CTS hw flow control
    tty.c_cflag |= (CREAD | CLOCAL);  // Turn on READ & ignore ctrl lines (CLOCAL = 1)

    tty.c_lflag &= ~ICANON;
    tty.c_lflag &= ~(ECHO | ECHOE |ECHONL); // Disable echo
    tty.c_lflag &= ~ISIG;     // Disable interpretation of INTR, QUIT and SUSP signals
    tty.c_iflag &= ~(IXON | IXOFF | IXANY);   // Turn off sw flow ctrl
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL);  // Disable any special handling of received bytes

    tty.c_oflag &= ~OPOST;    // Prevent special interpretation of output bytes (e.g. newline chars)
    tty.c_oflag &= ~ONLCR;    // Prevent conversion of newline to carriage return/line feed
#ifndef __linux__
    tty.c_oflag &= ~OXTABS;   // Prevent conversion of tabs to spaces (NOT PRESENT ON LINUX)
    tty.c_oflag &= ~ONOEOT;   // Prevent removal of C-d chars (0x004) in output (NOT PRESENT ON LINUX)
#endif

    tty.c_cc[VTIME] = 10;     // Wait for up to 1s (10 deciseconds), returning as soon as any data is received.
    tty.c_cc[VMIN] = 0;

    cfsetispeed(&tty, B115200);
    cfsetospeed(&tty, B115200);

    rv = tcsetattr(tty_fd, TCSANOW, &tty);
    if (rv) return -1;

    return tty_fd;
};