forked from sanpeqf/w80xprog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
termios.c
144 lines (116 loc) · 2.79 KB
/
termios.c
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
/* SPDX-License-Identifier: GPL-2.0-or-later */
/*
* Copyright(c) 2021 Sanpe <[email protected]>
*/
#include "w80xprog.h"
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <termios.h>
static int ttys;
int termios_setspeed(unsigned int speed)
{
struct termios term;
int retval;
retval = tcgetattr(ttys, &term);
if (retval)
return retval;
retval = cfsetspeed(&term, speed);
if (retval)
return retval;
tcflush(ttys, TCIOFLUSH);
return tcsetattr(ttys, TCSANOW, &term);
}
int termios_setup(unsigned int speed, int databits, int stopbits, char parity)
{
struct termios term;
int retval;
retval = termios_setspeed(speed);
if (retval)
return retval;
retval = tcgetattr(ttys, &term);
if (retval)
return retval;
term.c_cflag |= (CLOCAL | CREAD);
term.c_cflag &= ~CSIZE;
if (databits == 7)
term.c_cflag |= CS7;
else
term.c_cflag |= CS8;
if (stopbits == 2)
term.c_cflag |= CSTOPB;
else
term.c_cflag &= ~CSTOPB;
switch (parity){
case 'N': case 'n':
term.c_cflag &= ~PARENB;
term.c_iflag &= ~INPCK;
break;
case 'O': case 'o':
term.c_cflag |= (PARODD | PARENB);
term.c_iflag |= INPCK;
break;
case 'E': case 'e':
term.c_cflag |= PARENB;
term.c_cflag &= ~PARODD;
term.c_iflag |= INPCK;
break;
case 'S': case 's':
term.c_cflag &= ~PARENB;
term.c_cflag &= ~CSTOPB;
break;
}
if (parity != 'n')
term.c_iflag |= INPCK;
term.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
term.c_oflag &= ~OPOST;
term.c_cc[VTIME] = 255;
term.c_cc[VMIN] = 0;
tcflush(ttys, TCIOFLUSH);
tcsetattr(ttys, TCSANOW, &term);
return 0;
}
int termios_rts(bool enable)
{
unsigned int state;
int ret;
ret = ioctl(ttys, TIOCMGET, &state);
if (ret)
return ret;
if (enable)
state |= TIOCM_RTS;
else
state &= ~TIOCM_RTS;
return ioctl(ttys, TIOCMSET, &state);
}
int termios_flush(void)
{
return tcflush(ttys, TCIFLUSH);
}
int termios_read(void *data, unsigned long len)
{
int ret = read(ttys, data, len);
tcflush(ttys, TCIFLUSH);
return ret;
}
int termios_write(const void *data, unsigned long len)
{
int ret = write(ttys, data, len);
tcflush(ttys, TCOFLUSH);
return ret;
}
int termios_print(const char *str)
{
unsigned int len = strlen(str);
return termios_write(str, len);
}
int termios_open(char *path)
{
if (ttys)
return -EALREADY;
ttys = open(path, O_RDWR | O_NOCTTY | O_NDELAY);
fcntl(ttys, F_SETFL, 0);
return ttys < 0 ? ttys : 0;
}