-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbiosemi_io.cpp
More file actions
448 lines (393 loc) · 17.5 KB
/
biosemi_io.cpp
File metadata and controls
448 lines (393 loc) · 17.5 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
#include "biosemi_io.h"
#include <iostream>
#include <exception>
#include <vector>
#include <time.h>
#include "DLL/labview_dll.h"
#include <boost/lexical_cast.hpp>
// maximum waiting time when trying to connect
const float max_waiting_time = 3.0;
// size of the initial probing buffer
const int buffer_bytes = 8*1024*1024;
// preferred size of final buffer (note: must be a multiple of 512; also, ca. 32MB is a good size according to BioSemi)
const int buffer_samples = 60*512;
// 64 zero bytes
static char msg_enable[64] = {0};
// 0xFF followed by 63 zero bytes
static unsigned char msg_handshake[64] = {255,0};
std::string biosemi_io::get_last_error() {
#ifdef _WIN32
DWORD errorMessageID = GetLastError();
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
if (size)
{
std::string err_message(messageBuffer, size);
LocalFree(messageBuffer);
return err_message;
}
else
{
return std::string();
}
#else
return "?";
#endif
}
biosemi_io::biosemi_io() {
intptr_t start_idx; // index of the first sample that was recorded
intptr_t cur_idx; // index past the current sample
// === initialize driver ===
// connect to driver
std::cout << "Connecting to driver..." << std::endl;
hConn_ = OPEN_DRIVER_ASYNC();
if (!hConn_) {
throw std::runtime_error("Could not open connection to BioSemi driver.");
}
// initialize USB2 interface
std::cout << "Initializing USB interface..." << std::endl;
if (!USB_WRITE(hConn_,msg_enable)) {
CLOSE_DRIVER_ASYNC(hConn_);
throw std::runtime_error("Could not initialize BioSemi USB2 interface.");
}
// === allocate ring buffer and begin acquisiton ===
// initialize the initial (probing) ring buffer
std::cout << "Initializing ring buffer..." << std::endl;
ring_buffer_ = new boost::uint32_t[buffer_bytes];
if (!ring_buffer_) {
CLOSE_DRIVER_ASYNC(hConn_);
throw std::runtime_error("Could not allocate ring buffer (out of memory).");
}
memset(ring_buffer_,0,buffer_bytes);
// begin acquisition
READ_MULTIPLE_SWEEPS(hConn_,(char*)ring_buffer_,buffer_bytes);
// enable handshake
std::cout << "Enabling handshake..." << std::endl;
if (!USB_WRITE(hConn_,(char*) msg_handshake)) {
CLOSE_DRIVER_ASYNC(hConn_);
delete ring_buffer_;
throw std::runtime_error("Could not enable handshake with BioSemi USB2 interface.");
}
// === read the first sample ===
// obtain buffer head pointer
std::cout << "Querying buffer pointer..." << std::endl;
if (!READ_POINTER(hConn_,&start_idx)) {
USB_WRITE(hConn_, &msg_enable[0]);
CLOSE_DRIVER_ASYNC(hConn_);
delete ring_buffer_;
throw std::runtime_error("Can not obtain ring buffer pointer from BioSemi driver.");
}
// check head pointer validity
if (start_idx > buffer_bytes) {
USB_WRITE(hConn_, &msg_enable[0]);
CLOSE_DRIVER_ASYNC(hConn_);
delete ring_buffer_;
throw std::runtime_error("Buffer pointer returned by BioSemi driver is not in the valid range.");
}
// read the first sample
std::cout << "Waiting for data..." << std::endl;
clock_t start_time = clock();
while (1) {
// error checks...
if (!READ_POINTER(hConn_, &cur_idx)) {
USB_WRITE(hConn_, &msg_enable[0]);
CLOSE_DRIVER_ASYNC(hConn_);
delete ring_buffer_;
throw std::runtime_error("Ring buffer handshake with BioSemi driver failed unexpectedly.");
}
if ( ((double)(clock() - start_time))/CLOCKS_PER_SEC > max_waiting_time) {
USB_WRITE(hConn_, &msg_enable[0]);
CLOSE_DRIVER_ASYNC(hConn_);
delete ring_buffer_;
if (cur_idx - start_idx < 8)
throw std::runtime_error("BioSemi driver does not transmit data. Is the box turned on?");
else
throw std::runtime_error("Did not get a sync signal from BioSemi driver. Is the battery charged?");
}
if ((cur_idx - start_idx >= 8) && (ring_buffer_[0] == 0xFFFFFF00)) {
// got a sync signal on the first index...
start_idx = 0;
break;
}
if ((cur_idx - start_idx >= 8) && (ring_buffer_[start_idx/4] == 0xFFFFFF00))
// got the sync signal!
break;
}
// === parse amplifier configuration ===
// read the trigger channel data ...
std::cout << "Checking status..." << std::endl;
boost::uint32_t status = ring_buffer_[start_idx/4+1] >> 8;
std::cout << " status: " << status << std::endl;
// determine channel configuration
is_mk2_ = ((status&(1<<23)) != 0);
std::cout << " MK2: " << is_mk2_ << std::endl;
// check speed mode
speed_mode_ = ((status&(1<<17))>>17) + ((status&(1<<18))>>17) + ((status&(1<<19))>>17) + ((status&(1<<21))>>18);
std::cout << " speed mode: " << speed_mode_ << std::endl;
// check for problems...
if (speed_mode_ > 9) {
USB_WRITE(hConn_, &msg_enable[0]);
CLOSE_DRIVER_ASYNC(hConn_);
delete ring_buffer_;
if (is_mk2_)
throw std::runtime_error("BioSemi amplifier speed mode wheel must be between positions 0 and 8 (9 is a reserved value); recommended for typical use is 4.");
else
throw std::runtime_error("BioSemi amplifier speed mode wheel must be between positions 0 and 8 (9 is a reserved value); recommended for typical use is 4.");
}
// determine sampling rate (http://www.biosemi.com/faq/adjust_samplerate.htm)
switch (speed_mode_ & 3) {
case 0: srate_ = 2048; break;
case 1: srate_ = 4096; break;
case 2: srate_ = 8192; break;
case 3: srate_ = 16384; break;
}
// speed modes lower than 3 are special on Mk2 and are for daisy-chained setups (@2KHz)
bool multibox = false;
if (is_mk2_ && speed_mode_ < 4) {
srate_ = 2048;
multibox = true;
}
std::cout << " sampling rate: " << srate_ << std::endl;
// determine channel configuration -- this is written according to:
// http://www.biosemi.com/faq/make_own_acquisition_software.htm
// http://www.biosemi.com/faq/adjust_samplerate.htm
if (is_mk2_) {
// in an Mk2 the speed modes 0-3 are for up to 4 daisy-chained boxes; these are
// multiplexed, have 128ch EEG each and 8ch EXG each, plus 16 extra channels each (howdy!)
switch (speed_mode_) {
case 0:
case 1:
case 2:
case 3:
nbeeg_ = 4*128; nbexg_ = 4*8; nbaux_ = 4*16; nbaib_ = 0; nbtrig_ = 1; nbsync_ = 1; nbchan_ = 610; break;
// spd modes 4-7 are the regular ones and have 8 EXG's added in
case 4: nbeeg_ = 256; nbexg_ = 8; nbaux_ = 16; nbaib_ = 0; nbtrig_ = 1; nbsync_ = 1; nbchan_ = 282; break;
case 5: nbeeg_ = 128; nbexg_ = 8; nbaux_ = 16; nbaib_ = 0; nbtrig_ = 1; nbsync_ = 1; nbchan_ = 154; break;
case 6: nbeeg_ = 64; nbexg_ = 8; nbaux_ = 16; nbaib_ = 0; nbtrig_ = 1; nbsync_ = 1; nbchan_ = 90; break;
case 7: nbeeg_ = 32; nbexg_ = 8; nbaux_ = 16; nbaib_ = 0; nbtrig_ = 1; nbsync_ = 1; nbchan_ = 58; break;
// spd mode 8 adds
case 8: nbeeg_ = 256; nbexg_ = 8; nbaux_ = 16; nbaib_ = 32; nbtrig_ = 1; nbsync_ = 1; nbchan_ = 314; break;
}
} else {
// in a Mk1 the EXG's are off in spd mode 0-3 and on in spd mode 4-7 (but subtracted from the EEG channels)
switch (speed_mode_) {
// these are all-EEG modes
case 0: nbeeg_ = 256; nbexg_ = 0; nbaux_ = 0; nbaib_ = 0; nbtrig_ = 1; nbsync_ = 1; nbchan_ = 258; break;
case 1: nbeeg_ = 128; nbexg_ = 0; nbaux_ = 0; nbaib_ = 0; nbtrig_ = 1; nbsync_ = 1; nbchan_ = 130; break;
case 2: nbeeg_ = 64; nbexg_ = 0; nbaux_ = 0; nbaib_ = 0; nbtrig_ = 1; nbsync_ = 1; nbchan_ = 66; break;
case 3: nbeeg_ = 32; nbexg_ = 0; nbaux_ = 0; nbaib_ = 0; nbtrig_ = 1; nbsync_ = 1; nbchan_ = 34; break;
// in these modes there are are 8 EXGs and 16 aux channels
case 4: nbeeg_ = 232; nbexg_ = 8; nbaux_ = 16; nbaib_ = 0; nbtrig_ = 1; nbsync_ = 1; nbchan_ = 258; break;
case 5: nbeeg_ = 104; nbexg_ = 8; nbaux_ = 16; nbaib_ = 0; nbtrig_ = 1; nbsync_ = 1; nbchan_ = 130; break;
case 6: nbeeg_ = 40; nbexg_ = 8; nbaux_ = 16; nbaib_ = 0; nbtrig_ = 1; nbsync_ = 1; nbchan_ = 66; break;
case 7: nbeeg_ = 8; nbexg_ = 8; nbaux_ = 16; nbaib_ = 0; nbtrig_ = 1; nbsync_ = 1; nbchan_ = 34; break;
// in spd mode 8 there are 32 AIB channels from an Analog Input Box (AIB) multiplexed in (EXGs are off)
case 8: nbeeg_ = 256; nbexg_ = 0; nbaux_ = 0; nbaib_ = 32; nbtrig_ = 1; nbsync_ = 1; nbchan_ = 290; break;
}
}
std::cout << " channels: " << nbchan_ << "(" << nbsync_ << "xSync, " << nbtrig_ << "xTrigger, " << nbeeg_ << "xEEG, " << nbexg_ << "xExG, " << nbaux_ << "xAUX, " << nbaib_ << "xAIB)" << std::endl;
// check for additional problematic conditions
battery_low_ = (status & (1<<22)) != 0;
if (battery_low_)
std::cout << " battery: low" << std::endl;
else
std::cout << " battery: good" << std::endl;
if (battery_low_)
std::cout << "The BioSemi battery is low; amplifier will shut down within 30-60 minutes." << std::endl;
// compute a proper buffer size (needs to be a multiple of 512, a multiple of nbchan, as well as ~32MB in size)
std::cout << "Reallocating optimized ring buffer..." << std::endl;
// === shutdown current coonnection ===
// shutdown current connection
std::cout << "Sending the enable message again..." << std::endl;
if (!USB_WRITE(hConn_, &msg_enable[0])) {
CLOSE_DRIVER_ASYNC(hConn_);
throw std::runtime_error("Error while disabling the handshake.");
}
std::cout << "Closing the driver..." << std::endl;
if (!CLOSE_DRIVER_ASYNC(hConn_)) {
throw std::runtime_error("Error while disconnecting.");
}
// reset to a new ring buffer
std::cout << "Freeing the ring buffer..." << std::endl;
delete ring_buffer_;
// === reinitialize acquisition ===
std::cout << "Allocating a new ring buffer..." << std::endl;
ring_buffer_ = new boost::uint32_t[buffer_samples*nbchan_];
if (!ring_buffer_) {
throw std::runtime_error("Could not reallocate ring buffer (out of memory?).");
}
std::cout << "Zeroing the ring buffer..." << std::endl;
memset(ring_buffer_,0,buffer_samples*4*nbchan_);
// reconnect to driver
std::cout << "Opening the driver..." << std::endl;
hConn_ = OPEN_DRIVER_ASYNC();
if (!hConn_) {
throw std::runtime_error("Could not open connection to BioSemi driver.");
}
// reinitialize USB2 interface
std::cout << "Reinitializing the USB interface..." << std::endl;
if (!USB_WRITE(hConn_,&msg_enable[0])) {
CLOSE_DRIVER_ASYNC(hConn_);
throw std::runtime_error("Could not initialize BioSemi USB2 interface.");
}
// begin acquisition
std::cout << "Starting data acquisition..." << std::endl;
READ_MULTIPLE_SWEEPS(hConn_,(char*)ring_buffer_,buffer_samples*4*nbchan_);
// enable handshake
std::cout << "Enabling handshake..." << std::endl;
if (!USB_WRITE(hConn_, (char*) msg_handshake)) {
CLOSE_DRIVER_ASYNC(hConn_);
delete ring_buffer_;
throw std::runtime_error("Could not reenable handshake with BioSemi USB2 interface.");
}
// === check for correctness of new data ===
// make sure that we can read the buffer pointer
std::cout << "Attempt to read buffer pointer..." << std::endl;
if (!READ_POINTER(hConn_,&start_idx)) {
USB_WRITE(hConn_, &msg_enable[0]);
CLOSE_DRIVER_ASYNC(hConn_);
delete ring_buffer_;
throw std::runtime_error("Can not obtain ring buffer pointer from BioSemi driver.");
}
std::cout << "Verifying channel format..." << std::endl;
start_time = clock();
while (1) {
// error checks
if (!READ_POINTER(hConn_, &cur_idx)) {
USB_WRITE(hConn_, &msg_enable[0]);
CLOSE_DRIVER_ASYNC(hConn_);
delete ring_buffer_;
throw std::runtime_error("Ring buffer handshake with BioSemi driver failed unexpectedly.");
}
if ( ((double)(clock() - start_time))/CLOCKS_PER_SEC > max_waiting_time) {
USB_WRITE(hConn_, &msg_enable[0]);
CLOSE_DRIVER_ASYNC(hConn_);
delete ring_buffer_;
if (cur_idx - start_idx < 8)
throw std::runtime_error("BioSemi driver does not transmit data. Is the box turned on?");
else
throw std::runtime_error("Did not get a sync signal from BioSemi driver. Is the battery charged?");
}
if ((cur_idx - start_idx >= 4*nbchan_) && (ring_buffer_[0] == 0xFFFFFF00))
// got a sync signal on the first index
start_idx = 0;
if ((cur_idx - start_idx >= 4*nbchan_) && (ring_buffer_[start_idx/4] == 0xFFFFFF00)) {
if (ring_buffer_[start_idx/4+nbchan_] != 0xFFFFFF00) {
USB_WRITE(hConn_, &msg_enable[0]);
CLOSE_DRIVER_ASYNC(hConn_);
delete ring_buffer_;
throw std::runtime_error("Sync signal did not show up at the expected position.");
} else {
std::cout << "Channel format is correct..." << std::endl;
// all correct
break;
}
}
}
// === derive channel labels ===
channel_labels_.clear();
channel_types_.clear();
for (int k=1;k<=nbsync_;k++) {
channel_labels_.push_back(std::string("Sync") += boost::lexical_cast<std::string>(k));
channel_types_.push_back("Sync");
}
for (int k=1;k<=nbtrig_;k++) {
channel_labels_.push_back(std::string("Trig") += boost::lexical_cast<std::string>(k));
channel_types_.push_back("Trigger");
}
if (multibox) {
// multi-box setup
for (int b=0;b<=3;b++) {
const char *boxid[] = {"_Box1","_Box2","_Box3","_Box4"};
for (int k=1;k<=nbeeg_/4;k++) {
std::string tmp = "A"; tmp[0] = 'A'+(k-1)/32;
channel_labels_.push_back((std::string(tmp) += boost::lexical_cast<std::string>(1+(k-1)%32)) += boxid[b]);
channel_types_.push_back("EEG");
}
for (int k=1;k<=nbexg_/4;k++) {
channel_labels_.push_back((std::string("EX") += boost::lexical_cast<std::string>(k)) += boxid[b]);
channel_types_.push_back("EXG");
}
for (int k=1;k<=nbaux_/4;k++) {
channel_labels_.push_back((std::string("AUX") += boost::lexical_cast<std::string>(k)) += boxid[b]);
channel_types_.push_back("AUX");
}
for (int k=1;k<=nbaib_/4;k++) {
channel_labels_.push_back((std::string("AIB") += boost::lexical_cast<std::string>(k)) += boxid[b]);
channel_types_.push_back("Analog");
}
}
} else {
// regular setup
for (int k=1;k<=nbeeg_;k++) {
std::string tmp = "A"; tmp[0] = 'A'+(k-1)/32;
channel_labels_.push_back(std::string(tmp) += boost::lexical_cast<std::string>(1+(k-1)%32));
channel_types_.push_back("EEG");
}
for (int k=1;k<=nbexg_;k++) {
channel_labels_.push_back(std::string("EX") += boost::lexical_cast<std::string>(k));
channel_types_.push_back("EXG");
}
for (int k=1;k<=nbaux_;k++) {
channel_labels_.push_back(std::string("AUX") += boost::lexical_cast<std::string>(k));
channel_types_.push_back("AUX");
}
for (int k=1;k<=nbaib_;k++) {
channel_labels_.push_back(std::string("AIB") += boost::lexical_cast<std::string>(k));
channel_types_.push_back("Analog");
}
}
last_idx_ = 0;
}
biosemi_io::~biosemi_io() {
/* close driver connection */
if (!USB_WRITE(hConn_,&msg_enable[0]))
std::cout << "The handshake while shutting down the BioSemi driver gave an error." << std::endl;
if (!CLOSE_DRIVER_ASYNC(hConn_))
std::cout << "Closing the BioSemi driver gave an error." << std::endl;
// free the ring buffer
delete ring_buffer_;
}
void biosemi_io::get_chunk(chunk_t &result) {
// get current buffer offset
intptr_t cur_idx;
if (!READ_POINTER(hConn_, &cur_idx))
throw std::runtime_error("Reading the updated buffer pointer gave an error.");
cur_idx = cur_idx/4;
// forget about incomplete sample data
cur_idx = cur_idx - cur_idx % nbchan_;
if (cur_idx < 0)
cur_idx = cur_idx + buffer_samples*nbchan_;
result.clear();
if (cur_idx != last_idx_) {
if (cur_idx > last_idx_) {
// sequential read: copy intermediate part between offsets
int chunklen = (cur_idx - last_idx_) / nbchan_;
result.resize(chunklen);
for (int k=0;k<chunklen;k++) {
result[k].resize(nbchan_);
memcpy(&result[k][0], &ring_buffer_[last_idx_ + k*nbchan_], nbchan_*4);
}
} else {
// wrap-around read: concatenate two parts
int chunklen = (cur_idx + buffer_samples*nbchan_ - last_idx_) / nbchan_;
result.resize(chunklen);
int first_section = buffer_samples - last_idx_/nbchan_;
for (int k=0;k<first_section;k++) {
result[k].resize(nbchan_);
memcpy(&result[k][0], &ring_buffer_[last_idx_ + k*nbchan_], nbchan_*4);
}
int second_section = chunklen - first_section;
for (int k=0;k<second_section;k++) {
result[first_section+k].resize(nbchan_);
memcpy(&result[first_section+k][0], &ring_buffer_[k*nbchan_], nbchan_*4);
}
}
// update status flags
boost::uint32_t status = ring_buffer_[cur_idx] >> 8;
battery_low_ = (status & (1<<22)) != 0;
}
// update last buffer pointer
last_idx_ = cur_idx;
}