imme-dongle.tar.gz
[imme-dongle] / linux / tty_posix.c
1 #include <stdlib.h>
2 #include <string.h>
3 #include <sys/select.h>
4 #include <termios.h>
5 #include <unistd.h>
6
7 #include "tty_posix.h"
8 #include "console.h"
9
10 /**************************************************/
11
12 static struct termios orig_termios;
13
14 /**************************************************/
15
16 static void reset_terminal_mode()
17 {
18     tcsetattr(0, TCSANOW, &orig_termios);
19 }
20
21 static void set_conio_terminal_mode()
22 {
23     struct termios new_termios;
24
25     /* take two copies - one for now, one for later */
26     tcgetattr(0, &orig_termios);
27     memcpy(&new_termios, &orig_termios, sizeof(new_termios));
28
29     /* register cleanup handler, and set the new terminal mode */
30     atexit(reset_terminal_mode);
31     cfmakeraw(&new_termios);
32     tcsetattr(0, TCSANOW, &new_termios);
33 }
34
35 static int kbhit(void)
36 {
37     struct timeval tv = { 0L, 0L };
38     fd_set fds;
39     FD_SET(0, &fds);
40     return select(1, &fds, NULL, NULL, &tv);
41 }
42
43 static int getch(void)
44 {
45     int r;
46     unsigned char c;
47     if ((r = read(0, &c, 1)) < 0)
48         return r;
49     else
50         return c;
51 }
52
53 /**************************************************/
54
55 void tty_init(void)
56 {
57     set_conio_terminal_mode();
58 }
59
60 void tty_tick(void)
61 {
62     if (console_rx_ready_callback())
63     {
64         if (kbhit())
65             console_rx_callback(getch());
66     }
67 }
68
69 void tty_putc(char c)
70 {
71     write(1, &c, 1);
72 }
73
74
75