-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathSocketThread.cpp
More file actions
335 lines (268 loc) · 8.33 KB
/
SocketThread.cpp
File metadata and controls
335 lines (268 loc) · 8.33 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#ifdef _WIN32
#include <Windows.h>
#endif
#include "EphysSocket.h"
#include "SocketThread.h"
using namespace EphysSocketNode;
SocketThread::SocketThread (String name, EphysSocket* processor_)
: Thread (name), processor (processor_)
{
lastPacketReceived = time (nullptr);
socket = nullptr;
previousPort = -1;
depth = DEFAULT_DEPTH;
element_size = DEFAULT_ELEMENT_SIZE;
num_bytes = DEFAULT_NUM_BYTES;
num_channels = DEFAULT_NUM_CHANNELS;
num_samp = DEFAULT_NUM_SAMPLES;
error_flag = false;
connected = false;
shouldReconnect = false;
acquiring = false;
}
SocketThread::~SocketThread()
{
stopThread (1000);
if (socket != nullptr)
{
socket->close();
socket.reset();
}
}
void SocketThread::startAcquisition()
{
acquiring = true;
}
void SocketThread::stopAcquisition()
{
acquiring = false;
if (shouldReconnect)
{
processor->disconnectSocket();
}
}
bool SocketThread::connectSocket (int port, bool printOutput)
{
if (port == -1)
{
if (previousPort != -1)
{
port = previousPort;
}
else
{
LOGE ("Must give a valid port number for the first connection.");
return false;
}
}
std::lock_guard<std::mutex> lock (socketMutex);
if (socket != nullptr && socket->isConnected())
{
LOGE ("Attempting to connect to an already active socket.");
return false;
}
error_flag = false;
socket = std::make_unique<StreamingSocket>();
connected = socket->connect ("localhost", port, 250);
if (connected)
{
std::vector<std::byte> header_bytes (HEADER_SIZE);
LOGD ("Reading header...");
int rc;
for (int i = 0; i < 5; i++)
{
rc = socket->read (header_bytes.data(), HEADER_SIZE, false);
if (rc == HEADER_SIZE)
break;
else
sleep (100);
}
if (rc != HEADER_SIZE)
{
if (printOutput)
{
LOGC ("EphysSocket failed to connect; could not read header from stream. Bytes read: ", rc);
CoreServices::sendStatusMessage ("Ephys Socket: Could not read stream.");
}
socket->close();
socket.reset();
connected = false;
return false;
}
EphysSocketHeader tmp_header = EphysSocketHeader (header_bytes);
LOGD ("Header read and parsed correctly.");
num_bytes = tmp_header.num_bytes;
element_size = tmp_header.element_size;
depth = tmp_header.depth;
num_samp = tmp_header.num_samp;
num_channels = tmp_header.num_channels;
const int matrix_size = num_channels * num_samp * element_size;
header_bytes.reserve (matrix_size);
socket->read (header_bytes.data(), matrix_size, true); // NB: Realign stream to the beginning of a packet
lastPacketReceived = time (nullptr);
previousPort = port;
if (printOutput)
{
LOGC ("EphysSocket connected.");
CoreServices::sendStatusMessage ("Ephys Socket: Socket connected.");
}
read_buffer.resize (num_channels * num_samp * element_size + HEADER_SIZE);
shouldReconnect = false;
bool result = startThread();
return true;
}
else
{
if (printOutput)
{
LOGC ("EphysSocket failed to connect");
CoreServices::sendStatusMessage ("Ephys Socket: Could not connect.");
}
return false;
}
}
void SocketThread::disconnectSocket()
{
std::lock_guard<std::mutex> lock (socketMutex);
if (socket != nullptr)
{
LOGD ("Disconnecting socket.");
socket->close();
socket.reset();
CoreServices::sendStatusMessage ("Ephys Socket: Disconnected.");
}
connected = false;
shouldReconnect = false;
}
bool SocketThread::isConnected()
{
return connected;
}
bool SocketThread::isError() const
{
return error_flag;
}
bool SocketThread::compareHeaders (EphysSocketHeader header) const
{
if (header.depth != depth || header.element_size != element_size || header.num_channels != num_channels || header.num_samp != num_samp)
{
return false;
}
return true;
}
void SocketThread::attemptToReconnect()
{
auto previousHeader = EphysSocketHeader (num_bytes, depth, element_size, num_samp, num_channels);
if (connectSocket (previousPort, false))
{
shouldReconnect = false;
if (! compareHeaders (previousHeader))
{
disconnectSocket();
LOGE ("Mismatched header, disconnecting socket.");
CoreServices::sendStatusMessage ("Ephys Socket: Invalid header, disconnecting.");
error_flag = true;
return;
}
LOGD ("Successfully reconnected the socket.");
CoreServices::sendStatusMessage ("Ephys Socket: Socket reconnected.");
lastPacketReceived = time (nullptr);
}
}
void SocketThread::run()
{
while (! threadShouldExit())
{
if (connected)
{
if (error_flag)
{
const MessageManagerLock mmLock;
processor->disconnectSocket();
return;
}
std::lock_guard<std::mutex> lock (socketMutex);
const int bytes_expected = num_channels * num_samp * element_size + HEADER_SIZE;
int rc;
EphysSocketHeader header;
if (socket != nullptr && socket->isConnected())
{
rc = socket->read (read_buffer.data(), bytes_expected, false);
}
else
{
rc = 0; // NB: This will attempt to reconnect the socket below
}
if (rc == -1)
{
if (socket->getRawSocketHandle() == -1)
{
CoreServices::sendStatusMessage ("Ephys Socket: Socket handle invalid.");
LOGE ("Ephys Socket: Socket handle is invalid");
error_flag = true;
continue;
}
else
{
CoreServices::sendStatusMessage ("Ephys Socket: Socket read error");
LOGE ("Ephys Socket: Reading from socket did not complete");
error_flag = true;
continue;
}
}
else if (rc == 0)
{
if (difftime (time (nullptr), lastPacketReceived) >= 2)
{
LOGD ("Last packet was too old.");
socket->close();
socket.reset();
connected = false;
shouldReconnect = true;
LOGC ("EphysSocket has been disconnected. Attempting to reconnect now.");
CoreServices::sendStatusMessage ("Ephys Socket: Attempting to reconnect...");
}
continue;
}
else if (rc != bytes_expected)
{
int bytes_received = rc;
while (bytes_received < bytes_expected)
{
rc = socket->read (read_buffer.data() + bytes_received, bytes_expected - bytes_received, false);
if (rc != 0)
{
bytes_received += rc;
}
if (threadShouldExit())
{
return;
}
}
}
header = EphysSocketHeader (read_buffer);
if (! compareHeaders (header))
{
CoreServices::sendStatusMessage ("Ephys Socket: Invalid header");
LOGE ("Ephys Socket: Header values have changed since first connecting");
error_flag = true;
continue;
}
lastPacketReceived = time (nullptr);
if (acquiring)
{
data.add (read_buffer);
}
}
else if (shouldReconnect)
{
attemptToReconnect();
if (error_flag)
{
const MessageManagerLock mmLock;
processor->disconnectSocket();
return;
}
}
}
}