-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserial.cpp
More file actions
61 lines (50 loc) · 1.16 KB
/
serial.cpp
File metadata and controls
61 lines (50 loc) · 1.16 KB
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
#include <stdexcept>
#include <string_view>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include "serial.hpp"
namespace multicast
{
namespace serial
{
Device::Device(std::string_view path)
{
fd_ = open(path.data(), O_WRONLY | O_NOCTTY | O_SYNC);
if (fd_ < 0)
{
throw std::runtime_error("failed to open serial device");
}
termios tty{};
if (tcgetattr(fd_, &tty) != 0)
{
close(fd_);
std::runtime_error("tcgetattr failed");
}
if (cfsetospeed(&tty, B9600) != 0)
{
close(fd_);
std::runtime_error("cfsetospeed failed");
}
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;
tty.c_cflag |= CLOCAL | CREAD;
tty.c_cflag &= ~(PARENB | CSTOPB | CRTSCTS);
tty.c_lflag = 0;
tty.c_oflag = 0;
tty.c_iflag = 0;
if (tcsetattr(fd_, TCSANOW, &tty) != 0)
{
close(fd_);
std::runtime_error("tcsetattr failed");
}
}
int Device::Handler() const noexcept
{
return fd_;
}
bool send(const Device& device, std::string_view message)
{
return write(device.Handler(), message.data(), message.size()) >= 0;
}
} // namespace serial
} // namespace multicast