forked from mcsltd/NB2CppDemo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNB2CppDemo.cpp
More file actions
358 lines (311 loc) · 13.1 KB
/
NB2CppDemo.cpp
File metadata and controls
358 lines (311 loc) · 13.1 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
#include <nb2mcs/nb2mcs.h>
#include <iostream>
#include <iomanip>
#include <string>
#include <future>
// command line arguments processing
// settings passed by command line arguments
struct ProgramSettings {
enum ProgramMode { Eeg, Impedance, Status, Help };
ProgramSettings() :
Mode(Eeg), DataRate(Hz125), InputRange(Mv150), EnabledChannels(0xFFFF) {}
ProgramMode Mode;
Nb2Rate DataRate;
Nb2Range InputRange;
uint16_t EnabledChannels;
};
ProgramSettings::ProgramMode modeArg(const std::string& mode) {
if (mode == "eeg") return ProgramSettings::ProgramMode::Eeg;
if (mode == "impedance") return ProgramSettings::ProgramMode::Impedance;
if (mode == "status") return ProgramSettings::ProgramMode::Status;
if (mode == "help" || mode == "--help" || mode == "=h")
return ProgramSettings::ProgramMode::Help;
throw std::exception(("Unknown program mode: " + mode).c_str());
}
Nb2Rate dataRateArg(const std::string& rate) {
if (rate == "125") return Hz125;
if (rate == "250") return Hz250;
if (rate == "500") return Hz500;
if (rate == "1000") return Hz1000;
throw std::exception(("Unknown rate: " + rate).c_str());
}
Nb2Range inputRangeArg(const std::string& range) {
if (range == "150") return Mv150;
if (range == "300") return Mv300;
throw std::exception(("Unknown range: " + range).c_str());
}
uint16_t enabledChannelsArg(const std::string& channels) {
uint16_t enabled = 0;
std::string::size_type offset = 0;
std::string::size_type pos = std::string(channels).find(',');
while (offset != std::string::npos) {
enabled |= 1 << (std::stoi(channels.substr(offset, pos - offset)) - 1);
offset = pos < std::string::npos ? pos + 1 : pos;
pos = std::string(channels).find(',', offset);
}
return enabled;
}
void showUsage() {
std::cout << "NB2CppDemo - demo program for working with the NB2-EEG16 device" << std::endl;
std::cout << "Medical Computer Systems Ltd., 2022" << std::endl << std::endl;
std::cout << "Usage: " << std::endl;
std::cout << "NB2CppDemo.exe <mode> <data-rate> <input-range> <chs-enabled>" << std::endl;
std::cout << " <mode> program working mode: eeg (default), impedance, status or help" << std::endl;
std::cout << " <data-rate> eeg sampling rate in herz: 125 (default), 250, 500 or 1000" << std::endl;
std::cout << " <input-range> adc input range in mV: 150 (default) or 300" << std::endl;
std::cout << " <chs-enabled> comma-separated numbers of channels that ase used for eeg/impedance asquisition;" << std::endl;
std::cout << " all channels are enabled by default; space in enumeration are not allowed" << std::endl;
std::cout << "All arguments are optional (see default values)." << std::endl << std::endl;
}
void showPorgramSettings(int argc, const char* argv[]) {
std::cout << "Device configuration: data rate " << (argc > 2 ? argv[2] : "125") << " Hz, " <<
"input range " << (argc > 3 ? argv[3] : "150") << " mV, " <<
"enabled channels " << (argc > 4 ? argv[4] : "all") << std::endl;
}
ProgramSettings processCommandLineArguments(int argc, const char* argv[]) {
try {
ProgramSettings sets;
if (argc > 1) sets.Mode = modeArg(argv[1]);
if (argc > 2) sets.DataRate = dataRateArg(argv[2]);
if (argc > 3) sets.InputRange = inputRangeArg(argv[3]);
if (argc > 4) sets.EnabledChannels = enabledChannelsArg(argv[4]);
return sets;
}
catch (const std::exception& ex) {
std::cerr << "Bad command line arguments: " << ex.what() << std::endl;
showUsage();
std::exit(-1);
}
}
// return value check for all nb2 functions
#define CHECK(x) check((#x), (x))
int check(const std::string& function, int ret) {
if(ret < 0) {
switch(ret) {
case Nb2Error::ErrId: throw std::exception(("Invalid device id: " + function).c_str());
case Nb2Error::ErrParam: throw std::exception(("Invalid function parameters :" + function).c_str());
case Nb2Error::ErrFail: throw std::exception(("Call function fail :" + function).c_str());
default: throw std::exception(("Unidentified error " + std::to_string(ret) + ": " + function).c_str());
}
}
return ret;
}
// nb2GetData and nb2GetEvents functions return the
// count of bytes copied to buffer or error code,
// transform into the number of EEG or event samples
int itemCount(int returnValue, size_t itemSize) {
if(returnValue > 0) {
if(returnValue % itemSize != 0) {
throw std::exception("Bad data/event size in bytes");
}
return int (returnValue / itemSize);
}
return returnValue;
}
// peak-to-peak amplitude of signal in Volts over a period of time
float signalAmplitude(const t_nb2Property& prop, t_nb2Data* data, size_t size, size_t channel) {
if(size == 0) {
return 0.f;
}
int min = std::numeric_limits<int>::max();
int max = std::numeric_limits<int>::min();
for (size_t i = 0; i < size; i++) {
int value = data[i].Channel[channel];
if (max < value) {
max = value;
}
if (min > value) {
min = value;
}
}
return ((float)max - min) * prop.Resolution;
}
// number of lost samples per time period
size_t lostSamples(t_nb2Data* data, size_t size) {
static size_t expectedCounter = 0;
size_t lostSamples = 0;
for(size_t i = 0; i < size; i++) {
if(data[i].Counter == 0) { // counter reset
expectedCounter = 0;
}
lostSamples += data[i].Counter - expectedCounter;
expectedCounter = data[i].Counter + 1;
}
return lostSamples;
}
void searchDevice() {
std::cout << "Search devices ..." << std::endl;
int count = 0;
while(count == 0) {
// returns the number of devices, may vary from call to call,
// devices are not found immediately (up to a few seconds)
count = CHECK(nb2GetCount());
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
std::string versionPrettyStringFirmware(uint64_t version) {
return std::to_string((version >> 48) % 0x10000) + '.' +
std::to_string((version >> 32) % 0x10000) + '.' +
std::to_string(version % 0x100000000);
}
std::string versionPrettyStringDll(uint64_t version) {
return std::to_string((version >> 48) % 0x10000) + '.' +
std::to_string((version >> 32) % 0x10000) + '.' +
std::to_string((version >> 16) % 0x10000) + '.' +
std::to_string(version % 0x10000);
}
std::string datePrettyString(const t_nb2Date& date) {
return std::to_string(date.Day) + '.' + std::to_string(date.Month) + '.' + std::to_string(date.Year);
}
void showInfoAboutDevice(int id) {
// software versions
t_nb2Version version; CHECK(nb2GetVersion(id, &version));
std::cout << "Version: firmware " << versionPrettyStringFirmware(version.Firmware)
<< " dll " << versionPrettyStringDll(version.Dll) << std::endl;
// device production info
t_nb2Information info; CHECK(nb2GetInformation(id, &info));
std::cout << "Serial number: " << info.SerialNumber << std::endl;
std::cout << "Production date: " << datePrettyString(info.ProductionDate) << std::endl;
}
void configureDevice(int id, const ProgramSettings& settings) {
// EEG acquisition settings
t_nb2DataSettings dsets;
dsets.DataRate = settings.DataRate; // sampling rate
dsets.EnabledChannels = settings.EnabledChannels; // enabled channels bitset, all channels enabled
dsets.InputRange = settings.InputRange; // ADC range
CHECK(nb2SetDataSettings(id, &dsets));
// event settings
t_nb2EventSettings esets;
esets.ActivityThreshold = 1; // accelerometer sensitivity, from 0 to 2, use 1 by default
esets.EnabledEvents = 0x003F; // detected event types bitset, all events will be detected
CHECK(nb2SetEventSettings(id, &esets));
// mode - EEG or impedance acquisition
t_nb2Mode mode;
mode.Mode = settings.Mode == Nb2Mode::Impedance ? Nb2Mode::Impedance : Nb2Mode::Data;
CHECK(nb2SetMode(id, &mode));
}
std::string eventTypePrettyString(Nb2EventType etype) {
switch(etype) {
case EvButton: return "button_press";
case EvActivity: return "activity";
case EvFreeFall: return "free_fall";
case EvOrientation: return "orientation";
case EvStart: return "start";
case EvCharge: return "charge";
default: return "unknown_" + std::to_string(etype);
}
}
void processDataAndEvents(int id) {
// nb2GetProperty gets info about physical characteristics of channels
t_nb2Property prop; CHECK(nb2GetProperty(id, &prop));
t_nb2Data data[2000]; // EEG data buffer, 2 second for maximal data rate
t_nb2Event events[100]; // event buffer for short time period
std::cout.precision(3);
// EEG acquisition while user doesn't press q and enter, read data and events one time per second
const std::future<void> future = std::async([] { while (std::cin.get() != 'q'); });
while(future.wait_for(std::chrono::seconds(1)) != std::future_status::ready) {
// EEG samples processing, pass buffer size in bytes
const size_t sampleCount = CHECK(itemCount(nb2GetData(id, data, sizeof(data)), sizeof(*data)));
std::cout << "EEG p-p (uV):";
for(size_t channel = 0; channel < 16; ++channel) {
std::cout << std::fixed << std::setw(6) << std::setprecision(3)
<< round(signalAmplitude(prop, data, sampleCount, channel) * 1e6);
}
// lost samples processing
if(const size_t lost = lostSamples(data, sampleCount)) {
std::cout << " lost " << lost << "samples";
}
std::cout << std::endl;
// event processing, pass buffer size in bytes
const size_t eventCount = CHECK(itemCount(nb2GetEvent(id, events, sizeof(events)), sizeof(*events)));
for(size_t i = 0; i < eventCount; ++i) {
std::cout << "Event " << events[i].Number << " counter " << events[i].Counter
<< " type " << eventTypePrettyString(Nb2EventType(events[i].Type))
<< " value " << std::to_string(events[i].Value) << std::endl;
}
}
}
void showTimeString(std::chrono::seconds::rep time) {
std::cout << std::setfill('0') << std::setw(2) << time / 3600 << ":";
std::cout << std::setfill('0') << std::setw(2) << time / 60 % 60 << ":";
std::cout << std::setfill('0') << std::setw(2) << time % 60;
std::cout << std::setfill(' ');
}
void processImpedances(int id) {
t_nb2Impedance impedance;
// impedance acquisition while user doesn't press q and enter, read data one time per second
const std::future<void> future = std::async([] { while(std::cin.get() != 'q'); });
while(future.wait_for(std::chrono::seconds(1)) != std::future_status::ready) {
// impedance value in Ohm for all channels, MAX_UINT - channel not connected
CHECK(nb2GetImpedance(id, &impedance));
std::cout << "Impedances (kOhm):";
for(size_t channel = 0; channel < 16; ++channel) {
std::cout << std::setw(6) << std::setprecision(1) << impedance.Channel[channel] * 1e-3;
}
std::cout << std::endl;
}
}
void processStatus(int id) {
t_nb2DataStatus sdata;
t_nb2BatteryProperties sbattery;
t_nb2UsageStats susage;
// status registration while user doesn't press q and enter, read data one time per minute
bool first = true;
const auto start = std::chrono::steady_clock::now();
std::future<void> future = std::async([] { while (std::cin.get() != 'q'); });
while (first || future.wait_for(std::chrono::seconds(60)) != std::future_status::ready) {
CHECK(nb2GetDataStatus(id, &sdata));
CHECK(nb2GetBattery(id, &sbattery));
CHECK(nb2GetUsageStats(id, &susage));
showTimeString(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - start).count());
std::cout << " battery " << std::fixed << std::setw(5) << std::setprecision(1) << sbattery.Level / 10.f
<< "%, ble utilization " << std::fixed << std::setw(5) << std::setprecision(1) << sdata.Utilization
<< "%, errors " << int(susage.ErrorsStats.ACC) << " ACC " << int(susage.ErrorsStats.ADC) << " ADC "
<< int(susage.ErrorsStats.CELL) << " CELL " << int(susage.ErrorsStats.RW) << " RW "
<< int(susage.ErrorsStats.SYS) << " SYS" << std::endl;
first = false;
}
}
int main(int argc, const char* argv[]) {
try {
ProgramSettings settings = processCommandLineArguments(argc, argv);
if (settings.Mode == ProgramSettings::Help) {
showUsage();
return 0;
}
showPorgramSettings(argc, argv);
// start device search, library resources initialization
CHECK(nb2ApiInit());
searchDevice();
// open device with number 0
std::cout << "Device 0 found, opening ..." << std::endl;
int id = CHECK(nb2GetId(0));
CHECK(nb2Open(id));
showInfoAboutDevice(id);
configureDevice(id, settings);
// EEG or impedance acquisition start
CHECK(nb2Start(id));
// EEG, events or impedances processing
if (settings.Mode == ProgramSettings::Impedance) processImpedances(id);
else if (settings.Mode == ProgramSettings::Eeg) processDataAndEvents(id);
else if (settings.Mode == ProgramSettings::Status) processStatus(id);
// EEG or impedance acquisition stop
CHECK(nb2Stop(id));
// manual power off device after 2 seconds
// (if not calling - automatic power off after 3 minutes)
CHECK(nb2PowerOff(id, 2));
// close device
CHECK(nb2Close(id));
// free library resources
CHECK(nb2ApiDone());
}
catch(const std::exception& ex) {
std::cerr << ex.what() << std::endl;
return -1;
}
catch(...) {
std::cerr << "Unknown error" << std::endl;
return -1;
}
return 0;
}