source: flair-src/trunk/lib/FlairCore/src/FrameworkManager_impl.cpp@ 262

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

maj pour udt

File size: 27.4 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/08/31
6// filename: FrameworkManager.cpp
7//
8// author: Guillaume Sanahuja
9// Copyright Heudiasyc UMR UTC/CNRS 7253
10//
11// version: $Id: $
12//
13// purpose: Classe de base de la librairie
14//
15//
16/*********************************************************************/
17
18#include "FrameworkManager_impl.h"
19#include "FrameworkManager.h"
20#include "Widget_impl.h"
21#include <unistd.h>
22#include "IODevice.h"
23#include "IODevice_impl.h"
24#include "TabWidget.h"
25#include "Layout.h"
26#include "PushButton.h"
27#include "communication.h"
28#include "config.h"
29#include "Watchdog.h"
30#include <errno.h>
31#include <string.h>
32#include <arpa/inet.h>
33#include <sys/mman.h>
34#include <execinfo.h>
35#include <signal.h>
36#include <fcntl.h>
37#ifdef __XENO__
38#include <native/task.h>
39#include <rtdk.h>
40#endif
41
42using namespace std;
43using namespace flair::core;
44using namespace flair::gui;
45
46ui_com *FrameworkManager_impl::com = NULL;
47FrameworkManager_impl *FrameworkManager_impl::_this = NULL;
48
49namespace {
50#ifdef __XENO__
51
52#ifdef SIGDEBUG
53static const char *reason_str[] = {
54 "undefined", "received signal", "invoked syscall", "triggered fault",
55 "affected by priority inversion", "missing mlockall", "runaway thread",
56};
57
58void warn_upon_switch(int sig, siginfo_t *si, void *context) {
59 unsigned int reason = si->si_value.sival_int;
60 void *bt[32];
61 int nentries;
62#ifdef SIGDEBUG_WATCHDOG
63 printf("\nSIGDEBUG received, reason %d: %s\n", reason,
64 reason <= SIGDEBUG_WATCHDOG ? reason_str[reason] : "<unknown>");
65#endif
66 // Dump a backtrace of the frame which caused the switch to secondary mode:
67 nentries = backtrace(bt, sizeof(bt) / sizeof(bt[0]));
68 backtrace_symbols_fd(bt, nentries, fileno(stdout));
69}
70#else // SIGDEBUG
71void warn_upon_switch(int sig __attribute__((unused))) {
72 void *bt[32];
73 int nentries;
74
75 /* Dump a backtrace of the frame which caused the switch to
76 secondary mode: */
77 nentries = backtrace(bt, sizeof(bt) / sizeof(bt[0]));
78 backtrace_symbols_fd(bt, nentries, fileno(stdout));
79}
80#endif // SIGDEBUG
81#endif //__XENO__
82void seg_fault(int sig __attribute__((unused))) {
83 void *bt[32];
84 int nentries;
85
86 printf("Segmentation fault:\n");
87 /* Dump a backtrace of the frame which caused the segfault: */
88 nentries = backtrace(bt, sizeof(bt) / sizeof(bt[0]));
89 backtrace_symbols_fd(bt, nentries, fileno(stdout));
90
91 exit(1);
92}
93}
94
95FrameworkManager_impl::FrameworkManager_impl(FrameworkManager *self,
96 string name)
97 : Thread(self, "FrameworkManager", FRAMEWORK_TASK_PRIORITY) {
98 this->self = self;
99 is_logging = false;
100 logger_defined = false;
101 disable_errors = false;
102 ui_defined = false;
103 rcv_buf = NULL;
104 gcs_watchdog = NULL;
105 _this = this;
106 tabwidget=NULL;
107
108 // Avoids memory swapping for this program
109 mlockall(MCL_CURRENT | MCL_FUTURE);
110
111 // catch segfault
112 signal(SIGSEGV, seg_fault);
113
114// catch primary->secondary switch
115#ifdef __XENO__
116#ifdef SIGDEBUG
117 struct sigaction sa;
118 sigemptyset(&sa.sa_mask);
119 sa.sa_sigaction = warn_upon_switch;
120 sa.sa_flags = SA_SIGINFO;
121 sigaction(SIGDEBUG, &sa, NULL);
122#else //SIGDEBUG
123 signal(SIGXCPU, warn_upon_switch);
124#endif //SIGDEBUG
125 string task_name = "Framework_" + name;
126
127 // Perform auto-init of rt_print buffers if the task doesn't do so
128 rt_print_auto_init(1);
129 // Initialise the rt_print buffer for this task explicitly
130 rt_print_init(512, task_name.c_str());
131
132 int status = rt_task_shadow(NULL, task_name.c_str(), 10, 0);
133 if (status != 0) {
134 char errorMsg[256];
135 self->Err("rt_task_shadow error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
136 }
137
138#endif //__XENO__
139}
140
141void FrameworkManager_impl::SetConnectionLost(void) {
142 Err("connection lost\n");
143 if(gcs_watchdog!=NULL) gcs_watchdog->SafeStop();
144 connection_lost = true;
145}
146
147FrameworkManager_impl::~FrameworkManager_impl() {
148 // Printf("destruction FrameworkManager_impl\n");
149 int status;
150
151 SafeStop();
152 Join();
153
154 if (rcv_buf != NULL)
155 free(rcv_buf);
156
157 if (logger_defined == true) {
158 continuer = false;
159 (void)pthread_join(log_th, NULL);
160
161 status = DeletePipe(&cmd_pipe);
162 if (status != 0) {
163 char errorMsg[256];
164 Err("Error deleting pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
165 }
166 status = DeletePipe(&data_pipe);
167 if (status != 0) {
168 char errorMsg[256];
169 Err("Error deleting pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
170 }
171
172#ifdef __XENO__
173 status = rt_heap_delete(&log_heap);
174 if (status != 0) {
175 char errorMsg[256];
176 Err("rt_heap_delete error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
177 }
178#endif
179
180 logs.clear();
181 }
182
183 if (file_doc != NULL)
184 xmlFreeDoc(file_doc);
185
186 if (ui_defined)
187 delete top_layout;
188
189 if (com != NULL) {
190 delete com;
191 //avoid waiting on closing if connection is lost
192 if(connection_lost) {
193 bool blocking = false;
194 if (UDT::setsockopt(com_sock, 0, UDT_SNDSYN, &blocking, sizeof(bool)) != 0)
195 Err("UDT::setsockopt error (UDT_SNDSYN)\n");
196 }
197 status = UDT::close(com_sock);
198 if (status != 0)
199 Printf("Error udt::close %s", UDT::getlasterror().getErrorMessage());
200
201 SleepMS(200); // a revoir, sinon UDT::cleanup bloque en RT
202
203 if(connection_lost) {
204 //don't know why?
205 Warn("Cleaning up UDT socket, this can take some time\n");
206 }
207 if (UDT::cleanup() != 0)
208 Err("UDT::cleanup error\n");
209 }
210
211 // Printf("destruction FrameworkManager_impl ok\n");
212}
213
214void FrameworkManager_impl::SetupConnection(string address, uint16_t port,Time watchdogTimeout,
215 size_t rcv_buf_size) {
216 if (com != NULL) {
217 Err("SetupConnection should be called only one time\n");
218 return;
219 }
220 this->address=address;
221 this->port=port;
222
223 UDT::startup2(1024*256,1024*256,1024*256);
224 this->rcv_buf_size = rcv_buf_size;
225
226 // socket file_socket, doit être créé en premier, cf station sol
227 Printf("Connecting to %s:%i\n", address.c_str(), port);
228 //file_sock = GetSocket(address, port);
229 com_sock = GetSocket();
230
231 // receive buffer allocation
232 rcv_buf = (char *)malloc(rcv_buf_size);
233 if (rcv_buf == NULL) {
234 Err("receive buffer malloc error\n");
235 }
236
237 com = new ui_com(this, com_sock);
238
239 Start();
240
241 // watchdog for connection with ground station
242 connection_lost = false;
243 gcs_watchdog = new Watchdog(this, std::bind(&FrameworkManager_impl::SetConnectionLost, this),watchdogTimeout);
244 gcs_watchdog->Start();
245}
246
247void FrameworkManager_impl::SetupUserInterface(string xml_file) {
248 ui_defined = true;
249 this->xml_file = xml_file;
250
251 // top_layout=new Layout(NULL,XML_ROOT_ELEMENT,XML_ROOT_TYPE);
252 top_layout = new Layout(NULL, self->ObjectName(), XML_ROOT_TYPE);
253
254 // xml setup of the main widget
255 if (xml_file != "") {
256 xmlNodePtr *file_node = &(((Widget *)(top_layout))->pimpl_->file_node);
257 file_doc = xmlParseFile(xml_file.c_str());
258 if (file_doc == NULL) {
259 self->Warn("XML document not parsed successfully. Creating a new one.\n");
260 file_doc = xmlNewDoc((xmlChar *)"1.0");
261 *file_node = xmlNewNode(NULL, (xmlChar *)XML_ROOT_TYPE);
262 xmlSetProp(*file_node, (xmlChar *)"name",
263 (xmlChar *)ObjectName().c_str());
264 xmlDocSetRootElement(file_doc, *file_node);
265 // PrintXml();
266 } else {
267 *file_node = xmlDocGetRootElement(file_doc);
268 if (xmlStrcmp((*file_node)->name, (xmlChar *)XML_ROOT_TYPE)) {
269 self->Warn("%s, no match found in xml file\n", XML_ROOT_TYPE);
270 *file_node = xmlNewNode(NULL, (xmlChar *)XML_ROOT_TYPE);
271 xmlSetProp(*file_node, (xmlChar *)"name",
272 (xmlChar *)ObjectName().c_str());
273 xmlDocSetRootElement(file_doc, *file_node);
274 }
275 }
276 } else {
277 self->Err("xml file not defined\n");
278 }
279
280 // gui
281 tabwidget =
282 new TabWidget(top_layout->At(0, 0), XML_MAIN_TABWIDGET, TabWidget::North);
283 save_button =
284 new PushButton(top_layout->At(1, 0),
285 "save config on target (" + self->ObjectName() + ")");
286 // load_button=new PushButton(top_layout->At(1,1),"load config on target (" +
287 // self->ObjectName() + ")");
288}
289
290// in case of RT, this thread switches to secondary mode when calling
291// com->Receive
292// it switches back to RT in ProcessXML when mutex are locked
293void FrameworkManager_impl::Run(void) {
294 while (!ToBeStopped()) {
295 ssize_t bytesRead;
296 bytesRead = com->Receive(rcv_buf, rcv_buf_size);
297 com->CheckConnection();
298//printf("%i\n",bytesRead);
299 if (bytesRead == (ssize_t)rcv_buf_size)
300 Err("FrameworkManager max receive size, augmenter le buffer size!\n");
301
302 if (bytesRead > 0) {
303 //printf("recu %ld, trame %x %lld\n",bytesRead,(uint8_t)rcv_buf[0],GetTime()/(1000000));
304 //rcv_buf[bytesRead-1]=0;//pour affichage
305 //printf("%s\n",rcv_buf);
306
307 switch ((uint8_t)rcv_buf[0]) {
308 case XML_HEADER: {
309 xmlDoc *doc;
310 rcv_buf[bytesRead] = 0;
311 //Printf("%s\n",rcv_buf);
312 doc = xmlReadMemory(rcv_buf, (int)bytesRead, "include.xml",
313 "ISO-8859-1", 0);
314 xmlNode *cur_node = NULL;
315
316 for (cur_node = xmlDocGetRootElement(doc); cur_node;
317 cur_node = cur_node->next) {
318 if (cur_node->type == XML_ELEMENT_NODE) {
319 if (!xmlStrcmp(cur_node->name, (xmlChar *)XML_ROOT_TYPE)) {
320#ifdef __XENO__
321 WarnUponSwitches(
322 true); // ProcessXML should not switch to secondary mode
323#endif
324 top_layout->Widget::pimpl_->ProcessXML(cur_node->children);
325#ifdef __XENO__
326 WarnUponSwitches(false); // other parts of this thread can switch
327 // to secondary mode
328#endif
329 break;
330 }
331 }
332 }
333
334 xmlFreeDoc(doc);
335
336 if (save_button->Clicked())
337 SaveXml();
338
339 SaveXmlChange(rcv_buf);
340
341 break;
342 }
343 case WATCHDOG_HEADER: {
344 if(gcs_watchdog!=NULL) gcs_watchdog->Touch();
345 break;
346 }
347 default:
348 Err("unknown id: %x\n", (uint8_t)rcv_buf[0]);
349 break;
350 }
351 } else {
352 if (com->ConnectionLost())
353 SleepMS(10); // avoid infinite loop in this case
354 }
355 }
356}
357
358void FrameworkManager_impl::SaveXml(void) {
359 if (ui_defined)
360 xmlSaveFormatFile(xml_file.c_str(), file_doc, 1);
361}
362
363void FrameworkManager_impl::SaveXmlChange(char *buf) {
364 if (is_logging == true) {
365 FILE *xml_change;
366 char filename[256];
367 Time time = GetTime();
368
369 sprintf(filename, "%s/changes_at_%lld.xml", log_path.c_str(), time);
370
371 xml_change = fopen(filename, "a");
372 fprintf(xml_change, "%s", buf);
373 fclose(xml_change);
374
375 sprintf(filename, "changes_at_%lld.xml", time);
376 xml_changes.push_back(filename);
377 }
378}
379
380void FrameworkManager_impl::SendFile(UDTSOCKET socket,string path, string name) {
381 char *buf, *more_buf;
382 int size;
383 filebuf *pbuf;
384 ssize_t nb_write;
385 string filename = path + "/" + name;
386
387 // open the file
388 fstream ifs(filename.c_str(), ios::in | ios::binary);
389 ifs.seekg(0, ios::end);
390 size = ifs.tellg();
391 ifs.seekg(0, ios::beg);
392 pbuf = ifs.rdbuf();
393
394 if (size <= 0) {
395 Err("error opening file %s\n", filename.c_str());
396 return;
397 }
398
399 buf = (char *)malloc(sizeof(uint8_t) + sizeof(int) + name.size());
400 if (buf == NULL) {
401 Err("malloc error, not sending file\n");
402 return;
403 }
404
405 if (IsBigEndian()) {
406 buf[0] = FILE_INFO_BIG_ENDIAN;
407 } else {
408 buf[0] = FILE_INFO_LITTLE_ENDIAN;
409 }
410
411 memcpy(buf + 1, &size, sizeof(int));
412 memcpy(buf + 1 + sizeof(int), name.c_str(), name.size());
413 Printf("sending %s, size: %i\n", filename.c_str(), size);
414 // send file information
415 UDT::sendmsg(socket, buf, sizeof(uint8_t) + sizeof(int) + name.size(), -1,true);
416
417 more_buf = (char *)realloc((void *)buf, size);
418 if (more_buf == NULL) {
419 Err("realloc error, not sending file\n");
420 free(buf);
421 return;
422 } else {
423 buf = more_buf;
424 }
425
426 pbuf->sgetn(buf, size);
427 // send the file
428 nb_write = UDT::sendmsg(socket, buf, size, -1, true);
429
430 if (nb_write < 0) {
431 Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
432 } else if (nb_write != size) {
433 Err("UDT::sendmsg error, sent %ld/%i\n", nb_write, size);
434 }
435
436 ifs.close();
437 free(buf);
438}
439
440void FrameworkManager_impl::FinishSending(UDTSOCKET socket) {
441 char rm_cmd[256];
442
443 // send orignal xml
444 SendFile(socket,log_path, "setup.xml");
445 sprintf(rm_cmd, "rm %s/setup.xml", log_path.c_str());
446 system(rm_cmd);
447
448 // send xml changes
449 for (size_t i = 0; i < xml_changes.size(); i++) {
450 // Printf("%s\n",xml_changes.at(i).c_str());
451 SendFile(socket,log_path, xml_changes.at(i).c_str());
452 sprintf(rm_cmd, "rm %s/%s", log_path.c_str(), xml_changes.at(i).c_str());
453 system(rm_cmd);
454 }
455 xml_changes.clear();
456
457 // end notify
458 char buf = END_SENDING_FILES;
459 int nb_write = UDT::sendmsg(socket, &buf, 1, -1, true);
460
461 if (nb_write < 0) {
462 Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
463 } else if (nb_write != 1) {
464 Err("UDT::sendmsg error, sent %i/%i\n", nb_write, 1);
465 }
466
467 //wait end ACK
468 int nb_read = UDT::recvmsg(socket,&buf,1);
469 if(nb_read<0) {
470 Err("UDT::recvmsg error (%s)\n",UDT::getlasterror().getErrorMessage());
471 } else if (nb_read != 1) {
472 Err("UDT::recvmsg error, sent %i/%i\n",nb_read,1);
473 }
474}
475
476UDTSOCKET FrameworkManager_impl::GetSocket(void) {
477 while (1) {
478 UDTSOCKET new_fd;
479 new_fd = UDT::socket(AF_INET, SOCK_DGRAM, 0);
480 if (new_fd == UDT::INVALID_SOCK) {
481 Err("socket error: %s\n", UDT::getlasterror().getErrorMessage());
482 return 0;
483 }
484
485 sockaddr_in serv_addr;
486 serv_addr.sin_family = AF_INET;
487 serv_addr.sin_port = htons(short(port));
488
489 if (inet_pton(AF_INET, address.c_str(), &serv_addr.sin_addr) <= 0) {
490 Err("incorrect network address\n");
491 return 0;
492 }
493
494 memset(&(serv_addr.sin_zero), '\0', 8);
495
496 if (UDT::ERROR ==
497 UDT::connect(new_fd, (sockaddr *)&serv_addr, sizeof(serv_addr))) {
498 // Printf("connect error: %s
499 // %i\n",UDT::getlasterror().getErrorMessage(),UDT::getlasterror().getErrorCode());
500 UDT::close(new_fd);
501 if (UDT::getlasterror().getErrorCode() != 1001 &&
502 UDT::getlasterror().getErrorCode() != 1002) {
503 Err("connect error: %s\n", UDT::getlasterror().getErrorMessage());
504 return 0;
505 }
506 } else {
507 // printf("connected to
508 // %s:%i\n",inet_ntoa(serv_addr.sin_addr),serv_addr.sin_port);
509 return new_fd;
510 }
511 }
512}
513
514#ifdef __XENO__
515int FrameworkManager_impl::CreatePipe(RT_PIPE *fd, string name) {
516 name = self->ObjectName() + "-" + name;
517 // xenomai limitation
518 if (name.size() > 31)
519 self->Err("rt_pipe_create error (%s is too long)\n", name.c_str());
520// start log writter
521#ifdef RT_PIPE_SIZE
522 return rt_pipe_create(fd, name.c_str(), P_MINOR_AUTO, RT_PIPE_SIZE);
523#else
524 return rt_pipe_create(fd, name.c_str(), P_MINOR_AUTO, 0);
525#endif
526}
527#else
528int FrameworkManager_impl::CreatePipe(int (*fd)[2], string name) {
529 // if(pipe2(fd[0],O_NONBLOCK) == -1)
530 if (pipe(fd[0]) == -1) {
531 return errno;
532 } else {
533 int attr = fcntl((*fd)[0], F_GETFL, 0);
534 if (attr == -1) {
535 return errno;
536 }
537 if (fcntl((*fd)[0], F_SETFL, attr | O_NONBLOCK) == -1) {
538 return errno;
539 }
540 attr = fcntl((*fd)[1], F_GETFL, 0);
541 if (attr == -1) {
542 return errno;
543 }
544 if (fcntl((*fd)[1], F_SETFL, attr | O_NONBLOCK) == -1) {
545 return errno;
546 }
547
548 return 0;
549 }
550}
551#endif
552
553#ifdef __XENO__
554int FrameworkManager_impl::DeletePipe(RT_PIPE *fd) {
555 return rt_pipe_delete(fd);
556}
557#else
558int FrameworkManager_impl::DeletePipe(int (*fd)[2]) {
559 int status1 = close((*fd)[0]);
560 int status2 = close((*fd)[1]);
561 if (status1 == 0 && status2 == 0)
562 return 0;
563 if (status1 != 0)
564 return status1;
565 if (status2 != 0)
566 return status2;
567}
568#endif
569
570void FrameworkManager_impl::SetupLogger(string log_path,uint32_t stackSize) {
571
572 if (logger_defined == true) {
573 Warn("SetupLogger() was already called.\n");
574 return;
575 }
576
577 this->log_path = log_path;
578
579 int status = CreatePipe(&cmd_pipe, "log_cmd");
580 if (status != 0) {
581 char errorMsg[256];
582 Err("Error creating pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
583 return;
584 }
585
586 status = CreatePipe(&data_pipe, "log_data");
587 if (status != 0) {
588 char errorMsg[256];
589 Err("Error creating pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
590 return;
591 }
592
593#ifdef __XENO__
594 string tmp_name;
595 tmp_name = self->ObjectName() + "-log_heap";
596 status = rt_heap_create(&log_heap, tmp_name.c_str(), RT_LOG_HEAP, H_FIFO);
597 if (status != 0) {
598 char errorMsg[256];
599 Err("rt_heap_create error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
600 return;
601 }
602#endif //__XENO__
603
604 continuer = true;
605
606 // Initialize thread creation attributes
607 pthread_attr_t attr;
608 status=pthread_attr_init(&attr);
609 if (status != 0) {
610 char errorMsg[256];
611 Err("pthread_attr_init error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
612 return;
613 }
614
615 status=pthread_attr_setstacksize(&attr, stackSize);
616 if (status != 0) {
617 char errorMsg[256];
618 Err("pthread_attr_setstacksize error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
619 return;
620 }
621
622 status=pthread_create(&log_th, &attr, write_log_user, (void *)this);
623 if (status < 0) {
624 char errorMsg[256];
625 Err("pthread_create error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
626 return;
627 }
628
629 status=pthread_attr_destroy(&attr);
630 if (status != 0) {
631 char errorMsg[256];
632 Err("pthread_attr_destroy error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
633 return;
634 }
635
636 logger_defined = true;
637}
638
639void FrameworkManager_impl::AddDeviceToLog(IODevice *device) {
640 if (logger_defined == false) {
641 Warn("SetupLogger() was not called, not adding to log\n");
642 return;
643 }
644
645 if (is_logging == false) {
646 if (!device->pimpl_->IsSetToBeLogged()) {
647 device->pimpl_->SetToBeLogged();
648 log_desc_t tmp;
649 tmp.device = device;
650 logs.push_back(tmp);
651 } else {
652 Warn("not adding it twice\n");
653 }
654 } else {
655 Err("impossible while logging\n");
656 }
657}
658
659bool FrameworkManager_impl::IsDeviceLogged(const IODevice *device) const {
660 return device->pimpl_->IsSetToBeLogged();
661}
662
663void FrameworkManager_impl::StartLog(void) {
664 if (logger_defined == false) {
665 Err("SetupLogger() was not called, not starting log\n");
666 return;
667 }
668
669 ssize_t written;
670 size_t nb_err = 0;
671
672 if (logs.size() == 0) {
673 Warn("Not starting log: nothing to log!\n");
674 return;
675 }
676
677 if (is_logging == false) {
678 for (size_t i = 0; i < logs.size(); i++) {
679
680 logs.at(i).running = true;
681 logs.at(i).dbtFile = NULL;
682 logs.at(i).size = logs.at(i).device->pimpl_->LogSize();
683#ifdef __XENO__
684 written =
685 rt_pipe_write(&cmd_pipe, &logs.at(i), sizeof(log_desc_t), P_NORMAL);
686#else
687 written = write(cmd_pipe[1], &logs.at(i), sizeof(log_desc_t));
688#endif
689
690 if (written < 0) {
691 char errorMsg[256];
692 Err("write pipe error (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
693 nb_err++;
694 logs.at(i).running = false;
695 } else if (written != sizeof(log_desc_t)) {
696 Err("write pipe error %ld/%ld\n", written, sizeof(log_desc_t));
697 nb_err++;
698 logs.at(i).running = false;
699 }
700 }
701
702 if (nb_err != logs.size())
703 is_logging = true;
704 } else {
705 Warn("Already logging\n");
706 }
707}
708
709void FrameworkManager_impl::StopLog(void) {
710 ssize_t written;
711
712 if (is_logging == true) {
713 for (size_t i = 0; i < logs.size(); i++) {
714 logs.at(i).running = false;
715 }
716// send only one running false condition, user thread will stop and send all
717#ifdef __XENO__
718 written =
719 rt_pipe_write(&cmd_pipe, &logs.at(0), sizeof(log_desc_t), P_NORMAL);
720#else
721 written = write(cmd_pipe[1], &logs.at(0), sizeof(log_desc_t));
722#endif
723
724 if (written < 0) {
725 char errorMsg[256];
726 Err("write pipe error (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
727 return;
728 } else if (written != sizeof(log_desc_t)) {
729 Err("write pipe error %ld/%ld\n", written, sizeof(log_desc_t));
730 return;
731 }
732
733 is_logging = false;
734 } else {
735 Warn("Not logging\n");
736 }
737}
738
739char *FrameworkManager_impl::GetBuffer(size_t sz) {
740// Printf("alloc %i\n",sz);
741#ifdef __XENO__
742 void *ptr;
743 int status = rt_heap_alloc(&log_heap, sz, TM_NONBLOCK, &ptr);
744 if (status != 0) {
745 char errorMsg[256];
746 Err("rt_heap_alloc error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
747 ptr = NULL;
748 }
749 return (char *)ptr;
750#else
751 return (char *)malloc(sz);
752#endif
753}
754
755void FrameworkManager_impl::ReleaseBuffer(char *buf) {
756#ifdef __XENO__
757 int status = rt_heap_free(&log_heap, buf);
758
759 if (status != 0) {
760 char errorMsg[256];
761 Err("rt_heap_free error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
762 }
763#else
764 free(buf);
765#endif
766}
767
768void FrameworkManager_impl::WriteLog(const char *buf, size_t size) {
769 ssize_t written;
770
771#ifdef __XENO__
772 written = rt_pipe_write(&data_pipe, buf, size, P_NORMAL);
773#else
774 written = write(data_pipe[1], buf, size);
775#endif
776
777 if (written < 0) {
778 char errorMsg[256];
779 Err("error write pipe (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
780 } else if (written != (ssize_t)size) {
781 Err("error write pipe %ld/%ld\n", written, size);
782 }
783}
784
785void *FrameworkManager_impl::write_log_user(void *arg) {
786 int cmd_pipe = -1;
787 int data_pipe = -1;
788 fd_set set;
789 struct timeval timeout;
790 FrameworkManager_impl *caller = (FrameworkManager_impl *)arg;
791 int rv;
792
793 vector<log_desc_t> logs;
794
795#ifdef __XENO__
796 while (cmd_pipe < 0) {
797 string filename = NRT_PIPE_PATH + caller->self->ObjectName() + "-log_cmd";
798 cmd_pipe = open(filename.c_str(), O_RDWR);
799 if (cmd_pipe < 0 && errno != ENOENT) {
800 char errorMsg[256];
801 caller->self->Err("open rt_pipe error: %s %s\n", filename.c_str(), strerror_r(errno, errorMsg, sizeof(errorMsg)));
802 }
803 usleep(1000);
804 }
805 while (data_pipe < 0) {
806 string filename = NRT_PIPE_PATH + caller->self->ObjectName() + "-log_data";
807 data_pipe = open(filename.c_str(), O_RDWR);
808 if (data_pipe < 0 && errno != ENOENT) {
809 char errorMsg[256];
810 caller->self->Err("open rt_pipe error: %s %s\n", filename.c_str(), strerror_r(errno, errorMsg, sizeof(errorMsg)));
811 }
812 usleep(1000);
813 }
814#else
815 cmd_pipe = caller->cmd_pipe[0];
816 data_pipe = caller->data_pipe[0];
817#endif
818
819 while (caller->continuer == true) {
820 FD_ZERO(&set);
821 FD_SET(cmd_pipe, &set);
822 FD_SET(data_pipe, &set);
823
824 timeout.tv_sec = 0;
825 timeout.tv_usec = SELECT_TIMEOUT_MS * 1000;
826 rv = select(FD_SETSIZE, &set, NULL, NULL, &timeout);
827
828 if (rv == -1) {
829 caller->Err("select error\n"); // an error accured
830 } else if (rv == 0) {
831 // printf("timeout write_log_user %s\n",caller->ObjectName().c_str()); //
832 // a timeout occured
833 } else {
834 if (FD_ISSET(cmd_pipe, &set)) {
835 log_desc_t tmp;
836 read(cmd_pipe, &tmp, sizeof(log_desc_t));
837
838 if (tmp.running == true) {// start logging
839 string filename = caller->log_path + "/" + caller->FileName(tmp.device) + ".dbt";
840 printf("Creating log file %s (log size %i)\n", filename.c_str(), (int)tmp.size);
841 tmp.dbtFile = inithdFile((char *)filename.c_str(), UAV, tmp.size);
842 logs.push_back(tmp);
843
844 if (logs.size() == 1) {
845 filename = caller->log_path + "/setup.xml";
846 xmlSaveFile(filename.c_str(), caller->file_doc);
847 }
848 } else {// stop logging
849 //disable watchdog temporarly
850 //this is necessary because GCS is no longer sending the heartbeat when receiving files...
851 //TODO: add a thread in GCS for receiving file
852 //but be careful that with a xbee modem for exemple, sending files can saturate communication and
853 //avoid the heartbeat to be received... so disabling watchdog is not a so bad option...
854 if(caller->gcs_watchdog!=NULL) {
855 caller->gcs_watchdog->SafeStop();
856 caller->gcs_watchdog->Join();
857 }
858 //create a socket for files
859 UDTSOCKET file_sock = caller->GetSocket();
860 char data=START_SENDING_FILES;
861 ssize_t nb_write = UDT::sendmsg(file_sock, &data, 1, -1, true);
862 if (nb_write < 0) {
863 caller->Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
864 if (UDT::getlasterror().getErrorCode() == CUDTException::ECONNLOST ||
865 UDT::getlasterror().getErrorCode() == CUDTException::EINVSOCK) {
866 }
867 } else if (nb_write != 1) {
868 caller->Err("%s, code %i (%ld/%ld)\n", UDT::getlasterror().getErrorMessage(),
869 UDT::getlasterror().getErrorCode(), nb_write, 1);
870 }
871 for (size_t i = 0; i < logs.size(); i++) {
872 if (logs.at(i).dbtFile != NULL) {
873 close_hdfile(logs.at(i).dbtFile);
874
875 string filename = caller->FileName(logs.at(i).device) + ".dbt";
876 caller->SendFile(file_sock,caller->log_path, filename);
877
878 fstream txt_file;
879 filename = caller->FileName(logs.at(i).device) + ".txt";
880 txt_file.open((caller->log_path + "/" + filename).c_str(),
881 fstream::out);
882 txt_file << "1: time (us)\n2: time (ns)\n";
883 int index = 3;
884 logs.at(i).device->pimpl_->WriteLogsDescriptors(txt_file, &index);
885 txt_file.close();
886
887 caller->SendFile(file_sock,caller->log_path, filename);
888 }
889 }
890 // a revoir celui ci est le xml enregistré et pas forcement l'actuel
891 // if(caller->xml_file!="") caller->SendFile(caller->xml_file);
892 caller->FinishSending(file_sock);
893
894 int status = UDT::close(file_sock);
895 if (status != 0)
896 caller->Err("Error udt::close %s", UDT::getlasterror().getErrorMessage());
897
898 logs.clear();
899 //enable watchdog again
900 if(caller->gcs_watchdog!=NULL) {
901 caller->gcs_watchdog->Start();
902 }
903 }
904 }
905
906 if (FD_ISSET(data_pipe, &set)) {
907 log_header_t header;
908 read(data_pipe, &header, sizeof(log_header_t));
909
910 for (size_t i = 0; i < logs.size(); i++) {
911 if (logs.at(i).device == header.device) {
912 char *buf = (char *)malloc(header.size);
913 read(data_pipe, buf, header.size);
914 // printf("%s \n",header.device->ObjectName().c_str());
915 // for(int i=0;i<header.size;i++) printf("%x ",buf[i]);
916 // printf("\n");
917 if (logs.at(i).size == header.size) {
918 if (logs.at(i).dbtFile != NULL) {
919 write_hdfile(
920 logs.at(i).dbtFile, buf, (road_time_t)(header.time / 1000),
921 (road_timerange_t)(header.time % 1000), header.size);
922 } else {
923 printf("err\n");
924 }
925 } else {
926 caller->self->Err("%s log size is not correct %i/%i\n",
927 header.device->ObjectName().c_str(),
928 header.size, logs.at(i).size);
929 }
930 free(buf);
931 }
932 }
933 }
934 }
935 }
936
937#ifdef __XENO__
938 close(cmd_pipe);
939 close(data_pipe);
940#endif
941
942 pthread_exit(0);
943}
944
945string FrameworkManager_impl::FileName(IODevice *device) {
946 return getFrameworkManager()->ObjectName() + "_" + device->ObjectName();
947}
948
949void FrameworkManager_impl::PrintXml(void) const {
950 xmlChar *xmlbuff;
951 int buffersize;
952 xmlDocDumpFormatMemory(file_doc, &xmlbuff, &buffersize, 1);
953 Printf("xml:\n%s\n", xmlbuff);
954 xmlFree(xmlbuff);
955}
Note: See TracBrowser for help on using the repository browser.