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

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

matrix

File size: 26.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::ConnectionLost(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 status = UDT::close(com_sock);
192 if (status != 0)
193 Printf("Error udt::close %s", UDT::getlasterror().getErrorMessage());
194
195 status = UDT::close(file_sock);
196 if (status != 0)
197 Printf("Error udt::close %s", UDT::getlasterror().getErrorMessage());
198
199 SleepMS(200); // a revoir, sinon UDT::cleanup bloque en RT
200 UDT::cleanup();
201 }
202
203 // Printf("destruction FrameworkManager_impl ok\n");
204}
205
206void FrameworkManager_impl::SetupConnection(string address, uint16_t port,Time watchdogTimeout,
207 size_t rcv_buf_size) {
208 if (com != NULL) {
209 Err("SetupConnection should be called only one time\n");
210 return;
211 }
212
213 UDT::startup(1024*256,1024*256,1024*256);
214 this->rcv_buf_size = rcv_buf_size;
215
216 // socket file_socket, doit être créé en premier, cf station sol
217 Printf("Connecting to %s:%i\n", address.c_str(), port);
218 file_sock = GetSocket(address, port);
219 com_sock = GetSocket(address, port);
220
221 // receive buffer allocation
222 rcv_buf = (char *)malloc(rcv_buf_size);
223 if (rcv_buf == NULL) {
224 Err("receive buffer malloc error\n");
225 }
226
227 com = new ui_com(this, com_sock);
228
229 // file managment
230 bool blocking = true;
231 UDT::setsockopt(file_sock, 0, UDT_SNDSYN, &blocking, sizeof(bool));
232 UDT::setsockopt(file_sock, 0, UDT_RCVSYN, &blocking, sizeof(bool));
233
234 int timeout = 100; // ms
235 UDT::setsockopt(com_sock, 0, UDT_RCVTIMEO, &timeout, sizeof(int));
236
237 Start();
238
239 // watchdog for connection with ground station
240 connection_lost = false;
241 gcs_watchdog = new Watchdog(this, std::bind(&FrameworkManager_impl::ConnectionLost, this),watchdogTimeout);
242 gcs_watchdog->Start();
243}
244
245void FrameworkManager_impl::SetupUserInterface(string xml_file) {
246 ui_defined = true;
247 this->xml_file = xml_file;
248
249 // top_layout=new Layout(NULL,XML_ROOT_ELEMENT,XML_ROOT_TYPE);
250 top_layout = new Layout(NULL, self->ObjectName(), XML_ROOT_TYPE);
251
252 // xml setup of the main widget
253 if (xml_file != "") {
254 xmlNodePtr *file_node = &(((Widget *)(top_layout))->pimpl_->file_node);
255 file_doc = xmlParseFile(xml_file.c_str());
256 if (file_doc == NULL) {
257 self->Warn("XML document not parsed successfully. Creating a new one.\n");
258 file_doc = xmlNewDoc((xmlChar *)"1.0");
259 *file_node = xmlNewNode(NULL, (xmlChar *)XML_ROOT_TYPE);
260 xmlSetProp(*file_node, (xmlChar *)"name",
261 (xmlChar *)ObjectName().c_str());
262 xmlDocSetRootElement(file_doc, *file_node);
263 // PrintXml();
264 } else {
265 *file_node = xmlDocGetRootElement(file_doc);
266 if (xmlStrcmp((*file_node)->name, (xmlChar *)XML_ROOT_TYPE)) {
267 self->Warn("%s, no match found in xml file\n", XML_ROOT_TYPE);
268 *file_node = xmlNewNode(NULL, (xmlChar *)XML_ROOT_TYPE);
269 xmlSetProp(*file_node, (xmlChar *)"name",
270 (xmlChar *)ObjectName().c_str());
271 xmlDocSetRootElement(file_doc, *file_node);
272 }
273 }
274 } else {
275 self->Err("xml file not defined\n");
276 }
277
278 // gui
279 tabwidget =
280 new TabWidget(top_layout->At(0, 0), XML_MAIN_TABWIDGET, TabWidget::North);
281 save_button =
282 new PushButton(top_layout->At(1, 0),
283 "save config on target (" + self->ObjectName() + ")");
284 // load_button=new PushButton(top_layout->At(1,1),"load config on target (" +
285 // self->ObjectName() + ")");
286}
287
288// in case of RT, this thread switches to secondary mode when calling
289// com->Receive
290// it switches back to RT in ProcessXML when mutex are locked
291void FrameworkManager_impl::Run(void) {
292 while (!ToBeStopped()) {
293 ssize_t bytesRead;
294
295 bytesRead = com->Receive(rcv_buf, rcv_buf_size);
296
297 if (bytesRead == (ssize_t)rcv_buf_size)
298 Err("FrameworkManager max receive size, augmenter le buffer size!\n");
299
300 if (bytesRead > 0) {
301 // printf("recu %ld, trame %x\n",bytesRead,(uint8_t)rcv_buf[0]);
302 // rcv_buf[bytesRead-1]=0;//pour affichage
303 // printf("%s\n",rcv_buf);
304
305 switch ((uint8_t)rcv_buf[0]) {
306 case XML_HEADER: {
307 xmlDoc *doc;
308 rcv_buf[bytesRead] = 0;
309 //Printf("%s\n",rcv_buf);
310 doc = xmlReadMemory(rcv_buf, (int)bytesRead, "include.xml",
311 "ISO-8859-1", 0);
312 xmlNode *cur_node = NULL;
313
314 for (cur_node = xmlDocGetRootElement(doc); cur_node;
315 cur_node = cur_node->next) {
316 if (cur_node->type == XML_ELEMENT_NODE) {
317 if (!xmlStrcmp(cur_node->name, (xmlChar *)XML_ROOT_TYPE)) {
318#ifdef __XENO__
319 WarnUponSwitches(
320 true); // ProcessXML should not switch to secondary mode
321#endif
322 top_layout->Widget::pimpl_->ProcessXML(cur_node->children);
323#ifdef __XENO__
324 WarnUponSwitches(false); // other parts of this thread can switch
325 // to secondary mode
326#endif
327 break;
328 }
329 }
330 }
331
332 xmlFreeDoc(doc);
333
334 if (save_button->Clicked())
335 SaveXml();
336
337 SaveXmlChange(rcv_buf);
338
339 break;
340 }
341 case WATCHDOG_HEADER: {
342 if(gcs_watchdog!=NULL) gcs_watchdog->Touch();
343 break;
344 }
345 default:
346 Err("unknown id: %x\n", (uint8_t)rcv_buf[0]);
347 break;
348 }
349 } else {
350 if (com->ConnectionLost())
351 SleepMS(10); // avoid infinite loop in this case
352 }
353 }
354}
355
356void FrameworkManager_impl::SaveXml(void) {
357 if (ui_defined)
358 xmlSaveFormatFile(xml_file.c_str(), file_doc, 1);
359}
360
361void FrameworkManager_impl::SaveXmlChange(char *buf) {
362 if (is_logging == true) {
363 FILE *xml_change;
364 char filename[256];
365 Time time = GetTime();
366
367 sprintf(filename, "%s/changes_at_%lld.xml", log_path.c_str(), time);
368
369 xml_change = fopen(filename, "a");
370 fprintf(xml_change, "%s", buf);
371 fclose(xml_change);
372
373 sprintf(filename, "changes_at_%lld.xml", time);
374 xml_changes.push_back(filename);
375 }
376}
377
378void FrameworkManager_impl::SendFile(string path, string name) {
379 char *buf, *more_buf;
380 int size;
381 filebuf *pbuf;
382 ssize_t nb_write;
383 string filename = path + "/" + name;
384
385 // open the file
386 fstream ifs(filename.c_str(), ios::in | ios::binary);
387 ifs.seekg(0, ios::end);
388 size = ifs.tellg();
389 ifs.seekg(0, ios::beg);
390 pbuf = ifs.rdbuf();
391
392 if (size <= 0) {
393 Err("error opening file %s\n", filename.c_str());
394 return;
395 }
396
397 buf = (char *)malloc(sizeof(uint8_t) + sizeof(int) + name.size());
398 if (buf == NULL) {
399 Err("malloc error, not sending file\n");
400 return;
401 }
402
403 if (IsBigEndian()) {
404 buf[0] = FILE_INFO_BIG_ENDIAN;
405 } else {
406 buf[0] = FILE_INFO_LITTLE_ENDIAN;
407 }
408
409 memcpy(buf + 1, &size, sizeof(int));
410 memcpy(buf + 1 + sizeof(int), name.c_str(), name.size());
411 Printf("sending %s, size: %i\n", filename.c_str(), size);
412 // send file information
413 UDT::sendmsg(file_sock, buf, sizeof(uint8_t) + sizeof(int) + name.size(), -1,true);
414
415 more_buf = (char *)realloc((void *)buf, size);
416 if (more_buf == NULL) {
417 Err("realloc error, not sending file\n");
418 free(buf);
419 return;
420 } else {
421 buf = more_buf;
422 }
423
424 pbuf->sgetn(buf, size);
425 // send the file
426 nb_write = UDT::sendmsg(file_sock, buf, size, -1, true);
427
428 if (nb_write < 0) {
429 Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
430 } else if (nb_write != size) {
431 Err("UDT::sendmsg error, sent %ld/%i\n", nb_write, size);
432 }
433
434 ifs.close();
435 free(buf);
436}
437
438void FrameworkManager_impl::FinishSending() {
439 char rm_cmd[256];
440
441 // send orignal xml
442 SendFile(log_path, "setup.xml");
443 sprintf(rm_cmd, "rm %s/setup.xml", log_path.c_str());
444 system(rm_cmd);
445
446 // send xml changes
447 for (size_t i = 0; i < xml_changes.size(); i++) {
448 // Printf("%s\n",xml_changes.at(i).c_str());
449 SendFile(log_path, xml_changes.at(i).c_str());
450 sprintf(rm_cmd, "rm %s/%s", log_path.c_str(), xml_changes.at(i).c_str());
451 system(rm_cmd);
452 }
453 xml_changes.clear();
454
455 // end notify
456 char buf = END;
457 int nb_write = UDT::sendmsg(file_sock, &buf, 1, -1, true);
458
459 if (nb_write < 0) {
460 Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
461 } else if (nb_write != 1) {
462 Err("UDT::sendmsg error, sent %i/%i\n", nb_write, 1);
463 }
464
465 //wait end ACK
466 int nb_read = UDT::recvmsg(file_sock,&buf,1);
467 if(nb_read<0) {
468 Err("UDT::recvmsg error (%s)\n",UDT::getlasterror().getErrorMessage());
469 } else if (nb_read != 1) {
470 Err("UDT::recvmsg error, sent %i/%i\n",nb_read,1);
471 }
472}
473
474UDTSOCKET FrameworkManager_impl::GetSocket(string address, uint16_t port) {
475 while (1) {
476 UDTSOCKET new_fd;
477 new_fd = UDT::socket(AF_INET, SOCK_DGRAM, 0);
478 if (new_fd == UDT::INVALID_SOCK) {
479 Err("socket error: %s\n", UDT::getlasterror().getErrorMessage());
480 return 0;
481 }
482
483 sockaddr_in serv_addr;
484 serv_addr.sin_family = AF_INET;
485 serv_addr.sin_port = htons(short(port));
486
487 if (inet_pton(AF_INET, address.c_str(), &serv_addr.sin_addr) <= 0) {
488 Err("incorrect network address\n");
489 return 0;
490 }
491
492 memset(&(serv_addr.sin_zero), '\0', 8);
493
494 if (UDT::ERROR ==
495 UDT::connect(new_fd, (sockaddr *)&serv_addr, sizeof(serv_addr))) {
496 // Printf("connect error: %s
497 // %i\n",UDT::getlasterror().getErrorMessage(),UDT::getlasterror().getErrorCode());
498 UDT::close(new_fd);
499 if (UDT::getlasterror().getErrorCode() != 1001 &&
500 UDT::getlasterror().getErrorCode() != 1002) {
501 Err("connect error: %s\n", UDT::getlasterror().getErrorMessage());
502 return 0;
503 }
504 } else {
505 // printf("connected to
506 // %s:%i\n",inet_ntoa(serv_addr.sin_addr),serv_addr.sin_port);
507 return new_fd;
508 }
509 }
510}
511
512#ifdef __XENO__
513int FrameworkManager_impl::CreatePipe(RT_PIPE *fd, string name) {
514 name = self->ObjectName() + "-" + name;
515 // xenomai limitation
516 if (name.size() > 31)
517 self->Err("rt_pipe_create error (%s is too long)\n", name.c_str());
518// start log writter
519#ifdef RT_PIPE_SIZE
520 return rt_pipe_create(fd, name.c_str(), P_MINOR_AUTO, RT_PIPE_SIZE);
521#else
522 return rt_pipe_create(fd, name.c_str(), P_MINOR_AUTO, 0);
523#endif
524}
525#else
526int FrameworkManager_impl::CreatePipe(int (*fd)[2], string name) {
527 // if(pipe2(fd[0],O_NONBLOCK) == -1)
528 if (pipe(fd[0]) == -1) {
529 return errno;
530 } else {
531 int attr = fcntl((*fd)[0], F_GETFL, 0);
532 if (attr == -1) {
533 return errno;
534 }
535 if (fcntl((*fd)[0], F_SETFL, attr | O_NONBLOCK) == -1) {
536 return errno;
537 }
538 attr = fcntl((*fd)[1], F_GETFL, 0);
539 if (attr == -1) {
540 return errno;
541 }
542 if (fcntl((*fd)[1], F_SETFL, attr | O_NONBLOCK) == -1) {
543 return errno;
544 }
545
546 return 0;
547 }
548}
549#endif
550
551#ifdef __XENO__
552int FrameworkManager_impl::DeletePipe(RT_PIPE *fd) {
553 return rt_pipe_delete(fd);
554}
555#else
556int FrameworkManager_impl::DeletePipe(int (*fd)[2]) {
557 int status1 = close((*fd)[0]);
558 int status2 = close((*fd)[1]);
559 if (status1 == 0 && status2 == 0)
560 return 0;
561 if (status1 != 0)
562 return status1;
563 if (status2 != 0)
564 return status2;
565}
566#endif
567
568void FrameworkManager_impl::SetupLogger(string log_path,uint32_t stackSize) {
569
570 if (logger_defined == true) {
571 Warn("SetupLogger() was already called.\n");
572 return;
573 }
574
575 this->log_path = log_path;
576
577 int status = CreatePipe(&cmd_pipe, "log_cmd");
578 if (status != 0) {
579 char errorMsg[256];
580 Err("Error creating pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
581 return;
582 }
583
584 status = CreatePipe(&data_pipe, "log_data");
585 if (status != 0) {
586 char errorMsg[256];
587 Err("Error creating pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
588 return;
589 }
590
591#ifdef __XENO__
592 string tmp_name;
593 tmp_name = self->ObjectName() + "-log_heap";
594 status = rt_heap_create(&log_heap, tmp_name.c_str(), RT_LOG_HEAP, H_FIFO);
595 if (status != 0) {
596 char errorMsg[256];
597 Err("rt_heap_create error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
598 return;
599 }
600#endif //__XENO__
601
602 continuer = true;
603
604 // Initialize thread creation attributes
605 pthread_attr_t attr;
606 status=pthread_attr_init(&attr);
607 if (status != 0) {
608 char errorMsg[256];
609 Err("pthread_attr_init error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
610 return;
611 }
612
613 status=pthread_attr_setstacksize(&attr, stackSize);
614 if (status != 0) {
615 char errorMsg[256];
616 Err("pthread_attr_setstacksize error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
617 return;
618 }
619
620 status=pthread_create(&log_th, &attr, write_log_user, (void *)this);
621 if (status < 0) {
622 char errorMsg[256];
623 Err("pthread_create error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
624 return;
625 }
626
627 status=pthread_attr_destroy(&attr);
628 if (status != 0) {
629 char errorMsg[256];
630 Err("pthread_attr_destroy error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
631 return;
632 }
633
634 logger_defined = true;
635}
636
637void FrameworkManager_impl::AddDeviceToLog(IODevice *device) {
638 if (logger_defined == false) {
639 Warn("SetupLogger() was not called, not adding to log\n");
640 return;
641 }
642
643 if (is_logging == false) {
644 if (!device->pimpl_->IsSetToBeLogged()) {
645 device->pimpl_->SetToBeLogged();
646 log_desc_t tmp;
647 tmp.device = device;
648 logs.push_back(tmp);
649 } else {
650 Warn("not adding it twice\n");
651 }
652 } else {
653 Err("impossible while logging\n");
654 }
655}
656
657bool FrameworkManager_impl::IsDeviceLogged(const IODevice *device) const {
658 return device->pimpl_->IsSetToBeLogged();
659}
660
661void FrameworkManager_impl::StartLog(void) {
662 if (logger_defined == false) {
663 Err("SetupLogger() was not called, not starting log\n");
664 return;
665 }
666
667 ssize_t written;
668 size_t nb_err = 0;
669
670 if (logs.size() == 0) {
671 Warn("Not starting log: nothing to log!\n");
672 return;
673 }
674
675 if (is_logging == false) {
676 for (size_t i = 0; i < logs.size(); i++) {
677
678 logs.at(i).running = true;
679 logs.at(i).dbtFile = NULL;
680 logs.at(i).size = logs.at(i).device->pimpl_->LogSize();
681#ifdef __XENO__
682 written =
683 rt_pipe_write(&cmd_pipe, &logs.at(i), sizeof(log_desc_t), P_NORMAL);
684#else
685 written = write(cmd_pipe[1], &logs.at(i), sizeof(log_desc_t));
686#endif
687
688 if (written < 0) {
689 char errorMsg[256];
690 Err("write pipe error (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
691 nb_err++;
692 logs.at(i).running = false;
693 } else if (written != sizeof(log_desc_t)) {
694 Err("write pipe error %ld/%ld\n", written, sizeof(log_desc_t));
695 nb_err++;
696 logs.at(i).running = false;
697 }
698 }
699
700 if (nb_err != logs.size())
701 is_logging = true;
702 } else {
703 Warn("Already logging\n");
704 }
705}
706
707void FrameworkManager_impl::StopLog(void) {
708 ssize_t written;
709
710 if (is_logging == true) {
711 for (size_t i = 0; i < logs.size(); i++) {
712 logs.at(i).running = false;
713 }
714// send only one running false condition, user thread will stop and send all
715#ifdef __XENO__
716 written =
717 rt_pipe_write(&cmd_pipe, &logs.at(0), sizeof(log_desc_t), P_NORMAL);
718#else
719 written = write(cmd_pipe[1], &logs.at(0), sizeof(log_desc_t));
720#endif
721
722 if (written < 0) {
723 char errorMsg[256];
724 Err("write pipe error (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
725 return;
726 } else if (written != sizeof(log_desc_t)) {
727 Err("write pipe error %ld/%ld\n", written, sizeof(log_desc_t));
728 return;
729 }
730
731 is_logging = false;
732 } else {
733 Warn("Not logging\n");
734 }
735}
736
737char *FrameworkManager_impl::GetBuffer(size_t sz) {
738// Printf("alloc %i\n",sz);
739#ifdef __XENO__
740 void *ptr;
741 int status = rt_heap_alloc(&log_heap, sz, TM_NONBLOCK, &ptr);
742 if (status != 0) {
743 char errorMsg[256];
744 Err("rt_heap_alloc error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
745 ptr = NULL;
746 }
747 return (char *)ptr;
748#else
749 return (char *)malloc(sz);
750#endif
751}
752
753void FrameworkManager_impl::ReleaseBuffer(char *buf) {
754#ifdef __XENO__
755 int status = rt_heap_free(&log_heap, buf);
756
757 if (status != 0) {
758 char errorMsg[256];
759 Err("rt_heap_free error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
760 }
761#else
762 free(buf);
763#endif
764}
765
766void FrameworkManager_impl::WriteLog(const char *buf, size_t size) {
767 ssize_t written;
768
769#ifdef __XENO__
770 written = rt_pipe_write(&data_pipe, buf, size, P_NORMAL);
771#else
772 written = write(data_pipe[1], buf, size);
773#endif
774
775 if (written < 0) {
776 char errorMsg[256];
777 Err("error write pipe (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
778 } else if (written != (ssize_t)size) {
779 Err("error write pipe %ld/%ld\n", written, size);
780 }
781}
782
783void *FrameworkManager_impl::write_log_user(void *arg) {
784 int cmd_pipe = -1;
785 int data_pipe = -1;
786 fd_set set;
787 struct timeval timeout;
788 FrameworkManager_impl *caller = (FrameworkManager_impl *)arg;
789 int rv;
790
791 vector<log_desc_t> logs;
792
793#ifdef __XENO__
794 while (cmd_pipe < 0) {
795 string filename = NRT_PIPE_PATH + caller->self->ObjectName() + "-log_cmd";
796 cmd_pipe = open(filename.c_str(), O_RDWR);
797 if (cmd_pipe < 0 && errno != ENOENT) {
798 char errorMsg[256];
799 caller->self->Err("open rt_pipe error: %s %s\n", filename.c_str(), strerror_r(errno, errorMsg, sizeof(errorMsg)));
800 }
801 usleep(1000);
802 }
803 while (data_pipe < 0) {
804 string filename = NRT_PIPE_PATH + caller->self->ObjectName() + "-log_data";
805 data_pipe = open(filename.c_str(), O_RDWR);
806 if (data_pipe < 0 && errno != ENOENT) {
807 char errorMsg[256];
808 caller->self->Err("open rt_pipe error: %s %s\n", filename.c_str(), strerror_r(errno, errorMsg, sizeof(errorMsg)));
809 }
810 usleep(1000);
811 }
812#else
813 cmd_pipe = caller->cmd_pipe[0];
814 data_pipe = caller->data_pipe[0];
815#endif
816
817 while (caller->continuer == true) {
818 FD_ZERO(&set);
819 FD_SET(cmd_pipe, &set);
820 FD_SET(data_pipe, &set);
821
822 timeout.tv_sec = 0;
823 timeout.tv_usec = SELECT_TIMEOUT_MS * 1000;
824 rv = select(FD_SETSIZE, &set, NULL, NULL, &timeout);
825
826 if (rv == -1) {
827 caller->Err("select error\n"); // an error accured
828 } else if (rv == 0) {
829 // printf("timeout write_log_user %s\n",caller->ObjectName().c_str()); //
830 // a timeout occured
831 } else {
832 if (FD_ISSET(cmd_pipe, &set)) {
833 log_desc_t tmp;
834 read(cmd_pipe, &tmp, sizeof(log_desc_t));
835
836 if (tmp.running == true) {// start logging
837 string filename = caller->log_path + "/" + caller->FileName(tmp.device) + ".dbt";
838 printf("Creating log file %s (log size %i)\n", filename.c_str(), (int)tmp.size);
839 tmp.dbtFile = inithdFile((char *)filename.c_str(), UAV, tmp.size);
840 logs.push_back(tmp);
841
842 if (logs.size() == 1) {
843 filename = caller->log_path + "/setup.xml";
844 xmlSaveFile(filename.c_str(), caller->file_doc);
845 }
846 } else {// stop logging
847 //disable watchdog temporarly
848 //this is necessary because GCS is no longer sending the heartbeat when receiving files...
849 //TODO: add a thread in GCS for receiving file
850 //but be careful that with a xbee modem for exemple, sending files can saturate communication and
851 //avoid the heartbeat to be received... so disabling watchdog is not a so bad option...
852 if(caller->gcs_watchdog!=NULL) {
853 caller->gcs_watchdog->SafeStop();
854 caller->gcs_watchdog->Join();
855 }
856 for (size_t i = 0; i < logs.size(); i++) {
857 if (logs.at(i).dbtFile != NULL) {
858 close_hdfile(logs.at(i).dbtFile);
859
860 string filename = caller->FileName(logs.at(i).device) + ".dbt";
861 caller->SendFile(caller->log_path, filename);
862
863 fstream txt_file;
864 filename = caller->FileName(logs.at(i).device) + ".txt";
865 txt_file.open((caller->log_path + "/" + filename).c_str(),
866 fstream::out);
867 txt_file << "1: time (us)\n2: time (ns)\n";
868 int index = 3;
869 logs.at(i).device->pimpl_->WriteLogsDescriptors(txt_file, &index);
870 txt_file.close();
871
872 caller->SendFile(caller->log_path, filename);
873 }
874 }
875 // a revoir celui ci est le xml enregistré et pas forcement l'actuel
876 // if(caller->xml_file!="") caller->SendFile(caller->xml_file);
877 caller->FinishSending();
878
879 logs.clear();
880 //enable watchdog again
881 if(caller->gcs_watchdog!=NULL) {
882 caller->gcs_watchdog->Start();
883 }
884 }
885 }
886
887 if (FD_ISSET(data_pipe, &set)) {
888 log_header_t header;
889 read(data_pipe, &header, sizeof(log_header_t));
890
891 for (size_t i = 0; i < logs.size(); i++) {
892 if (logs.at(i).device == header.device) {
893 char *buf = (char *)malloc(header.size);
894 read(data_pipe, buf, header.size);
895 // printf("%s \n",header.device->ObjectName().c_str());
896 // for(int i=0;i<header.size;i++) printf("%x ",buf[i]);
897 // printf("\n");
898 if (logs.at(i).size == header.size) {
899 if (logs.at(i).dbtFile != NULL) {
900 write_hdfile(
901 logs.at(i).dbtFile, buf, (road_time_t)(header.time / 1000),
902 (road_timerange_t)(header.time % 1000), header.size);
903 } else {
904 printf("err\n");
905 }
906 } else {
907 caller->self->Err("%s log size is not correct %i/%i\n",
908 header.device->ObjectName().c_str(),
909 header.size, logs.at(i).size);
910 }
911 free(buf);
912 }
913 }
914 }
915 }
916 }
917
918#ifdef __XENO__
919 close(cmd_pipe);
920 close(data_pipe);
921#endif
922
923 pthread_exit(0);
924}
925
926string FrameworkManager_impl::FileName(IODevice *device) {
927 return getFrameworkManager()->ObjectName() + "_" + device->ObjectName();
928}
929
930void FrameworkManager_impl::PrintXml(void) const {
931 xmlChar *xmlbuff;
932 int buffersize;
933 xmlDocDumpFormatMemory(file_doc, &xmlbuff, &buffersize, 1);
934 Printf("xml:\n%s\n", xmlbuff);
935 xmlFree(xmlbuff);
936}
Note: See TracBrowser for help on using the repository browser.