source: flair-src/trunk/lib/FlairCore/src/ui_com.cpp@ 133

Last change on this file since 133 was 133, checked in by Sanahuja Guillaume, 6 years ago

modif sterror

File size: 15.2 KB
Line 
1// %flair:license{
2// This file is part of the Flair framework distributed under the
3// CECILL-C License, Version 1.0.
4// %flair:license}
5// created: 2011/05/01
6// filename: ui_com.cpp
7//
8// author: Guillaume Sanahuja
9// Copyright Heudiasyc UMR UTC/CNRS 7253
10//
11// version: $Id: $
12//
13// purpose: classe permettant la lecture et l'ecriture sur socket UDT
14//
15//
16/*********************************************************************/
17
18#include "ui_com.h"
19#include <cstdlib>
20#include <string.h>
21#include <unistd.h>
22#include "Mutex.h"
23#include "SendData.h"
24#include "communication.h"
25#include "FrameworkManager.h"
26#include "zlib.h"
27#include <assert.h>
28#include "config.h"
29
30#ifdef __XENO__
31#include <pthread.h>
32#include <native/task.h>
33#include <native/task.h>
34#include <fcntl.h>
35#endif
36
37using std::string;
38using namespace flair::core;
39using namespace flair::gui;
40
41ui_com::ui_com(const Object *parent, UDTSOCKET sock)
42 : Thread(parent, "send", 2) {
43 // buffer envoi
44 send_buffer = (char *)malloc(3);
45 send_size = 3; // id(1)+period(2)
46
47 // mutex
48 send_mutex = NULL;
49 send_mutex = new Mutex(this, ObjectName());
50
51 socket_fd = sock;
52 connection_lost = false;
53
54#ifdef __XENO__
55 int status;
56 string tmp_name;
57
58 is_running = true;
59
60 // pipe
61 tmp_name = getFrameworkManager()->ObjectName() + "-" + ObjectName() + "-pipe";
62 // xenomai limitation
63 if (tmp_name.size() > 31)
64 Err("rt_pipe_create error (%s is too long)\n", tmp_name.c_str());
65#ifdef RT_PIPE_SIZE
66 status = rt_pipe_create(&pipe, tmp_name.c_str(), P_MINOR_AUTO, RT_PIPE_SIZE);
67#else
68 status = rt_pipe_create(&pipe, tmp_name.c_str(), P_MINOR_AUTO, 0);
69#endif
70
71 if (status != 0) {
72 char errorMsg[256];
73 Err("rt_pipe_create error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
74 // return -1;
75 }
76
77// start user side thread
78#ifdef NRT_STACK_SIZE
79 // Initialize thread creation attributes
80 pthread_attr_t attr;
81 if (pthread_attr_init(&attr) != 0) {
82 Err("pthread_attr_init error\n");
83 }
84
85 if (pthread_attr_setstacksize(&attr, NRT_STACK_SIZE) != 0) {
86 Err("pthread_attr_setstacksize error\n");
87 }
88
89 if (pthread_create(&thread, &attr, user_thread, (void *)this) < 0)
90#else // NRT_STACK_SIZE
91 if (pthread_create(&thread, NULL, user_thread, (void *)this) < 0)
92#endif // NRT_STACK_SIZE
93 {
94 Err("pthread_create error\n");
95 // return -1;
96 }
97#ifdef NRT_STACK_SIZE
98 if (pthread_attr_destroy(&attr) != 0) {
99 Err("pthread_attr_destroy error\n");
100 }
101#endif
102
103#endif //__XENO__
104 int timeout = 100;
105 if (UDT::setsockopt(socket_fd, 0, UDT_RCVTIMEO, &timeout, sizeof(int)) != 0)
106 Err("UDT::setsockopt error (UDT_RCVTIMEO)\n");
107
108 bool blocking = true;
109 if (UDT::setsockopt(socket_fd, 0, UDT_SNDSYN, &blocking, sizeof(bool)) != 0)
110 Err("UDT::setsockopt error (UDT_SNDSYN)\n");
111
112 if (UDT::setsockopt(socket_fd, 0, UDT_RCVSYN, &blocking, sizeof(bool)) != 0)
113 Err("UDT::setsockopt error (UDT_RCVSYN)\n");
114 //#endif //__XENO__
115
116 Start();
117}
118
119ui_com::~ui_com() {
120// printf("destruction ui_com\n");
121
122#ifdef __XENO__
123 is_running = false;
124
125 pthread_join(thread, NULL);
126
127 int status = rt_pipe_delete(&pipe);
128 if (status != 0) {
129 char errorMsg[256];
130 Err("rt_pipe_delete error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
131 }
132#endif
133
134 SafeStop();
135
136 if (IsSuspended() == true)
137 Resume();
138
139 Join();
140
141 if (send_buffer != NULL)
142 free(send_buffer);
143 send_buffer = NULL;
144
145 // printf("destruction ui_com ok\n");
146}
147
148void ui_com::Send(char *buf, ssize_t size) {
149 if (connection_lost == true)
150 return;
151
152 char *tosend = buf;
153 ssize_t nb_write;
154
155 if (buf[0] == XML_HEADER) {
156 // cut xml header
157 tosend = strstr(buf, "<root");
158 size -= tosend - buf;
159 }
160
161#ifdef __XENO__
162 nb_write = rt_pipe_write(&pipe, tosend, size, P_NORMAL);
163
164 if (nb_write < 0) {
165 char errorMsg[256];
166 Err("rt_pipe_write error (%s)\n", strerror_r(-nb_write, errorMsg, sizeof(errorMsg)));
167 } else if (nb_write != size) {
168 Err("rt_pipe_write error %i/%i\n", nb_write, size);
169 }
170#else //__XENO__
171
172#ifdef COMPRESS_FRAMES
173 bool sendItCompressed = false;
174 if (buf[0] == XML_HEADER) {
175 sendItCompressed = true;
176 }
177
178 if (sendItCompressed) {
179 char *out;
180 ssize_t out_size;
181 if (compressBuffer(tosend, size, &out, &out_size, 9) == Z_OK) {
182 size = out_size;
183 nb_write = UDT::sendmsg(socket_fd, out, size, -1, true);
184 free(out);
185 } else {
186 Warn("Compress error, sending it uncompressed\n");
187 sendItCompressed = false;
188 }
189 }
190
191 if (!sendItCompressed) {
192 nb_write = UDT::sendmsg(socket_fd, tosend, size, -1, true);
193 }
194
195#else // COMPRESS_FRAMES
196 nb_write = UDT::sendmsg(socket_fd, tosend, size, -1, true);
197#endif // COMPRESS_FRAMES
198 // Printf("write %i %i\n",nb_write,size);
199 if (nb_write < 0) {
200 Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
201 if (UDT::getlasterror().getErrorCode() == CUDTException::ECONNLOST ||
202 UDT::getlasterror().getErrorCode() == CUDTException::EINVSOCK) {
203 connection_lost = true;
204 }
205 } else if (nb_write != size) {
206 Err("%s, code %i (%ld/%ld)\n", UDT::getlasterror().getErrorMessage(),
207 UDT::getlasterror().getErrorCode(), nb_write, size);
208 }
209#endif //__XENO__
210}
211
212ssize_t ui_com::Receive(char *buf, ssize_t buf_size) {
213 ssize_t bytesRead = UDT::recvmsg(socket_fd, buf, buf_size);
214
215 if (bytesRead < 0) {
216 if (UDT::getlasterror().getErrorCode() == CUDTException::ECONNLOST) {
217 Err("UDT::recvmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
218 connection_lost = true;
219 }
220 }
221
222 return bytesRead;
223}
224
225void ui_com::Run(void) {
226 // check endianness
227 char header;
228 if (IsBigEndian()) {
229 header = DATAS_BIG_ENDIAN;
230 Printf("System is big endian\n");
231 } else {
232 header = DATAS_LITTLE_ENDIAN;
233 Printf("System is little endian\n");
234 }
235
236#ifdef __XENO__
237 WarnUponSwitches(true);
238 printf("\n"); // a revoir pourquoi??
239// sans ce printf, dans le simu_roll, le suspend ne fonctionne pas...
240#endif
241 // on attend d'avoir des choses à faire
242 Suspend();
243
244 while (!ToBeStopped()) {
245 size_t resume_id;
246 Time min = 0xffffffffffffffffULL;
247
248 // on recpuere l'id de la prochaine execution
249 send_mutex->GetMutex();
250 resume_id = resume_time.size();
251 for (size_t i = 0; i < resume_time.size(); i++) {
252 if (resume_time.at(i) < min && data_to_send.at(i)->IsEnabled() == true) {
253 min = resume_time.at(i);
254 resume_id = i;
255 }
256 }
257
258 // attente
259 if (resume_id < resume_time.size()) {
260 Time time = resume_time.at(resume_id);
261 uint16_t resume_period = data_to_send.at(resume_id)->SendPeriod();
262 send_mutex->ReleaseMutex();
263 // on dort jusqu'a la prochaine execution
264 SleepUntil(time);
265
266 // envoi des donnees
267 int offset = 3;
268 send_buffer[0] = header;
269 send_mutex->GetMutex();
270
271 for (size_t i = 0; i < data_to_send.size(); i++) {
272 if (data_to_send.at(i)->SendPeriod() == resume_period &&
273 data_to_send.at(i)->IsEnabled() == true) {
274 data_to_send.at(i)->CopyDatas(send_buffer + offset);
275 offset += data_to_send.at(i)->SendSize();
276 }
277 }
278 if (offset != 3) {
279 memcpy(&send_buffer[1], &resume_period, sizeof(uint16_t));
280 // printf("send %i %i %i %x
281 // %x\n",resume_period,offset,sizeof(uint16_t),send_buffer,&send_buffer[1]);
282 // for(int i=0;i<offset;i++) printf("%x ",send_buffer[i]);
283 // printf("\n");
284 Send(send_buffer, offset);
285 }
286
287 // on planifie la prochaine execution
288 for (size_t i = 0; i < data_to_send.size(); i++) {
289 if (data_to_send.at(i)->SendPeriod() == resume_period) {
290 resume_time.at(i) += data_to_send.at(i)->SendPeriod() * 1000000;
291 }
292 }
293 send_mutex->ReleaseMutex();
294 // Printf("%i %lld\n",resume_period,GetTime()/1000000);
295 } else {
296 send_mutex->ReleaseMutex();
297 // rien a faire, suspend
298 // Printf("rien a faire suspend\n");
299 Suspend();
300 // Printf("wake\n");
301 // on planifie la prochaine execution
302 Time time = GetTime();
303 send_mutex->GetMutex();
304 for (size_t i = 0; i < data_to_send.size(); i++) {
305 resume_time.at(i) =
306 time + (Time)data_to_send.at(i)->SendPeriod() * 1000000;
307 }
308 send_mutex->ReleaseMutex();
309 }
310 }
311}
312#ifdef __XENO__
313void *ui_com::user_thread(void *arg) {
314 int pipe_fd = -1;
315 string devname;
316 char *buf = NULL;
317 ui_com *caller = (ui_com *)arg;
318 int rv;
319 fd_set set;
320 struct timeval timeout;
321 ssize_t nb_read, nb_write;
322
323 buf = (char *)malloc(NRT_PIPE_SIZE);
324 if (buf == NULL) {
325 caller->Err("malloc error\n");
326 }
327
328 devname = NRT_PIPE_PATH + getFrameworkManager()->ObjectName() + "-" +
329 caller->ObjectName() + "-pipe";
330 while (pipe_fd < 0) {
331 pipe_fd = open(devname.c_str(), O_RDWR);
332 if (pipe_fd < 0 && errno != ENOENT) {
333 char errorMsg[256];
334 caller->Err("open pipe_fd error (%s)\n", strerror_r(errno, errorMsg, sizeof(errorMsg)));
335 }
336 usleep(1000);
337 }
338
339 while (1) {
340 FD_ZERO(&set); // clear the set
341 FD_SET(pipe_fd, &set); // add our file descriptor to the set
342
343 timeout.tv_sec = 0;
344 timeout.tv_usec = SELECT_TIMEOUT_MS * 1000;
345
346 rv = select(FD_SETSIZE, &set, NULL, NULL, &timeout);
347
348 if (rv == -1) {
349 if (caller->is_running == false &&
350 UDT::getlasterror().getErrorCode() == CUDTException::ETIMEOUT)
351 break; // timeout
352 if (UDT::getlasterror().getErrorCode() != CUDTException::ETIMEOUT)
353 caller->Err("epoll_wait, %s, code %i\n",
354 UDT::getlasterror().getErrorMessage(),
355 UDT::getlasterror().getErrorCode());
356 } else if (rv == 0) {
357 // printf("timeout\n"); // a timeout occured
358 if (caller->is_running == false)
359 break;
360
361 } else {
362 nb_read = read(pipe_fd, buf, NRT_PIPE_SIZE);
363 buf[nb_read] = 0;
364// printf("envoi\n%s\n",buf);
365
366#ifdef COMPRESS_FRAMES
367 char *out;
368 ssize_t out_size;
369
370 if (buf[0] == XML_HEADER) {
371 if (compressBuffer(buf, nb_read, &out, &out_size, 9) == Z_OK) {
372 nb_read = out_size;
373 nb_write = UDT::sendmsg(caller->socket_fd, out, out_size, -1, true);
374 free(out);
375 } else {
376 caller->Warn("Compress error, sending it uncompressed\n");
377 nb_write = UDT::sendmsg(caller->socket_fd, buf, nb_read, -1, true);
378 }
379 } else {
380 nb_write = UDT::sendmsg(caller->socket_fd, buf, nb_read, -1, true);
381 }
382#else
383 nb_write = UDT::sendmsg(caller->socket_fd, buf, nb_read, -1, true);
384#endif
385
386 if (nb_write < 0) {
387 caller->Err("UDT::sendmsg error (%s)\n",
388 UDT::getlasterror().getErrorMessage());
389 if (UDT::getlasterror().getErrorCode() == CUDTException::ECONNLOST ||
390 UDT::getlasterror().getErrorCode() == CUDTException::EINVSOCK) {
391 caller->connection_lost = true;
392 }
393 } else if (nb_write != nb_read) {
394 caller->Err("UDT::sendmsg error %i/%i\n", nb_write, nb_read);
395 }
396 }
397 }
398
399 close(pipe_fd);
400 if (buf != NULL)
401 free(buf);
402 pthread_exit(0);
403}
404#endif
405
406int ui_com::compressBuffer(char *in, ssize_t in_size, char **out,
407 ssize_t *out_size, int level) {
408 int ret, flush;
409 unsigned have;
410 z_stream strm;
411
412 /* allocate deflate state */
413 strm.zalloc = Z_NULL;
414 strm.zfree = Z_NULL;
415 strm.opaque = Z_NULL;
416 ret = deflateInit(&strm, level);
417 if (ret != Z_OK)
418 return ret;
419
420 *out = (char *)malloc(COMPRESS_CHUNK);
421 if (!(*out))
422 return Z_BUF_ERROR;
423
424 strm.next_in = (unsigned char *)in;
425 strm.avail_out = COMPRESS_CHUNK;
426 strm.next_out = (unsigned char *)*out;
427 strm.avail_in = in_size;
428 flush = Z_FINISH;
429
430 ret = deflate(&strm, flush); /* no bad return value */
431 if (ret == Z_STREAM_ERROR) {
432 free(*out);
433 return ret;
434 }
435
436 have = COMPRESS_CHUNK - strm.avail_out;
437 *out_size = have;
438 // printf("%i -> %i\n",in_size,have);
439 /* clean up and return */
440 (void)deflateEnd(&strm);
441
442 if (strm.avail_out != 0) {
443 return Z_OK;
444 } else {
445 return Z_STREAM_ERROR;
446 }
447}
448
449int ui_com::uncompressBuffer(unsigned char *in, ssize_t in_size,
450 unsigned char **out, ssize_t *out_size) {
451 int ret;
452 // unsigned have;
453 z_stream strm;
454
455 /* allocate inflate state */
456 strm.zalloc = Z_NULL;
457 strm.zfree = Z_NULL;
458 strm.opaque = Z_NULL;
459 strm.avail_in = 0;
460 strm.next_in = Z_NULL;
461 ret = inflateInit(&strm);
462 if (ret != Z_OK)
463 return ret;
464
465 *out = (unsigned char *)malloc(COMPRESS_CHUNK);
466 if (!(*out))
467 return Z_BUF_ERROR;
468
469 strm.avail_in = in_size;
470 strm.next_in = in;
471 strm.avail_out = COMPRESS_CHUNK;
472 strm.next_out = *out;
473
474 ret = inflate(&strm, Z_NO_FLUSH);
475 assert(ret != Z_STREAM_ERROR); /* state not clobbered */
476 switch (ret) {
477 case Z_NEED_DICT:
478 ret = Z_DATA_ERROR; /* and fall through */
479 case Z_DATA_ERROR:
480 case Z_MEM_ERROR:
481 (void)inflateEnd(&strm);
482 return ret;
483 }
484 // have = COMPRESS_CHUNK - strm.avail_out;
485
486 /* clean up and return */
487 (void)inflateEnd(&strm);
488 return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
489}
490
491bool ui_com::ConnectionLost() { return connection_lost; }
492
493void ui_com::AddSendData(const SendData *obj) {
494 send_mutex->GetMutex();
495
496 resume_time.push_back(GetTime() + (Time)obj->SendPeriod() * 1000000);
497
498 // on resume en meme temps tout ceux qui ont la meme periode
499 for (size_t i = 0; i < data_to_send.size(); i++) {
500 if (data_to_send.at(i)->SendPeriod() == obj->SendPeriod()) {
501 resume_time.at(resume_time.size() - 1) = resume_time.at(i);
502 break;
503 }
504 }
505
506 data_to_send.push_back(obj);
507
508 send_mutex->ReleaseMutex();
509}
510
511void ui_com::UpdateSendData(const SendData *obj) {
512 // le mutex est deja pris par l'appellant
513 size_t id, i;
514
515 // on recupere l'id
516 for (i = 0; i < data_to_send.size(); i++) {
517 if (data_to_send.at(i) == obj) {
518 id = i;
519 break;
520 }
521 }
522
523 // on resume en meme temps tout ceux qui ont la meme periode
524 for (i = 0; i < data_to_send.size(); i++) {
525 if (i == id)
526 continue;
527 if (data_to_send.at(i)->IsEnabled() == true &&
528 data_to_send.at(i)->SendPeriod() == obj->SendPeriod()) {
529 resume_time.at(id) = resume_time.at(i);
530 break;
531 }
532 }
533
534 // si aucun match, on planifie l'execution
535 if (i == data_to_send.size())
536 resume_time.at(id) = GetTime() + (Time)obj->SendPeriod() * 1000000;
537
538 if (IsSuspended() == true)
539 Resume();
540
541 return;
542}
543
544void ui_com::UpdateDataToSendSize(void) {
545 send_mutex->GetMutex();
546 send_size = 3; // id(1)+period(2)
547 for (size_t i = 0; i < data_to_send.size(); i++) {
548 if (data_to_send[i] != NULL)
549 send_size += data_to_send[i]->SendSize();
550 }
551
552 // send_buffer=(char*)realloc((void*)send_buffer,send_size*sizeof(char));
553 if (send_buffer != NULL)
554 free(send_buffer);
555 send_buffer = (char *)malloc(send_size * sizeof(char));
556 send_mutex->ReleaseMutex();
557}
558
559void ui_com::RemoveSendData(const SendData *obj) {
560 // printf("remove_data_to_send %i\n",data_to_send.size());
561
562 send_mutex->GetMutex();
563 // on recupere l'id
564 for (size_t i = 0; i < data_to_send.size(); i++) {
565 if (data_to_send.at(i) == obj) {
566 data_to_send.erase(data_to_send.begin() + i);
567 resume_time.erase(resume_time.begin() + i);
568 // printf("remove_data_to_send %i ok\n",data_to_send.size());
569 break;
570 }
571 }
572 send_mutex->ReleaseMutex();
573
574 return;
575}
576
577void ui_com::Block(void) { send_mutex->GetMutex(); }
578
579void ui_com::UnBlock(void) { send_mutex->ReleaseMutex(); }
Note: See TracBrowser for help on using the repository browser.