-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhidp_server.cc
More file actions
97 lines (83 loc) · 2.73 KB
/
hidp_server.cc
File metadata and controls
97 lines (83 loc) · 2.73 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
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
#include "hidp_common.h"
#include "hidp_device.h"
#include "hidp_net.h"
#include "hidp_proto.h"
#include <memory>
#include <errno.h>
#include <string.h>
#include <sys/select.h>
int main(int argc, char *argv[])
{
InputDeviceMonitor device_monitor;
std::string listen_addr = "10.0.0.133";
int listen_port = 10020;
if (argc > 2) {
listen_addr = argv[1];
listen_port = static_cast<int>(strtol(argv[2], nullptr, 10));
}
TcpListener tcp_listener(listen_addr.c_str(), listen_port);
tcp_listener.Start();
std::unique_ptr<Socket> client;
std::vector< std::unique_ptr<InputDevice> > input_devices = device_monitor.FindAll();
while (true) {
fd_set read_fds;
FD_ZERO(&read_fds);
int max_fd = -1;
fd_set_add(read_fds, tcp_listener, &max_fd);
fd_set_add(read_fds, device_monitor, &max_fd);
for (const std::unique_ptr<InputDevice> &dev : input_devices)
fd_set_add(read_fds, dev, &max_fd);
if (client)
fd_set_add(read_fds, client, &max_fd);
int ret = select(max_fd + 1, &read_fds, nullptr, nullptr, nullptr);
if (ret == -1) {
XLOG_INFO("select returned error. %s", strerror(errno));
continue;
}
if (fd_is_set(read_fds, tcp_listener)) {
client = tcp_listener.Accept();
ProtocolWriter writer(*client);
for (const std::unique_ptr<InputDevice> &dev : input_devices)
writer.SendCreate(dev);
}
if (client && fd_is_set(read_fds, client)) {
ProtocolReader reader(*client);
reader.ProcessIncomingClientMessage(input_devices);
}
if (fd_is_set(read_fds, device_monitor)) {
device_monitor.ReadNext(
[&input_devices, &client](std::unique_ptr<InputDevice> new_device) {
if (client) {
ProtocolWriter writer(*client);
writer.SendCreate(new_device);
}
input_devices.push_back(std::move(new_device));
},
// device disconnected
[&input_devices, &client](std::string uuid) {
XLOG_INFO("device disconnected");
auto old_device = std::find_if(std::begin(input_devices), std::end(input_devices),
[&uuid](const std::unique_ptr<InputDevice>& dev)
{
return dev->GetId() == uuid;
});
if (old_device != std::end(input_devices)) {
if (client) {
ProtocolWriter writer(*client);
writer.SendDelete(*old_device);
}
input_devices.erase(old_device);
}
});
}
for (std::unique_ptr<InputDevice> &dev : input_devices) {
if (fd_is_set(read_fds, dev)) {
dev->ReadInputReport();
if (client) {
ProtocolWriter writer(*client);
writer.SendInputReport(dev);
}
}
}
}
}