Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
alexbevi
GitHub Repository: alexbevi/BizHawk
Path: blob/master/libsnes/bsnes/nall/serial.hpp
2 views
1
#ifndef NALL_SERIAL_HPP
2
#define NALL_SERIAL_HPP
3
4
#include <sys/ioctl.h>
5
#include <fcntl.h>
6
#include <termios.h>
7
#include <unistd.h>
8
9
#include <nall/stdint.hpp>
10
11
namespace nall {
12
class serial {
13
public:
14
//-1 on error, otherwise return bytes read
15
int read(uint8_t *data, unsigned length) {
16
if(port_open == false) return -1;
17
return ::read(port, (void*)data, length);
18
}
19
20
//-1 on error, otherwise return bytes written
21
int write(const uint8_t *data, unsigned length) {
22
if(port_open == false) return -1;
23
return ::write(port, (void*)data, length);
24
}
25
26
bool open(const char *portname, unsigned rate, bool flowcontrol) {
27
close();
28
29
port = ::open(portname, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
30
if(port == -1) return false;
31
32
if(ioctl(port, TIOCEXCL) == -1) { close(); return false; }
33
if(fcntl(port, F_SETFL, 0) == -1) { close(); return false; }
34
if(tcgetattr(port, &original_attr) == -1) { close(); return false; }
35
36
termios attr = original_attr;
37
cfmakeraw(&attr);
38
cfsetspeed(&attr, rate);
39
40
attr.c_lflag &=~ (ECHO | ECHONL | ISIG | ICANON | IEXTEN);
41
attr.c_iflag &=~ (BRKINT | PARMRK | INPCK | ISTRIP | INLCR | IGNCR | ICRNL | IXON | IXOFF | IXANY);
42
attr.c_iflag |= (IGNBRK | IGNPAR);
43
attr.c_oflag &=~ (OPOST);
44
attr.c_cflag &=~ (CSIZE | CSTOPB | PARENB | CLOCAL);
45
attr.c_cflag |= (CS8 | CREAD);
46
if(flowcontrol == false) {
47
attr.c_cflag &= ~CRTSCTS;
48
} else {
49
attr.c_cflag |= CRTSCTS;
50
}
51
attr.c_cc[VTIME] = attr.c_cc[VMIN] = 0;
52
53
if(tcsetattr(port, TCSANOW, &attr) == -1) { close(); return false; }
54
return port_open = true;
55
}
56
57
void close() {
58
if(port != -1) {
59
tcdrain(port);
60
if(port_open == true) {
61
tcsetattr(port, TCSANOW, &original_attr);
62
port_open = false;
63
}
64
::close(port);
65
port = -1;
66
}
67
}
68
69
serial() {
70
port = -1;
71
port_open = false;
72
}
73
74
~serial() {
75
close();
76
}
77
78
private:
79
int port;
80
bool port_open;
81
termios original_attr;
82
};
83
}
84
85
#endif
86
87