forked from cymait/virtual-serial-port-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
102 lines (84 loc) · 2.29 KB
/
main.cpp
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
/**
* Serial port example.
* Compile with: g++ main.cpp -lpthread -o main
*
* Cymait http://cymait.com
**/
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <termios.h>
#define BUFFER_SIZE 128
#define BAUDRATE B9600
void usage(char* cmd) {
std::cerr << "usage: " << cmd << " slave|master [device, only in slave mode]" << std::endl;
exit(EXIT_FAILURE);
}
void* reader_thread(void* pointer) {
int fd = *((int*)pointer);
char inputbyte;
while (read(fd, &inputbyte, 1) == 1) {
std::cout << inputbyte;
std::cout.flush();
}
return 0;
}
int main(int argc, char** argv) {
if (argc < 2) usage(argv[0]);
int fd = 0;
std::string mode = argv[1];
if (mode == "slave") {
if (argc < 3) usage(argv[0]);
fd = open(argv[2], O_RDWR);
if (fd == -1) {
std::cerr << "error opening file " << argv[2] << std::endl;
return -1;
}
} else if (mode == "master") {
std::string device = "/dev/ptmx";
fd = open(device.c_str(), O_RDWR | O_NOCTTY);
if (fd == -1) {
std::cerr << "error opening file " << device << std::endl;
return -1;
}
grantpt(fd);
unlockpt(fd);
char* pts_name = ptsname(fd);
std::cerr << "ptsname: " << pts_name << std::endl;
} else {
std::cerr << "unknown mode " << mode << std::endl;
usage(argv[0]);
}
/* serial port parameters */
struct termios newtio;
memset(&newtio, 0, sizeof(newtio));
struct termios oldtio;
tcgetattr(fd, &oldtio);
newtio = oldtio;
newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
newtio.c_iflag = 0;
newtio.c_oflag = 0;
newtio.c_lflag = 0;
newtio.c_cc[VMIN] = 1;
newtio.c_cc[VTIME] = 0;
tcflush(fd, TCIFLUSH);
cfsetispeed(&newtio, BAUDRATE);
cfsetospeed(&newtio, BAUDRATE);
tcsetattr(fd, TCSANOW, &newtio);
/* start reader thread */
pthread_t thread;
pthread_create(&thread, 0, reader_thread, (void*)(&fd));
/* read from stdin and send it to the serial port */
char c;
while (true) {
std::cin >> c;
write(fd, &c, 1);
}
close(fd);
return 0;
}