-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathTechnaidIMU.cpp
More file actions
415 lines (332 loc) · 14 KB
/
TechnaidIMU.cpp
File metadata and controls
415 lines (332 loc) · 14 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
#include "TechnaidIMU.h"
TechnaidIMU::TechnaidIMU(IMUParameters imuParameters)
: canChannel_(imuParameters.canChannel),
serialNo_(imuParameters.serialNo),
networkId_(imuParameters.networkId),
location_(imuParameters.location)
{
isInitialized_ = false;
hasMode_ = false;
}
bool TechnaidIMU::initialize() {
// Read parameters
if(!validateParameters()){
spdlog::error("[TechnaidIMU::initialize]: Parameters can't be read successfully!");
return false;
}
// CAN configuration
if(!canConfiguration()){
spdlog::error("[TechnaidIMU::initialize]: Error in CAN configuration");
return false;
}
// Communication check
if(!checkCommunication()){
spdlog::error("[TechnaidIMU::initialize]: Error in IMU communication");
return false;
}
// Set output mode of the IMUs
for(int index = 0; index<numberOfIMUs_; index++){
if(location_[index] == 'b'){
outputMode_[index].name = "quat_gyro";
outputMode_[index].dataSize = SIZE_QUATERNION_GYR;
outputMode_[index].code = START_QUATERNION_GYR_PHYSICAL_DATA_CAPTURE;
dataSize_[index] = SIZE_QUATERNION_GYR;
} else if(location_[index] == 'c') {
outputMode_[index].name = "acc";
outputMode_[index].dataSize = SIZE_ACCELERATION;
outputMode_[index].code = START_ACCELEROMETER_PHYSICAL_DATA_CAPTURE;
dataSize_[index] = SIZE_ACCELERATION;
}
}
sleep(1);
if(!startUpdateThread()){
spdlog::error("[TechnaidIMU::initialize]: Error during creating the update thread!");
return false;
}
spdlog::info("[TechnaidIMU::initialize]: Successfully initialized");
isInitialized_ = true;
return true;
}
bool TechnaidIMU::setOutputMode(int index, IMUOutputMode imuOutputMode) {
if(!isInitialized_){
spdlog::error("[TechnaidIMU::setOutputMode]: Not initialized yet!");
return false;
}
pthread_cancel(updateThread);
struct can_frame canFrame;
// struct timeval timeout = {1, }; // 10 ms timout
// fd_set readSet;
// FD_ZERO(&readSet);
// FD_SET(canSocket_, &readSet);
//
// while (select((canSocket_ + 1), &readSet, NULL, NULL, &timeout) && !exitSignalReceived) {
// read(canSocket_, &canFrame, sizeof(struct can_frame)); // read anything at the buffer
// }
// stop capture
canFrame.can_id = networkId_[index];
canFrame.can_dlc = 1;
canFrame.data[0] = STOP_DATA_CAPTURE;
write(canSocket_, &canFrame, sizeof(struct can_frame));
sleep(1);
switch (imuOutputMode) {
case ACCELERATION:
outputMode_[index].name = "acc";
outputMode_[index].dataSize = SIZE_ACCELERATION;
outputMode_[index].code = START_ACCELEROMETER_PHYSICAL_DATA_CAPTURE;
dataSize_[index] = SIZE_ACCELERATION;
break;
case QUATERNION:
outputMode_[index].name = "quat";
outputMode_[index].dataSize = SIZE_QUATERNION;
outputMode_[index].code = START_QUATERNION_DATA_CAPTURE;
dataSize_[index] = SIZE_QUATERNION;
break;
case QUATERNION_GYRO:
outputMode_[index].name = "quat_gyro";
outputMode_[index].dataSize = SIZE_QUATERNION_GYR;
outputMode_[index].code = START_QUATERNION_GYR_PHYSICAL_DATA_CAPTURE;
dataSize_[index] = SIZE_QUATERNION_GYR;
break;
default:
spdlog::error("Unhandled output mode!");
}
canFrame.can_id = networkId_[index];
canFrame.can_dlc = 1;
canFrame.data[0] = outputMode_[index].code;
int writeByte = write(canSocket_, &canFrame, sizeof(struct can_frame));
sleep(0.5);
bool success = (writeByte == sizeof(struct can_frame));
if(success) {
if(imuOutputMode == IMUOutputMode::QUATERNION){
spdlog::warn("Calibration started. Do not move IMUs for 6 seconds");
sleep(6);
} else if(imuOutputMode == IMUOutputMode::ACCELERATION) sleep(1);
spdlog::info("[TechnaidIMU::setOutputMode]: Mode is changed to {} for imu no: {}",outputMode_[index].name, index);
hasMode_ = true;
startUpdateThread();
sleep(1);
return true;
} else {
spdlog::error("[TechnaidIMU::setOutputMode]: Error while changing the mode to {} for imu no: {} !", outputMode_[index].name, index);
return false;
}
}
void* TechnaidIMU::update(void) {
std::chrono::steady_clock::time_point time0;
while(!exitSignalReceived) {
if (!isInitialized_) continue; // if not initialized, immediately return
// Pooling
struct can_frame canFrame;
canFrame.can_id = BROADCAST_ID;
canFrame.can_dlc = 0;
write(canSocket_, &canFrame, sizeof(struct can_frame));
int maxSize = 60;
//specify the amount of data to read for each imu
char data_bytes_multi[maxSize][numberOfIMUs_];
int count[numberOfIMUs_]; // count of the number of bytes that have been read for each imu
for (int i = 0; i < numberOfIMUs_; i++) count[i] = 0; // setting the elements to zero
struct timeval timeout = {0, 10000}; // 10 ms timout
fd_set readSet;
FD_ZERO(&readSet);
FD_SET(canSocket_, &readSet);
bool exit = false;
while (!exit && select((canSocket_ + 1), &readSet, NULL, NULL, &timeout) && !exitSignalReceived) {
// stays in the loop until all data is received or timeout value is reached
read(canSocket_, &canFrame, sizeof(struct can_frame));
exit = true;
for (int i = 0; i < numberOfIMUs_; i++) {
if(dataSize_[i] == 0) continue; // no output is set for this IMU. continue
if (canFrame.can_id == networkId_[i] + 16) {
for (int j = 0; j < canFrame.can_dlc; j++) {
data_bytes_multi[count[i]][i] = canFrame.data[j];
count[i]++;
}
}
exit = exit && (count[i] == dataSize_[i]); // if data from all sensors are received, this becomes true
}
}
for (int i = 0; i < numberOfIMUs_; i++) {
if(dataSize_[i] == 0) continue; // no output is set for this IMU. continue
if (count[i] == dataSize_[i]) {
// get the i th column
char data_bytes[dataSize_[i]];
for (int j = 0; j < dataSize_[i]; j++) {
data_bytes[j] = data_bytes_multi[j][i];
}
float *data_float;
data_float = (float *) data_bytes;
if(outputMode_[i].name == "acc"){
acceleration_(0, i) = data_float[0]; // acc x
acceleration_(1, i) = data_float[1]; // acc y
acceleration_(2, i) = data_float[2]; // acc z
} else if (outputMode_[i].name == "quat"){
quaternion_(0, i) = data_float[0]; // quat x
quaternion_(1, i) = data_float[1]; // quat y
quaternion_(2, i) = data_float[2]; // quat z
quaternion_(3, i) = data_float[3]; // quat w
} else if (outputMode_[i].name == "quat_gyro"){
quaternion_(0, i) = data_float[0]; // quat x
quaternion_(1, i) = data_float[1]; // quat y
quaternion_(2, i) = data_float[2]; // quat z
quaternion_(3, i) = data_float[3]; // quat w
angularVelocity_(0, i) = data_float[4]; //ang vel x
angularVelocity_(1, i) = data_float[5]; //ang vel y
angularVelocity_(2, i) = data_float[6]; //ang vel z
}
} else {
spdlog::warn("[TechnaidIMU::update()]: Data was not successfully read for IMU no: {}!", serialNo_[i]);
if (outputMode_[i].name == "acc") {
acceleration_.col(i) = Eigen::MatrixXd::Zero(3,1);
} else if (outputMode_[i].name == "quat") {
quaternion_.col(i) = 0.5*Eigen::MatrixXd::Ones(4,1);
} else if (outputMode_[i].name == "quat_gyro") {
angularVelocity_.col(i) = Eigen::MatrixXd::Zero(3,1);
}
}
}
}
// double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - time0).count()/1000.0;
// std::cout<<time_ms<<std::endl;
}
bool TechnaidIMU::validateParameters() {
numberOfIMUs_ = serialNo_.size();
if(networkId_.size()!=numberOfIMUs_ || location_.size()!=numberOfIMUs_){
spdlog::error("[TechnaidIMU:arameters()]: Size of the parameters are not same!");
return false;
}
for(int i = 0; i<numberOfIMUs_; i++){
dataSize_.push_back(0); // initializing all elements of dataSize to 0.
IMUOutputModeStruct defaultOutputModeStruct;
outputMode_.push_back(defaultOutputModeStruct);
}
acceleration_ = Eigen::MatrixXd::Zero(3, numberOfIMUs_);
quaternion_ = Eigen::MatrixXd::Zero(4, numberOfIMUs_);
angularVelocity_ = Eigen::MatrixXd::Zero(3, numberOfIMUs_);
return true;
}
bool TechnaidIMU::canConfiguration() {
// CAN initialization
canSocket_ = socket(PF_CAN, SOCK_RAW, CAN_RAW);
struct sockaddr_can addr;
struct ifreq ifr;
strcpy(ifr.ifr_name, canChannel_.c_str());
int ioControl = ioctl(canSocket_, SIOCGIFINDEX, &ifr);
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
bind(canSocket_, (struct sockaddr *)&addr, sizeof(addr));
return (ioControl >= 0);
}
bool TechnaidIMU::checkCommunication() {
// send check communication command
struct can_frame canFrame;
canFrame.can_id = BROADCAST_ID;
canFrame.can_dlc = 1;
canFrame.data[0] = CHECK_COMMUNICATION;
write(canSocket_, &canFrame, sizeof(struct can_frame));
sleep(0.1);
struct timeval timeout = {1, 0};
fd_set readSet;
FD_ZERO(&readSet);
FD_SET(canSocket_, &readSet);
std::vector<int> receivedIds;
// check the ids of the IMUs on the CAN network
while(select((canSocket_ + 1), &readSet, NULL, NULL, &timeout) && !exitSignalReceived) {
// stays in the loop as long as there is something to read
std::cout<<" IN READ !!!"<<std::endl;
read(canSocket_, &canFrame, sizeof(struct can_frame));
std::cout<<" ID: "<<canFrame.can_id<<std::endl;
receivedIds.push_back(canFrame.can_id);
}
bool alreadyConnected = false;
if(receivedIds.size() == 0){
// check communication command doesnt return anything if data capture already started.
// Check if data capture is started
struct can_frame canFrame;
canFrame.can_id = BROADCAST_ID;
canFrame.can_dlc = 0;
write(canSocket_, &canFrame, sizeof(struct can_frame));
sleep(0.1);
struct timeval timeout = {1, 0};
fd_set readSet;
FD_ZERO(&readSet);
FD_SET(canSocket_, &readSet);
// check the ids of the IMUs on the CAN network
while(select((canSocket_ + 1), &readSet, NULL, NULL, &timeout) && !exitSignalReceived) {
// stays in the loop as long as there is something to read
std::cout<<" IN READ !!!"<<std::endl;
read(canSocket_, &canFrame, sizeof(struct can_frame));
std::cout<<" ID: "<<canFrame.can_id<<std::endl;
receivedIds.push_back(canFrame.can_id);
}
// deleting the same ids
std::sort(receivedIds.begin(), receivedIds.end());
auto last = std::unique(receivedIds.begin(), receivedIds.end());
receivedIds.erase(last, receivedIds.end());
if(receivedIds.size() > 0) alreadyConnected = true;
}
// compare the number of IMUs in the network with the size of the parameters
if(receivedIds.size() != numberOfIMUs_){
spdlog::error("[TechnaidIMU::checkCommunication()]: {} sets of parameters are given but there are {} IMUs on {}!",
numberOfIMUs_, receivedIds.size(), canChannel_);
return false;
}
for(int id: receivedIds){
if(std::count(networkId_.begin(), networkId_.end(), id-16) == 0){
spdlog::error("[TechnaidIMU::checkCommunication()]: parameters of network id: {} could not be found!", (id-16));
return false;
} else if (std::count(networkId_.begin(), networkId_.end(), id-16) > 1){
spdlog::error("[TechnaidIMU::checkCommunication()]: parameters of network id: {} is given more than once!", (id-16));
return false;
}
}
return true;
}
void * TechnaidIMU::updateHelper(void *This) {
((TechnaidIMU *)This)->update();
return NULL;
}
bool TechnaidIMU::startUpdateThread() {
return (pthread_create(&updateThread, NULL, &TechnaidIMU::updateHelper, this) == 0);
}
void TechnaidIMU::exit() {
for(int i = 0; i<numberOfIMUs_; i++){
struct can_frame canFrame;
canFrame.can_id = networkId_[i];
canFrame.can_dlc = 1;
canFrame.data[0] = STOP_DATA_CAPTURE;
write(canSocket_, &canFrame, sizeof(struct can_frame));
spdlog::info("Data capture ended on IMU with serial no {}.", serialNo_[i]);
}
close(canSocket_);
}
Eigen::MatrixXd& TechnaidIMU::getAcceleration() {
return acceleration_;
}
Eigen::MatrixXd & TechnaidIMU::getQuaternion() {
return quaternion_;
}
Eigen::MatrixXd & TechnaidIMU::getAngularVelocity() {
return angularVelocity_;
}
int& TechnaidIMU::getNumberOfIMUs_() {
return numberOfIMUs_;
}
IMUOutputModeStruct & TechnaidIMU::getOutputMode_(int index) {
return outputMode_[index];
}
void TechnaidIMU::signalHandler(int signum) {
exitSignalReceived = 1;
std::raise(SIGTERM); // clean exit
}
int TechnaidIMU::getIndex(std::vector<int> vec, int element) {
auto it = find(vec.begin(), vec.end(), element);
int index;
// If element was found
if (it != vec.end()) {
index = it - vec.begin();
} else {
index = -1;
spdlog::error("[TechnaidIMU::getIndex]: Index not found");
}
return index;
}