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

Last change on this file since 122 was 122, checked in by Sanahuja Guillaume, 8 years ago

modifs uav vrpn i686

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