]> git.itanic.dy.fi Git - log-plotter/blob - baud.c
options: Fix short option for --baud
[log-plotter] / baud.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <fcntl.h>
4 #include <errno.h>
5 #include <string.h>
6 #include <linux/termios.h>
7 #include <unistd.h>
8 #include "debug.h"
9
10 /*
11  * HACK: declare the ioctl function by hand...
12  *
13  * We cannot include <sys/ioctl.h> as it will eventually include
14  * <termios.h>, which will conflict with <linux/temios.h>. As we
15  * really need the latter one AND the ioctl, just declare it by hand
16  * here so that we get to use it...
17  */
18 int ioctl(int d, int request, ...);
19
20 /**
21  * Open a serial device and adjust the baud rate to give (arbitrary)
22  * baud rate. The actual baud rate is stored back to the @baud
23  * variable. This might differ from the requested one as the
24  * underlying hardware may not support all possible baud
25  * rates.
26  *
27  * Returns the file descriptor that was opened.
28  */
29 int open_at_baud(const char *device, int *baud)
30 {
31         struct termios2 tios;
32         int fd;
33
34         fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY);
35
36         if (fd == -1) {
37                 pr_err("error opening %s: %m\n", device);
38                 return fd;
39         }
40
41         if (ioctl(fd, TCGETS2, &tios)) {
42                 pr_err("TCGETS2: %m\n");
43                 goto err;
44         }
45
46         tios.c_cflag &= ~CBAUD;
47         tios.c_cflag |= BOTHER;
48         tios.c_ispeed = *baud;
49         tios.c_ospeed = *baud;
50
51         if (ioctl(fd, TCSETS2, &tios)) {
52                 pr_err("TCSETS2: %m");
53                 goto err;
54         }
55
56         if (ioctl(fd, TCGETS2, &tios)) {
57                 pr_err("TCGETS2: %m");
58                 goto err;
59         }
60
61         *baud = tios.c_ospeed;
62
63         return fd;
64 err:
65         close(fd);
66
67         return -1;
68 }