-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplatform.h
103 lines (67 loc) · 2.03 KB
/
platform.h
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
#pragma once
#include <cstdint>
void initSystem();
uint64_t cpuTime();
void pingHost(const char* userAgent, const char* hostName, int hostPort);
struct Socket{
int64_t fd;
static Socket* connect(const char* host, int port);
static Socket* open(int port, int flags);
Socket(int64_t descriptor);
virtual ~Socket();
// const char *read();
int receive(char *, int n);
int send(const char *,int n);
int serve(struct Connection *service);
void listen(int port, int flags, void* user);
int accept();
// int listen(struct Connection *service);
void close();
static int testOSCIn();
static int testOSCOut();
};
struct Connection {
virtual void onConnect(Socket* link, std::string address) = 0;
};
#include <cstdint>
#include <vector>
#include <thread>
using Bytes = std::vector<uint8_t>;
struct Device {
std::string deviceName;
std::thread* readThread;
Bytes readBuffer;
uint64_t deviceEpoch = 0;
virtual void CloseDevice() = 0;
virtual void onRead(Bytes payload) = 0;
virtual size_t readBytes(void* buffer, size_t length) = 0;
virtual size_t writeBytes(const void* buffer, size_t length) = 0;
uint64_t deviceTime() {
return cpuTime() - deviceEpoch;
}
void Open(std::string name) {
deviceEpoch = cpuTime();
deviceName = name;
readBuffer.resize(8192);
readThread = new std::thread(&Device::runRead, this);
}
void runRead() {
while (true) {
uint8_t* buffer = readBuffer.data();
size_t count = readBuffer.size();
if (count == 0) break; // TODO : device not open device_error
size_t n = readBytes(buffer, count);
if (n == 0) break;
#ifdef LOG_DEVICE_READ
for (int i = 0; i < n; i++) {
std::cout << std::hex << std::setfill('0') << std::setw(2) << (int)buffer[i] << " ";
}
std::cout << std::dec << std::endl;
#endif
//#else
// std::cout << "*" << n << "*" << std::flush;
onRead({ buffer, buffer + n });
}
}
};
Device *openSocket(std::string address, Socket *s);